diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml index 6bb07489ec..d7ed058fa3 100644 --- a/.azure-pipelines.yml +++ b/.azure-pipelines.yml @@ -58,6 +58,7 @@ jobs: - script: make test-extensions displayName: Run In-tree Extension tests - bash: | + set -e rm -rf extensions/telemetry make integration-win git checkout extensions/telemetry @@ -102,6 +103,7 @@ jobs: - script: make test-extensions displayName: Run In-tree Extension tests - bash: | + set -e rm -rf extensions/telemetry make integration-mac git checkout extensions/telemetry @@ -159,6 +161,7 @@ jobs: sudo chown -R $USER $HOME/.kube $HOME/.minikube displayName: Install integration test dependencies - bash: | + set -e rm -rf extensions/telemetry xvfb-run --auto-servernum --server-args='-screen 0, 1600x900x24' make integration-linux git checkout extensions/telemetry diff --git a/.eslintrc.js b/.eslintrc.js index 3fd52c2465..57ee07348f 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -46,6 +46,8 @@ module.exports = { "avoidEscape": true, "allowTemplateLiterals": true, }], + "linebreak-style": ["error", "unix"], + "eol-last": ["error", "always"], "semi": ["error", "always"], "object-shorthand": "error", "prefer-template": "error", @@ -101,6 +103,8 @@ module.exports = { }], "semi": "off", "@typescript-eslint/semi": ["error"], + "linebreak-style": ["error", "unix"], + "eol-last": ["error", "always"], "object-shorthand": "error", "prefer-template": "error", "template-curly-spacing": "error", @@ -162,6 +166,8 @@ module.exports = { }], "semi": "off", "@typescript-eslint/semi": ["error"], + "linebreak-style": ["error", "unix"], + "eol-last": ["error", "always"], "object-shorthand": "error", "prefer-template": "error", "template-curly-spacing": "error", diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 0c6340d6a2..afbcc74367 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -18,7 +18,7 @@ jobs: uses: actions/setup-python@v2 with: python-version: '3.x' - + - name: Checkout Release from lens uses: actions/checkout@v2 with: @@ -83,12 +83,12 @@ jobs: mike deploy --push master - name: Get the release version - if: contains(github.ref, 'refs/tags/v') # && !github.event.release.prerelease (generate pre-release docs until Lens 4.0.0 is GA, see #1408) + if: contains(github.ref, 'refs/tags/v') && !github.event.release.prerelease id: get_version run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//} - name: mkdocs deploy new release - if: contains(github.ref, 'refs/tags/v') # && !github.event.release.prerelease (generate pre-release docs until Lens 4.0.0 is GA, see #1408) + if: contains(github.ref, 'refs/tags/v') && !github.event.release.prerelease run: | mike deploy --push --update-aliases ${{ steps.get_version.outputs.VERSION }} latest mike set-default --push ${{ steps.get_version.outputs.VERSION }} diff --git a/__mocks__/imageMock.ts b/__mocks__/imageMock.ts index a099545376..f053ebf797 100644 --- a/__mocks__/imageMock.ts +++ b/__mocks__/imageMock.ts @@ -1 +1 @@ -module.exports = {}; \ No newline at end of file +module.exports = {}; diff --git a/__mocks__/styleMock.ts b/__mocks__/styleMock.ts index a099545376..f053ebf797 100644 --- a/__mocks__/styleMock.ts +++ b/__mocks__/styleMock.ts @@ -1 +1 @@ -module.exports = {}; \ No newline at end of file +module.exports = {}; diff --git a/docs/extensions/guides/images/clusterpagemenus.png b/docs/extensions/guides/images/clusterpagemenus.png new file mode 100644 index 0000000000..3ed1c79e5b Binary files /dev/null and b/docs/extensions/guides/images/clusterpagemenus.png differ diff --git a/docs/extensions/guides/images/globalpagemenus.png b/docs/extensions/guides/images/globalpagemenus.png new file mode 100644 index 0000000000..e986cc32e9 Binary files /dev/null and b/docs/extensions/guides/images/globalpagemenus.png differ diff --git a/docs/extensions/guides/renderer-extension.md b/docs/extensions/guides/renderer-extension.md index f64cb5fd49..c3ff953b2a 100644 --- a/docs/extensions/guides/renderer-extension.md +++ b/docs/extensions/guides/renderer-extension.md @@ -1,13 +1,26 @@ # Renderer Extension -The renderer extension api is the interface to Lens's renderer process (Lens runs in main and renderer processes). -It allows you to access, configure, and customize Lens data, add custom Lens UI elements, and generally run custom code in Lens's renderer process. -The custom Lens UI elements that can be added include global pages, cluster pages, cluster page menus, cluster features, app preferences, status bar items, KubeObject menu items, and KubeObject details items. -These UI elements are based on React components. +The Renderer Extension API is the interface to Lens's renderer process. Lens runs in both the main and renderer processes. The Renderer Extension API allows you to access, configure, and customize Lens data, add custom Lens UI elements, and run custom code in Lens's renderer process. + +The custom Lens UI elements that you can add include: + +* [Cluster pages](#clusterpages) +* [Cluster page menus](#clusterpagemenus) +* [Global pages](#globalpages) +* [Global page menus](#globalpagemenus) +* [Cluster features](#clusterfeatures) +* [App preferences](#apppreferences) +* [Status bar items](#statusbaritems) +* [KubeObject menu items](#kubeobjectmenuitems) +* [KubeObject detail items](#kubeobjectdetailitems) + +All UI elements are based on React components. ## `LensRendererExtension` Class -To create a renderer extension simply extend the `LensRendererExtension` class: +### `onActivate()` and `onDeactivate()` Methods + +To create a renderer extension, extend the `LensRendererExtension` class: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -23,21 +36,21 @@ export default class ExampleExtensionMain extends LensRendererExtension { } ``` -There are two methods that you can implement to facilitate running your custom code. -`onActivate()` is called when your extension has been successfully enabled. -By implementing `onActivate()` you can initiate your custom code. -`onDeactivate()` is called when the extension is disabled (typically from the [Lens Extensions Page]()) and when implemented gives you a chance to clean up after your extension, if necessary. -The example above simply logs messages when the extension is enabled and disabled. +Two methods enable you to run custom code: `onActivate()` and `onDeactivate()`. Enabling your extension calls `onActivate()` and disabling your extension calls `onDeactivate()`. You can initiate custom code by implementing `onActivate()`. Implementing `onDeactivate()` gives you the opportunity to clean up after your extension. + +!!! info + Disable extensions from the Lens Extensions page: + + 1. Navigate to **File** > **Extensions** in the top menu bar. (On Mac, it is **Lens** > **Extensions**.) + 2. Click **Disable** on the extension you want to disable. + +The example above logs messages when the extension is enabled and disabled. ### `clusterPages` -Cluster pages appear as part of the cluster dashboard. -They are accessible from the side bar, and are shown in the menu list after *Custom Resources*. -It is conventional to use a cluster page to show information or provide functionality pertaining to the active cluster, along with custom data and functionality your extension may have. -However, it is not limited to the active cluster. -Also, your extension can gain access to the Kubernetes resources in the active cluster in a straightforward manner using the [`clusterStore`](../stores#clusterstore). +Cluster pages appear in the cluster dashboard. Use cluster pages to display information about or add functionality to the active cluster. It is also possible to include custom details from other clusters. Use your extension to access Kubernetes resources in the active cluster with [`clusterStore`](../stores#clusterstore). -The following example adds a cluster page definition to a `LensRendererExtension` subclass: +Add a cluster page definition to a `LensRendererExtension` subclass with the following example: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -56,12 +69,13 @@ export default class ExampleExtension extends LensRendererExtension { } ``` -Cluster pages are objects matching the `PageRegistration` interface. -The `id` field identifies the page, and at its simplest is just a string identifier, as shown in the example above. -The 'id' field can also convey route path details, such as variable parameters provided to a page ([See example below]()). -The `components` field matches the `PageComponents` interface for wich there is one field, `Page`. -`Page` is of type ` React.ComponentType`, which gives you great flexibility in defining the appearance and behaviour of your page. -For the example above `ExamplePage` can be defined in `page.tsx`: +`clusterPages` is an array of objects that satisfy the `PageRegistration` interface. The properties of the `clusterPages` array objects are defined as follows: + +* `id` is a string that identifies the page. +* `components` matches the `PageComponents` interface for which there is one field, `Page`. +* `Page` is of type ` React.ComponentType`. It offers flexibility in defining the appearance and behavior of your page. + +`ExamplePage` in the example above can be defined in `page.tsx`: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -78,14 +92,15 @@ export class ExamplePage extends React.Component<{ extension: LensRendererExtens } ``` -Note that the `ExamplePage` class defines a property named `extension`. -This allows the `ExampleExtension` object to be passed in React-style in the cluster page definition, so that `ExamplePage` can access any `ExampleExtension` subclass data. +Note that the `ExamplePage` class defines the `extension` property. This allows the `ExampleExtension` object to be passed in the cluster page definition in the React style. This way, `ExamplePage` can access all `ExampleExtension` subclass data. + +The above example shows how to create a cluster page, but not how to make that page available to the Lens user. Use `clusterPageMenus`, covered in the next section, to add cluster pages to the Lens UI. ### `clusterPageMenus` -The above example code shows how to create a cluster page but not how to make it available to the Lens user. -Cluster pages are typically made available through a menu item in the cluster dashboard sidebar. -Expanding on the above example a cluster page menu is added to the `ExampleExtension` definition: +`clusterPageMenus` allows you to add cluster page menu items to the secondary left nav. + +By expanding on the above example, you can add a cluster page menu item to the `ExampleExtension` definition: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -114,14 +129,16 @@ export default class ExampleExtension extends LensRendererExtension { } ``` -Cluster page menus are objects matching the `ClusterPageMenuRegistration` interface. -They define the appearance of the cluster page menu item in the cluster dashboard sidebar and the behaviour when the cluster page menu item is activated (typically by a mouse click). -The example above uses the `target` field to set the behaviour as a link to the cluster page with `id` of `"hello"`. -This is done by setting `target`'s `pageId` field to `"hello"`. -The cluster page menu item's appearance is defined by setting the `title` field to the text that is to be displayed in the cluster dashboard sidebar. -The `components` field is used to set an icon that appears to the left of the `title` text in the sidebar. -Thus when the `"Hello World"` menu item is activated the cluster dashboard will show the contents of `ExamplePage`. -This example requires the definition of another React-based component, `ExampleIcon`, which has been added to `page.tsx`: +`clusterPageMenus` is an array of objects that satisfy the `ClusterPageMenuRegistration` interface. This element defines how the cluster page menu item will appear and what it will do when you click it. The properties of the `clusterPageMenus` array objects are defined as follows: + +* `target` links to the relevant cluster page using `pageId`. +* `pageId` takes the value of the relevant cluster page's `id` property. +* `title` sets the name of the cluster page menu item that will appear in the left side menu. +* `components` is used to set an icon that appears to the left of the `title` text in the left side menu. + +The above example creates a menu item that reads **Hello World**. When users click **Hello World**, the cluster dashboard will show the contents of `Example Page`. + +This example requires the definition of another React-based component, `ExampleIcon`, which has been added to `page.tsx`, as follows: ``` typescript import { LensRendererExtension, Component } from "@k8slens/extensions"; @@ -142,14 +159,13 @@ export class ExamplePage extends React.Component<{ extension: LensRendererExtens } ``` -`ExampleIcon` introduces one of Lens's built-in components available to extension developers, the `Component.Icon`. -Built in are the [Material Design](https://material.io) [icons](https://material.io/resources/icons/). -One can be selected by name via the `material` field. -`ExampleIcon` also sets a tooltip, shown when the Lens user hovers over the icon with a mouse, by setting the `tooltip` field. +Lens includes various built-in components available for extension developers to use. One of these is the `Component.Icon`, introduced in `ExampleIcon`, which you can use to access any of the [icons](https://material.io/resources/icons/) available at [Material Design](https://material.io). The properties that `Component.Icon` uses are defined as follows: + +* `material` takes the name of the icon you want to use. +* `tooltip` sets the text you want to appear when a user hovers over the icon. + +`clusterPageMenus` can also be used to define sub menu items, so that you can create groups of cluster pages. The following example groups two sub menu items under one parent menu item: -A cluster page menu can also be used to define a foldout submenu in the cluster dashboard sidebar. -This enables the grouping of cluster pages. -The following example shows how to specify a submenu having two menu items: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -200,24 +216,17 @@ export default class ExampleExtension extends LensRendererExtension { } ``` -The above defines two cluster pages and three cluster page menu objects. -The cluster page definitons are straightforward. -The first cluster page menu object defines the parent of a foldout submenu. -Setting the `id` field in a cluster page menu definition implies that it is defining a foldout submenu. -Also note that the `target` field is not specified (it is ignored if the `id` field is specified). -This cluster page menu object specifies the `title` and `components` fields, which are used in displaying the menu item in the cluster dashboard sidebar. -Initially the submenu is hidden. -Activating this menu item toggles on and off the appearance of the submenu below it. -The remaining two cluster page menu objects define the contents of the submenu. -A cluster page menu object is defined to be a submenu item by setting the `parentId` field to the id of the parent of a foldout submenu, `"example"` in this case +The above defines two cluster pages and three cluster page menu objects. The three cluster page menu objects include one parent menu item and two sub menu items. Parent items require an `id` value, whereas sub items require a `parentId` value. The value of the sub item `parentId` will match the value of the corresponding parent item `id`. Parent items don't require a `target` value. Assign values to the remaining properties as explained above. + +This is what the example will look like, including how the menu item will appear in the secondary left nav: + +![clusterPageMenus](images/clusterpagemenus.png) ### `globalPages` -Global pages appear independently of the cluster dashboard and they fill the Lens UI space. -A global page is typically triggered from the cluster menu using a [global page menu](#globalpagemenus). -They can also be triggered by a [custom app menu selection](../main-extension#appmenus) from a Main Extension or a [custom status bar item](#statusbaritems). -Global pages can appear even when there is no active cluster, unlike cluster pages. -It is conventional to use a global page to show information and provide functionality relevant across clusters, along with custom data and functionality that your extension may have. +Global pages are independent of the cluster dashboard and can fill the entire Lens UI. Their primary use is to display information and provide functionality across clusters, including customized data and functionality unique to your extension. + +Typically, you would use a [global page menu](#globalpagemenus) located in the left nav to trigger a global page. You can also trigger a global page with a [custom app menu selection](../main-extension#appmenus) from a Main Extension or a [custom status bar item](#statusbaritems). Unlike cluster pages, users can trigger global pages even when there is no active cluster. The following example defines a `LensRendererExtension` subclass with a single global page definition: @@ -238,12 +247,13 @@ export default class HelpExtension extends LensRendererExtension { } ``` -Global pages are objects matching the `PageRegistration` interface. -The `id` field identifies the page, and at its simplest is just a string identifier, as shown in the example above. -The 'id' field can also convey route path details, such as variable parameters provided to a page ([See example below]()). -The `components` field matches the `PageComponents` interface for which there is one field, `Page`. -`Page` is of type ` React.ComponentType`, which gives you great flexibility in defining the appearance and behaviour of your page. -For the example above `HelpPage` can be defined in `page.tsx`: +`globalPages` is an array of objects that satisfy the `PageRegistration` interface. The properties of the `globalPages` array objects are defined as follows: + +* `id` is a string that identifies the page. +* `components` matches the `PageComponents` interface for which there is one field, `Page`. +* `Page` is of type `React.ComponentType`. It offers flexibility in defining the appearance and behavior of your page. + +`HelpPage` in the example above can be defined in `page.tsx`: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -260,20 +270,19 @@ export class HelpPage extends React.Component<{ extension: LensRendererExtension } ``` -Note that the `HelpPage` class defines a property named `extension`. -This allows the `HelpExtension` object to be passed in React-style in the global page definition, so that `HelpPage` can access any `HelpExtension` subclass data. +Note that the `HelpPage` class defines the `extension` property. This allows the `HelpExtension` object to be passed in the global page definition in the React-style. This way, `HelpPage` can access all `HelpExtension` subclass data. -This example code shows how to create a global page but not how to make it available to the Lens user. -Global pages are typically made available through a number of ways. -Menu items can be added to the Lens app menu system and set to open a global page when activated (See [`appMenus` in the Main Extension guide](../main-extension#appmenus)). -Interactive elements can be placed on the status bar (the blue strip along the bottom of the Lens UI) and can be configured to link to a global page when activated (See [`statusBarItems`](#statusbaritems)). -As well, global pages can be made accessible from the cluster menu, which is the vertical strip along the left side of the Lens UI showing the available cluster icons, and the Add Cluster icon. -Global page menu icons that are defined using [`globalPageMenus`](#globalpagemenus) appear below the Add Cluster icon. +This example code shows how to create a global page, but not how to make that page available to the Lens user. Global pages can be made available in the following ways: + +* To add global pages to the top menu bar, see [`appMenus`](../main-extension#appmenus) in the Main Extension guide. +* To add global pages as an interactive element in the blue status bar along the bottom of the Lens UI, see [`statusBarItems`](#statusbaritems). +* To add global pages to the left side menu, see [`globalPageMenus`](#globalpagemenus). ### `globalPageMenus` -Global page menus connect a global page to the cluster menu, which is the vertical strip along the left side of the Lens UI showing the available cluster icons, and the Add Cluster icon. -Expanding on the example from [`globalPages`](#globalPages) a global page menu is added to the `HelpExtension` definition: +`globalPageMenus` allows you to add global page menu items to the left nav. + +By expanding on the above example, you can add a global page menu item to the `HelpExtension` definition: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -302,14 +311,16 @@ export default class HelpExtension extends LensRendererExtension { } ``` -Global page menus are objects matching the `PageMenuRegistration` interface. -They define the appearance of the global page menu item in the cluster menu and the behaviour when the global page menu item is activated (typically by a mouse click). -The example above uses the `target` field to set the behaviour as a link to the global page with `id` of `"help"`. -This is done by setting `target`'s `pageId` field to `"help"`. -The global page menu item's appearance is defined by setting the `title` field to the text that is to be displayed as a tooltip in the cluster menu. -The `components` field is used to set an icon that appears in the cluster menu. -Thus when the `"Help"` icon is activated the contents of `ExamplePage` will be shown. -This example requires the definition of another React-based component, `HelpIcon`, which has been added to `page.tsx`: +`globalPageMenus` is an array of objects that satisfy the `PageMenuRegistration` interface. This element defines how the global page menu item will appear and what it will do when you click it. The properties of the `globalPageMenus` array objects are defined as follows: + +* `target` links to the relevant global page using `pageId`. +* `pageId` takes the value of the relevant global page's `id` property. +* `title` sets the name of the global page menu item that will display as a tooltip in the left nav. +* `components` is used to set an icon that appears in the left nav. + +The above example creates a "Help" icon menu item. When users click the icon, the Lens UI will display the contents of `ExamplePage`. + +This example requires the definition of another React-based component, `HelpIcon`. Update `page.tsx` from the example above with the `HelpIcon` definition, as follows: ``` typescript import { LensRendererExtension, Component } from "@k8slens/extensions"; @@ -330,14 +341,21 @@ export class HelpPage extends React.Component<{ extension: LensRendererExtension } ``` -`HelpIcon` introduces one of Lens's built-in components available to extension developers, the `Component.Icon`. -Built in are the [Material Design](https://material.io) [icons](https://material.io/resources/icons/). -One can be selected by name via the `material` field. +Lens includes various built-in components available for extension developers to use. One of these is the `Component.Icon`, introduced in `HelpIcon`, which you can use to access any of the [icons](https://material.io/resources/icons/) available at [Material Design](https://material.io). The property that `Component.Icon` uses is defined as follows: + +* `material` takes the name of the icon you want to use. + +This is what the example will look like, including how the menu item will appear in the left nav: + +![globalPageMenus](images/globalpagemenus.png) ### `clusterFeatures` Cluster features are Kubernetes resources that can be applied to and managed within the active cluster. -They can be installed/uninstalled by the Lens user from the [cluster settings page](). +They can be installed and uninstalled by the Lens user from the cluster **Settings** page. + +!!! info + To access the cluster **Settings** page, right-click the relevant cluster in the left side menu and click **Settings**. The following example shows how to add a cluster feature as part of a `LensRendererExtension`: @@ -364,8 +382,11 @@ export default class ExampleFeatureExtension extends LensRendererExtension { ]; } ``` -The `title` and `components.Description` fields provide content that appears on the cluster settings page, in the **Features** section. -The `feature` field must specify an instance which extends the abstract class `ClusterFeature.Feature`, and specifically implement the following methods: + +The properties of the `clusterFeatures` array objects are defined as follows: + +* `title` and `components.Description` provide content that appears on the cluster settings page, in the **Features** section. +* `feature` specifies an instance which extends the abstract class `ClusterFeature.Feature`, and specifically implements the following methods: ``` typescript abstract install(cluster: Cluster): Promise; @@ -374,20 +395,21 @@ The `feature` field must specify an instance which extends the abstract class `C abstract updateStatus(cluster: Cluster): Promise; ``` -The `install()` method is typically called by Lens when a user has indicated that this feature is to be installed (i.e. clicked **Install** for the feature on the cluster settings page). -The implementation of this method should install kubernetes resources using the `applyResources()` method, or by directly accessing the kubernetes api ([`K8sApi`](tbd)). +The four methods listed above are defined as follows: -The `upgrade()` method is typically called by Lens when a user has indicated that this feature is to be upgraded (i.e. clicked **Upgrade** for the feature on the cluster settings page). -The implementation of this method should upgrade the kubernetes resources already installed, if relevant to the feature. +* The `install()` method installs Kubernetes resources using the `applyResources()` method, or by directly accessing the [Kubernetes API](../api/README.md). This method is typically called when a user indicates that they want to install the feature (i.e., by clicking **Install** for the feature in the cluster settings page). -The `uninstall()` method is typically called by Lens when a user has indicated that this feature is to be uninstalled (i.e. clicked **Uninstall** for the feature on the cluster settings page). -The implementation of this method should uninstall kubernetes resources using the kubernetes api (`K8sApi`) +* The `upgrade()` method upgrades the Kubernetes resources already installed, if they are relevant to the feature. This method is typically called when a user indicates that they want to upgrade the feature (i.e., by clicking **Upgrade** for the feature in the cluster settings page). -The `updateStatus()` method is called periodically by Lens to determine details about the feature's current status. -The implementation of this method should provide the current status information in the `status` field of the `ClusterFeature.Feature` parent class. -The `status.currentVersion` and `status.latestVersion` fields may be displayed by Lens in describing the feature. -The `status.installed` field should be set to true if the feature is currently installed, otherwise false. -Also, Lens relies on the `status.canUpgrade` field to determine if the feature can be upgraded (i.e a new version could be available) so the implementation should set the `status.canUpgrade` field according to specific rules for the feature, if relevant. +* The `uninstall()` method uninstalls Kubernetes resources using the [Kubernetes API](../api/README.md). This method is typically called when a user indicates that they want to uninstall the feature (i.e., by clicking **Uninstall** for the feature in the cluster settings page). + +* The `updateStatus()` method provides the current status information in the `status` field of the `ClusterFeature.Feature` parent class. Lens periodically calls this method to determine details about the feature's current status. Consider using the following properties with `updateStatus()`: + + * `status.currentVersion` and `status.latestVersion` may be displayed by Lens in the feature's description. + + * `status.installed` should be set to `true` if the feature is installed, and `false` otherwise. + + * `status.canUpgrade` is set according to a rule meant to determine whether the feature can be upgraded. This rule can involve `status.currentVersion` and `status.latestVersion`, if desired. The following shows a very simple implementation of a `ClusterFeature`: @@ -435,9 +457,9 @@ export class ExampleFeature extends ClusterFeature.Feature { } ``` -This example implements the `install()` method by simply invoking the helper `applyResources()` method. +This example implements the `install()` method by invoking the helper `applyResources()` method. `applyResources()` tries to apply all resources read from all files found in the folder path provided. -In this case this folder path is the `../resources` subfolder relative to current source code's folder. +In this case the folder path is the `../resources` subfolder relative to the current source code's folder. The file `../resources/example-pod.yml` could contain: ``` yaml @@ -451,18 +473,18 @@ spec: image: nginx ``` -The `upgrade()` method in the example above is implemented by simply invoking the `install()` method. -Depending on the feature to be supported by an extension, upgrading may require additional and/or different steps. +The example above implements the four methods as follows: -The `uninstall()` method is implemented in the example above by utilizing the [`K8sApi`](tbd) provided by Lens to simply delete the `example-pod` pod applied by the `install()` method. +* It implements `upgrade()` by invoking the `install()` method. Depending on the feature to be supported by an extension, upgrading may require additional and/or different steps. -The `updateStatus()` method is implemented above by using the [`K8sApi`](tbd) as well, this time to get information from the `example-pod` pod, in particular to determine if it is installed, what version is associated with it, and if it can be upgraded. -How the status is updated for a specific cluster feature is up to the implementation. +* It implements `uninstall()` by utilizing the [Kubernetes API](../api/README.md) which Lens provides to delete the `example-pod` applied by the `install()` method. + +* It implements `updateStatus()` by using the [Kubernetes API](../api/README.md) which Lens provides to determine whether the `example-pod` is installed, what version is associated with it, and whether it can be upgraded. The implementation determines what the status is for a specific cluster feature. ### `appPreferences` -The Preferences page is a built-in global page. -Extensions can add custom preferences to the Preferences page, thus providing a single location for users to configure global options, for Lens and extensions alike. +The Lens **Preferences** page is a built-in global page. You can use Lens extensions to add custom preferences to the Preferences page, providing a single location for users to configure global options. + The following example demonstrates adding a custom preference: ``` typescript @@ -487,13 +509,20 @@ export default class ExampleRendererExtension extends LensRendererExtension { } ``` -App preferences are objects matching the `AppPreferenceRegistration` interface. -The `title` field specifies the text to show as the heading on the Preferences page. -The `components` field specifies two `React.Component` objects defining the interface for the preference. -`Input` should specify an interactive input element for your preference and `Hint` should provide descriptive information for the preference, which is shown below the `Input` element. -`ExamplePreferenceInput` expects its React props set to an `ExamplePreferenceProps` instance, which is how `ExampleRendererExtension` handles the state of the preference input. -`ExampleRendererExtension` has the field `preference`, which is provided to `ExamplePreferenceInput` when it is created. -In this example `ExamplePreferenceInput`, `ExamplePreferenceHint`, and `ExamplePreferenceProps` are defined in `./src/example-preference.tsx`: +`appPreferences` is an array of objects that satisfies the `AppPreferenceRegistration` interface. The properties of the `appPreferences` array objects are defined as follows: + +* `title` sets the heading text displayed on the Preferences page. +* `components` specifies two `React.Component` objects that define the interface for the preference. + * `Input` specifies an interactive input element for the preference. + * `Hint` provides descriptive information for the preference, shown below the `Input` element. + +!!! note + Note that the input and the hint can be comprised of more sophisticated elements, according to the needs of the extension. + +`ExamplePreferenceInput` expects its React props to be set to an `ExamplePreferenceProps` instance. This is how `ExampleRendererExtension` handles the state of the preference input. +`ExampleRendererExtension` has a `preference` field, which you will add to `ExamplePreferenceInput`. + +In this example `ExamplePreferenceInput`, `ExamplePreferenceHint`, and `ExamplePreferenceProps` are defined in `./src/example-preference.tsx` as follows: ``` typescript import { Component } from "@k8slens/extensions"; @@ -530,28 +559,26 @@ export class ExamplePreferenceHint extends React.Component { } ``` -`ExamplePreferenceInput` implements a simple checkbox (using Lens's `Component.Checkbox`). -It provides `label` as the text to display next to the checkbox and an `onChange` function, which reacts to the checkbox state change. -The checkbox's `value` is initially set to `preference.enabled`. -`ExamplePreferenceInput` is defined with React props of `ExamplePreferenceProps` type, which is an object with a single field, `enabled`. -This is used to indicate the state of the preference, and is bound to the checkbox state in `onChange`. +`ExamplePreferenceInput` implements a simple checkbox using Lens's `Component.Checkbox` using the following properties: + +* `label` sets the text that displays next to the checkbox. +* `value` is initially set to `preference.enabled`. +* `onChange` is a function that responds when the state of the checkbox changes. + +`ExamplePreferenceInput` is defined with the `ExamplePreferenceProps` React props. This is an object with the single `enabled` property. It is used to indicate the state of the preference, and it is bound to the checkbox state in `onChange`. + `ExamplePreferenceHint` is a simple text span. -Note that the input and the hint could comprise of more sophisticated elements, according to the needs of the extension. -Note that the above example introduces decorators `observable` and `observer` from the [`mobx`](https://mobx.js.org/README.html) and [`mobx-react`](https://github.com/mobxjs/mobx-react#mobx-react) packages. -`mobx` simplifies state management and without it this example would not visually update the checkbox properly when the user activates it. -[Lens uses `mobx` extensively for state management](../working-with-mobx) of its own UI elements and it is recommended that extensions rely on it too. -Alternatively, React's state management can be used, though `mobx` is typically simpler to use. +The above example introduces the decorators `observable` and `observer` from the [`mobx`](https://mobx.js.org/README.html) and [`mobx-react`](https://github.com/mobxjs/mobx-react#mobx-react) packages. `mobx` simplifies state management. Without it, this example would not visually update the checkbox properly when the user activates it. [Lens uses `mobx`](../working-with-mobx) extensively for state management of its own UI elements. We recommend that extensions rely on it, as well. +Alternatively, you can use React's state management, though `mobx` is typically simpler to use. -Also note that an extension's state data can be managed using an `ExtensionStore` object, which conveniently handles persistence and synchronization. -The example above defined a `preference` field in the `ExampleRendererExtension` class definition to hold the extension's state primarily to simplify the code for this guide, but it is recommended to manage your extension's state data using [`ExtensionStore`](../stores#extensionstore) +Note that you can manage an extension's state data using an `ExtensionStore` object, which conveniently handles persistence and synchronization. To simplify this guide, the example above defines a `preference` field in the `ExampleRendererExtension` class definition to hold the extension's state. However, we recommend that you manage your extension's state data using [`ExtensionStore`](../stores#extensionstore). ### `statusBarItems` -The Status bar is the blue strip along the bottom of the Lens UI. -Status bar items are `React.ReactNode` types, which can be used to convey status information, or act as a link to a global page, or even an external page. +The status bar is the blue strip along the bottom of the Lens UI. `statusBarItems` are `React.ReactNode` types. They can be used to display status information, or act as links to global pages as well as external pages. -The following example adds a status bar item definition, as well as a global page definition, to a `LensRendererExtension` subclass, and configures the status bar item to navigate to the global page upon activation (normally a mouse click): +The following example adds a `statusBarItems` definition and a `globalPages` definition to a `LensRendererExtension` subclass. It configures the status bar item to navigate to the global page upon activation (normally a mouse click): ``` typescript import { LensRendererExtension } from '@k8slens/extensions'; @@ -584,23 +611,23 @@ export default class HelpExtension extends LensRendererExtension { } ``` -The `item` field of a status bar item specifies the `React.Component` to be shown on the status bar. -By default items are added starting from the right side of the status bar. -Typically, `item` would specify an icon and/or a short string of text, considering the limited space on the status bar. -In the example above the `HelpIcon` from the [`globalPageMenus` guide](#globalpagemenus) is reused. -Also, the `item` provides a link to the global page by setting the `onClick` property to a function that calls the `LensRendererExtension` `navigate()` method. -`navigate()` takes as a parameter the id of the global page, which is shown when `navigate()` is called. +The properties of the `statusBarItems` array objects are defined as follows: + +* `item` specifies the `React.Component` that will be shown on the status bar. By default, items are added starting from the right side of the status bar. Due to limited space in the status bar, `item` will typically specify only an icon or a short string of text. The example above reuses the `HelpIcon` from the [`globalPageMenus` guide](#globalpagemenus). +* `onClick` determines what the `statusBarItem` does when it is clicked. In the example, `onClick` is set to a function that calls the `LensRendererExtension` `navigate()` method. `navigate` takes the `id` of the associated global page as a parameter. Thus, clicking the status bar item activates the associated global pages. ### `kubeObjectMenuItems` -An extension can add custom menu items (including actions) for specific Kubernetes resource kinds/apiVersions. -These menu items appear under the `...` for each listed resource in the cluster dashboard, and on the title bar of the details page for a specific resource: +An extension can add custom menu items (`kubeObjectMenuItems`) for specific Kubernetes resource kinds and apiVersions. +`kubeObjectMenuItems` appear under the vertical ellipsis for each listed resource in the cluster dashboard: ![List](images/kubeobjectmenuitem.png) +They also appear on the title bar of the details page for specific resources: + ![Details](images/kubeobjectmenuitemdetail.png) -The following example shows how to add a menu for Namespace resources, and associate an action with it: +The following example shows how to add a `kubeObjectMenuItems` for namespace resources with an associated action: ``` typescript import React from "react" @@ -621,12 +648,13 @@ export default class ExampleExtension extends LensRendererExtension { ``` -Kube object menu items are objects matching the `KubeObjectMenuRegistration` interface. -The `kind` field specifies the kubernetes resource type to apply this menu item to, and the `apiVersion` field specifies the kubernetes api to use in relation to this resource type. -This example adds a menu item for namespaces in the cluster dashboard. -The `components` field defines the menu item's appearance and behaviour. -The `MenuItem` field provides a function that returns a `React.Component` given a set of menu item properties. -In this example a `NamespaceMenuItem` object is returned. +`kubeObjectMenuItems` is an array of objects matching the `KubeObjectMenuRegistration` interface. The example above adds a menu item for namespaces in the cluster dashboard. The properties of the `kubeObjectMenuItems` array objects are defined as follows: + +* `kind` specifies the Kubernetes resource type the menu item will apply to. +* `apiVersion` specifies the Kubernetes API version number to use with the resource type. +* `components` defines the menu item's appearance and behavior. +* `MenuItem` provides a function that returns a `React.Component` given a set of menu item properties. In this example a `NamespaceMenuItem` object is returned. + `NamespaceMenuItem` is defined in `./src/namespace-menu-item.tsx`: ```typescript @@ -661,22 +689,18 @@ export function NamespaceMenuItem(props: Component.KubeObjectMenuProps>` it can access the current namespace object (type `K8sApi.Namespace`) through `this.props.object`. -This object can be queried for many details about the current namespace. -In this example the namespace's name is obtained in `componentDidMount()` using the `K8sApi.Namespace` `getName()` method. -The namespace's name is needed to limit the list of pods to only those in this namespace. -To get the list of pods this example uses the kubernetes pods api, specifically the `K8sApi.podsApi.list()` method. -The `K8sApi.podsApi` is automatically configured for the currently active cluster. +Since `NamespaceDetailsItem` extends `React.Component>`, it can access the current namespace object (type `K8sApi.Namespace`) through `this.props.object`. You can query this object for many details about the current namespace. In the example above, `componentDidMount()` gets the namespace's name using the `K8sApi.Namespace` `getName()` method. Use the namespace's name to limit the list of pods only to those in the relevant namespace. To get this list of pods, this example uses the Kubernetes pods API `K8sApi.podsApi.list()` method. The `K8sApi.podsApi` is automatically configured for the active cluster. -Note that `K8sApi.podsApi.list()` is an asynchronous method, and ideally getting the pods list should be done before rendering the `NamespaceDetailsItem`. -It is a common technique in React development to await async calls in `componentDidMount()`. -However, `componentDidMount()` is called right after the first call to `render()`. -In order to effect a subsequent `render()` call React must be made aware of a state change. -Like in the [`appPreferences` guide](#apppreferences), [`mobx`](https://mobx.js.org/README.html) and [`mobx-react`](https://github.com/mobxjs/mobx-react#mobx-react) are used to ensure `NamespaceDetailsItem` renders when the pods list is updated. -This is done simply by marking the `pods` field as an `observable` and the `NamespaceDetailsItem` class itself as an `observer`. +Note that `K8sApi.podsApi.list()` is an asynchronous method. Getting the pods list should occur prior to rendering the `NamespaceDetailsItem`. It is a common technique in React development to await async calls in `componentDidMount()`. However, `componentDidMount()` is called right after the first call to `render()`. In order to effect a subsequent `render()` call, React must be made aware of a state change. Like in the [`appPreferences` guide](#apppreferences), [`mobx`](https://mobx.js.org/README.html) and [`mobx-react`](https://github.com/mobxjs/mobx-react#mobx-react) are used to ensure `NamespaceDetailsItem` renders when the pods list updates. This is done simply by marking the `pods` field as an `observable` and the `NamespaceDetailsItem` class itself as an `observer`. -Finally, the `NamespaceDetailsItem` is rendered using the `render()` method. +Finally, the `NamespaceDetailsItem` renders using the `render()` method. Details are placed in drawers, and using `Component.DrawerTitle` provides a separator from details above this one. Multiple details in a drawer can be placed in `` elements for further separation, if desired. The rest of this example's details are defined in `PodsDetailsList`, found in `./pods-details-list.tsx`: @@ -800,6 +815,9 @@ export class PodsDetailsList extends React.Component { ![DetailsWithPods](images/kubeobjectdetailitemwithpods.png) - For each pod the name, age, and status are obtained using the `K8sApi.Pod` methods. +Obtain the name, age, and status for each pod using the `K8sApi.Pod` methods. Construct the table using the `Component.Table` and related elements. + + +For each pod the name, age, and status are obtained using the `K8sApi.Pod` methods. The table is constructed using the `Component.Table` and related elements. -See [`Component` documentation](url?) for further details. \ No newline at end of file +See [`Component` documentation](https://docs.k8slens.dev/master/extensions/api/modules/_renderer_api_components_/) for further details. \ No newline at end of file diff --git a/docs/extensions/guides/stores.md b/docs/extensions/guides/stores.md index 981a7cda3e..0319ee0aab 100644 --- a/docs/extensions/guides/stores.md +++ b/docs/extensions/guides/stores.md @@ -1,18 +1,16 @@ # Stores -Stores are components that persist and synchronize state data. Lens utilizes a number of stores for maintaining a variety of state information. -A few of these are exposed by the extensions api for use by the extension developer. +Stores are components that persist and synchronize state data. Lens uses a number of stores to maintain various kinds of state information, including: -- The `ClusterStore` manages cluster state data such as cluster details, and which cluster is active. -- The `WorkspaceStore` similarly manages workspace state data, such as workspace name, and which clusters belong to a given workspace. -- The `ExtensionStore` is a store for managing custom extension state data. +* The `ClusterStore` manages cluster state data (such as cluster details), and it tracks which cluster is active. +* The `WorkspaceStore` manages workspace state data (such as the workspace name), and and it tracks which clusters belong to a given workspace. +* The `ExtensionStore` manages custom extension state data. + +This guide focuses on the `ExtensionStore`. ## ExtensionStore -Extension developers can create their own store for managing state data by extending the `ExtensionStore` class. -This guide shows how to create a store for the [`appPreferences` guide example](../renderer-extension#apppreferences), which demonstrates how to add a custom preference to the Preferences page. -The preference is a simple boolean that indicates whether something is enabled or not. -The problem with that example is that the enabled state is not stored anywhere, and reverts to the default the next time Lens is started. +Extension developers can create their own store for managing state data by extending the `ExtensionStore` class. This guide shows how to create a store for the [`appPreferences`](../renderer-extension#apppreferences) guide example, which demonstrates how to add a custom preference to the **Preferences** page. The preference is a simple boolean that indicates whether or not something is enabled. However, in the example, the enabled state is not stored anywhere, and it reverts to the default when Lens is restarted. The following example code creates a store for the `appPreferences` guide example: @@ -53,25 +51,14 @@ export class ExamplePreferencesStore extends Store.ExtensionStore(); ``` -First the extension's data model is defined using a simple type, `ExamplePreferencesModel`, which has a single field, `enabled`, representing the preference's state. -`ExamplePreferencesStore` extends `Store.ExtensionStore`, based on the `ExamplePreferencesModel`. -The field `enabled` is added to the `ExamplePreferencesStore` class to hold the "live" or current state of the preference. -Note the use of the `observer` decorator on the `enabled` field. -As for the [`appPreferences` guide example](../renderer-extension#apppreferences), [`mobx`](https://mobx.js.org/README.html) is used for the UI state management, ensuring the checkbox updates when activated by the user. +First, our example defines the extension's data model using the simple `ExamplePreferencesModel` type. This has a single field, `enabled`, which represents the preference's state. `ExamplePreferencesStore` extends `Store.ExtensionStore`, which is based on the `ExamplePreferencesModel`. The `enabled` field is added to the `ExamplePreferencesStore` class to hold the "live" or current state of the preference. Note the use of the `observable` decorator on the `enabled` field. The [`appPreferences`](../renderer-extension#apppreferences) guide example uses [MobX](https://mobx.js.org/README.html) for the UI state management, ensuring the checkbox updates when it's activated by the user. -Then the constructor and two abstract methods are implemented. -In the constructor, the name of the store (`"example-preferences-store"`), and the default (initial) value for the preference state (`enabled: false`) are specified. -The `fromStore()` method is called by Lens internals when the store is loaded, and gives the extension the opportunity to retrieve the stored state data values based on the defined data model. -Here, the `enabled` field of the `ExamplePreferencesStore` is set to the value from the store whenever `fromStore()` is invoked. -The `toJSON()` method is complementary to `fromStore()`, and is called when the store is being saved. -`toJSON()` must provide a JSON serializable object, facilitating its storage in JSON format. -The `toJS()` function from [`mobx`](https://mobx.js.org/README.html) is convenient for this purpose, and is used here. +Next, our example implements the constructor and two abstract methods. The constructor specifies the name of the store (`"example-preferences-store"`) and the default (initial) value for the preference state (`enabled: false`). Lens internals call the `fromStore()` method when the store loads. It gives the extension the opportunity to retrieve the stored state data values based on the defined data model. The `enabled` field of the `ExamplePreferencesStore` is set to the value from the store whenever `fromStore()` is invoked. The `toJSON()` method is complementary to `fromStore()`. It is called when the store is being saved. +`toJSON()` must provide a JSON serializable object, facilitating its storage in JSON format. The `toJS()` function from [`mobx`](https://mobx.js.org/README.html) is convenient for this purpose, and is used here. -Finally, `examplePreferencesStore` is created by calling `ExamplePreferencesStore.getInstance()`, and exported for use by other parts of the extension. -Note that `examplePreferencesStore` is a singleton, calling this function again will not create a new store. +Finally, `examplePreferencesStore` is created by calling `ExamplePreferencesStore.getInstance()`, and exported for use by other parts of the extension. Note that `examplePreferencesStore` is a singleton. Calling this function again will not create a new store. -The following example code, modified from the [`appPreferences` guide example](../renderer-extension#apppreferences) demonstrates how to use the extension store. -`examplePreferencesStore` must be loaded in the main process, where loaded stores are automatically saved when exiting Lens. This can be done in `./main.ts`: +The following example code, modified from the [`appPreferences`](../renderer-extension#apppreferences) guide demonstrates how to use the extension store. `examplePreferencesStore` must be loaded in the main process, where loaded stores are automatically saved when exiting Lens. This can be done in `./main.ts`: ``` typescript import { LensMainExtension } from "@k8slens/extensions"; @@ -84,8 +71,8 @@ export default class ExampleMainExtension extends LensMainExtension { } ``` -Here, `examplePreferencesStore` is loaded with `examplePreferencesStore.loadExtension(this)`, which is conveniently called from the `onActivate()` method of `ExampleMainExtension`. -Similarly, `examplePreferencesStore` must be loaded in the renderer process where the `appPreferences` are handled. This can be done in `./renderer.ts`: +Here, `examplePreferencesStore` loads with `examplePreferencesStore.loadExtension(this)`, which is conveniently called from the `onActivate()` method of `ExampleMainExtension`. +Similarly, `examplePreferencesStore` must load in the renderer process where the `appPreferences` are handled. This can be done in `./renderer.ts`: ``` typescript import { LensRendererExtension } from "@k8slens/extensions"; @@ -111,8 +98,7 @@ export default class ExampleRendererExtension extends LensRendererExtension { } ``` -Again, `examplePreferencesStore.loadExtension(this)` is called to load `examplePreferencesStore`, this time from the `onActivate()` method of `ExampleRendererExtension`. -Also, there is no longer the need for the `preference` field in the `ExampleRendererExtension` class, as the props for `ExamplePreferenceInput` is now `examplePreferencesStore`. +Again, `examplePreferencesStore.loadExtension(this)` is called to load `examplePreferencesStore`, this time from the `onActivate()` method of `ExampleRendererExtension`. There is no longer the need for the `preference` field in the `ExampleRendererExtension` class because the props for `ExamplePreferenceInput` is now `examplePreferencesStore`. `ExamplePreferenceInput` is defined in `./src/example-preference.tsx`: ``` typescript @@ -151,5 +137,5 @@ export class ExamplePreferenceHint extends React.Component { ``` The only change here is that `ExamplePreferenceProps` defines its `preference` field as an `ExamplePreferencesStore` type. -Everything else works as before except now the `enabled` state persists across Lens restarts because it is managed by the +Everything else works as before, except that now the `enabled` state persists across Lens restarts because it is managed by the `examplePreferencesStore`. \ No newline at end of file diff --git a/docs/extensions/guides/working-with-mobx.md b/docs/extensions/guides/working-with-mobx.md index 5577ff6bdc..41ddc487a6 100644 --- a/docs/extensions/guides/working-with-mobx.md +++ b/docs/extensions/guides/working-with-mobx.md @@ -1,23 +1,26 @@ -# Working with mobx +# Working with MobX ## Introduction -Lens uses `mobx` as its state manager on top of React's state management system. -This helps with having a more declarative style of managing state, as opposed to `React`'s native `setState` mechanism. -You should already have a basic understanding of how `React` handles state ([read here](https://reactjs.org/docs/faq-state.html) for more information). -However, if you do not, here is a quick overview. +Lens uses MobX on top of React's state management system. +The result is a more declarative state management style, rather than React's native `setState` mechanism. -- A `React.Component` is generic over both `Props` and `State` (with default empty object types). -- `Props` should be considered read-only from the point of view of the component and is the mechanism for passing in "arguments" to a component. -- `State` is a component's internal state and can be read by accessing the parent field `state`. -- `State` **must** be updated using the `setState` parent method which merges the new data with the old state. -- `React` does do some optimizations around re-rendering components after quick successions of `setState` calls. +You can review how React handles state management [here](https://reactjs.org/docs/faq-state.html). -## How mobx works: +The following is a quick overview: -`mobx` is a package that provides an abstraction over `React`'s state management. The three main concepts are: -- `observable`: data stored in the component's `state` -- `action`: a function that modifies any `observable` data -- `computed`: data that is derived from `observable` data but is not actually stored. Think of this as computing `isEmpty` vs an `observable` field called `count`. +* `React.Component` is generic with respect to both `props` and `state` (which default to the empty object type). +* `props` should be considered read-only from the point of view of the component, and it is the mechanism for passing in arguments to a component. +* `state` is a component's internal state, and can be read by accessing the super-class field `state`. +* `state` **must** be updated using the `setState` parent method which merges the new data with the old state. +* React does some optimizations around re-rendering components after quick successions of `setState` calls. -Further reading is available from `mobx`'s [website](https://mobx.js.org/the-gist-of-mobx.html). +## How MobX Works: + +MobX is a package that provides an abstraction over React's state management system. The three main concepts are: + +* `observable` is a marker for data stored in the component's `state`. +* `action` is a function that modifies any `observable` data. +* `computed` is a marker for data that is derived from `observable` data, but that is not actually stored. Think of this as computing `isEmpty` rather than an observable field called `count`. + +Further reading is available on the [MobX website](https://mobx.js.org/the-gist-of-mobx.html). diff --git a/extensions/kube-object-event-status/src/resolver.tsx b/extensions/kube-object-event-status/src/resolver.tsx index 69691c2e79..5e9151288f 100644 --- a/extensions/kube-object-event-status/src/resolver.tsx +++ b/extensions/kube-object-event-status/src/resolver.tsx @@ -56,4 +56,4 @@ export function resolveStatusForCronJobs(cronJob: K8sApi.CronJob): K8sApi.KubeOb text: `${event.message}`, timestamp: event.metadata.creationTimestamp }; -} \ No newline at end of file +} diff --git a/integration/__tests__/app.tests.ts b/integration/__tests__/app.tests.ts index 7182a13107..c986e4804e 100644 --- a/integration/__tests__/app.tests.ts +++ b/integration/__tests__/app.tests.ts @@ -5,8 +5,11 @@ cluster and vice versa. */ import { Application } from "spectron"; -import * as util from "../helpers/utils"; -import { spawnSync } from "child_process"; +import * as utils from "../helpers/utils"; +import { spawnSync, exec } from "child_process"; +import * as util from "util"; + +export const promiseExec = util.promisify(exec); jest.setTimeout(60000); @@ -16,7 +19,7 @@ describe("Lens integration tests", () => { const BACKSPACE = "\uE003"; let app: Application; const appStart = async () => { - app = util.setup(); + app = utils.setup(); await app.start(); // Wait for splash screen to be closed while (await app.client.getWindowCount() > 1); @@ -71,7 +74,7 @@ describe("Lens integration tests", () => { afterAll(async () => { if (app?.isRunning()) { - await util.tearDown(app); + await utils.tearDown(app); } }); @@ -93,7 +96,10 @@ describe("Lens integration tests", () => { }); it("ensures helm repos", async () => { - await app.client.waitUntilTextExists("div.repos #message-bitnami", "bitnami"); // wait for the helm-cli to fetch the bitnami repo + const { stdout: reposJson } = await promiseExec("helm repo list -o json"); + const repos = JSON.parse(reposJson); + + await app.client.waitUntilTextExists("div.repos #message-bitnami", repos[0].name); // wait for the helm-cli to fetch the repo(s) await app.client.click("#HelmRepoSelect"); // click the repo select to activate the drop-down await app.client.waitUntilTextExists("div.Select__option", ""); // wait for at least one option to appear (any text) }); @@ -105,12 +111,12 @@ describe("Lens integration tests", () => { }); }); - util.describeIf(ready)("workspaces", () => { + utils.describeIf(ready)("workspaces", () => { beforeAll(appStart, 20000); afterAll(async () => { if (app && app.isRunning()) { - return util.tearDown(app); + return utils.tearDown(app); } }); @@ -169,7 +175,7 @@ describe("Lens integration tests", () => { await app.client.waitUntilTextExists("span.link-text", "Cluster"); }; - util.describeIf(ready)("cluster tests", () => { + utils.describeIf(ready)("cluster tests", () => { let clusterAdded = false; const addCluster = async () => { await clickWhatsNew(app); @@ -184,7 +190,7 @@ describe("Lens integration tests", () => { afterAll(async () => { if (app && app.isRunning()) { - return util.tearDown(app); + return utils.tearDown(app); } }); @@ -207,7 +213,7 @@ describe("Lens integration tests", () => { afterAll(async () => { if (app && app.isRunning()) { - return util.tearDown(app); + return utils.tearDown(app); } }); @@ -489,7 +495,7 @@ describe("Lens integration tests", () => { afterEach(async () => { if (app && app.isRunning()) { - return util.tearDown(app); + return utils.tearDown(app); } }); @@ -523,7 +529,7 @@ describe("Lens integration tests", () => { afterEach(async () => { if (app && app.isRunning()) { - return util.tearDown(app); + return utils.tearDown(app); } }); diff --git a/mkdocs.yml b/mkdocs.yml index ad3e19572e..dd72a677ea 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -34,7 +34,7 @@ nav: - Main Extension: extensions/guides/main-extension.md - Renderer Extension: extensions/guides/renderer-extension.md - Stores: extensions/guides/stores.md - - Working with mobx: extensions/guides/working-with-mobx.md + - Working with MobX: extensions/guides/working-with-mobx.md - Testing and Publishing: - Testing Extensions: extensions/testing-and-publishing/testing.md - Publishing Extensions: extensions/testing-and-publishing/publishing.md @@ -81,6 +81,8 @@ markdown_extensions: - toc: permalink: "#" toc_depth: 3 + - admonition: {} + - pymdownx.details: {} extra: generator: false diff --git a/package.json b/package.json index de63a3c87a..3a06db621b 100644 --- a/package.json +++ b/package.json @@ -200,7 +200,7 @@ "jsonpath": "^1.0.2", "lodash": "^4.17.15", "mac-ca": "^1.0.4", - "marked": "^1.1.0", + "marked": "^1.2.7", "md5-file": "^5.0.0", "mobx": "^5.15.7", "mobx-observable-history": "^1.0.3", @@ -219,7 +219,7 @@ "request-promise-native": "^1.0.8", "semver": "^7.3.2", "serializr": "^2.0.3", - "shell-env": "^3.0.0", + "shell-env": "^3.0.1", "spdy": "^4.0.2", "tar": "^6.0.5", "tcp-port-used": "^1.0.1", @@ -244,7 +244,7 @@ "@types/electron-devtools-installer": "^2.2.0", "@types/electron-window-state": "^2.0.34", "@types/fs-extra": "^9.0.1", - "@types/hapi": "^18.0.3", + "@types/hapi": "^18.0.5", "@types/hoist-non-react-statics": "^3.3.1", "@types/html-webpack-plugin": "^3.2.3", "@types/http-proxy": "^1.17.4", @@ -313,7 +313,7 @@ "jest-canvas-mock": "^2.3.0", "jest-fetch-mock": "^3.0.3", "jest-mock-extended": "^1.0.10", - "make-plural": "^6.2.1", + "make-plural": "^6.2.2", "mini-css-extract-plugin": "^0.9.0", "moment": "^2.26.0", "node-loader": "^0.6.0", diff --git a/src/common/__tests__/search-store.test.ts b/src/common/__tests__/search-store.test.ts index 7939ef1d8c..d361c858fd 100644 --- a/src/common/__tests__/search-store.test.ts +++ b/src/common/__tests__/search-store.test.ts @@ -77,4 +77,4 @@ describe("search store tests", () => { searchStore.onSearch(logs, "Starting"); expect(searchStore.totalFinds).toBe(2); }); -}); \ No newline at end of file +}); diff --git a/src/common/__tests__/user-store.test.ts b/src/common/__tests__/user-store.test.ts index 08ca359ce5..b74941a790 100644 --- a/src/common/__tests__/user-store.test.ts +++ b/src/common/__tests__/user-store.test.ts @@ -101,4 +101,4 @@ describe("user store tests", () => { expect(us.lastSeenAppVersion).toBe("0.0.0"); }); }); -}); \ No newline at end of file +}); diff --git a/src/common/__tests__/workspace-store.test.ts b/src/common/__tests__/workspace-store.test.ts index e69ebda0aa..355eb8b2ce 100644 --- a/src/common/__tests__/workspace-store.test.ts +++ b/src/common/__tests__/workspace-store.test.ts @@ -36,6 +36,13 @@ describe("workspace store tests", () => { expect(ws.getById(WorkspaceStore.defaultId)).not.toBe(null); }); + it("default workspace should be enabled", () => { + const ws = WorkspaceStore.getInstance(); + + expect(ws.workspaces.size).toBe(1); + expect(ws.getById(WorkspaceStore.defaultId).enabled).toBe(true); + }); + it("cannot remove the default workspace", () => { const ws = WorkspaceStore.getInstance(); diff --git a/src/common/custom-errors.ts b/src/common/custom-errors.ts index 9bcf3a998a..177ef7578f 100644 --- a/src/common/custom-errors.ts +++ b/src/common/custom-errors.ts @@ -10,4 +10,4 @@ export class ExecValidationNotFoundError extends Error { this.name = this.constructor.name; Error.captureStackTrace(this, this.constructor); } -} \ No newline at end of file +} diff --git a/src/common/kube-helpers.ts b/src/common/kube-helpers.ts index bb0e6b86d2..02a9faef92 100644 --- a/src/common/kube-helpers.ts +++ b/src/common/kube-helpers.ts @@ -175,4 +175,4 @@ export function validateKubeConfig (config: KubeConfig) { throw new ExecValidationNotFoundError(execCommand, isAbsolute); } } -} \ No newline at end of file +} diff --git a/src/common/prometheus-providers.ts b/src/common/prometheus-providers.ts index a5c515b338..5496163c38 100644 --- a/src/common/prometheus-providers.ts +++ b/src/common/prometheus-providers.ts @@ -10,4 +10,4 @@ import { PrometheusProviderRegistry } from "../main/prometheus/provider-registry PrometheusProviderRegistry.registerProvider(provider.id, provider); }); -export const prometheusProviders = PrometheusProviderRegistry.getProviders(); \ No newline at end of file +export const prometheusProviders = PrometheusProviderRegistry.getProviders(); diff --git a/src/common/rbac.ts b/src/common/rbac.ts index fbcf7c98d8..de242b114a 100644 --- a/src/common/rbac.ts +++ b/src/common/rbac.ts @@ -7,37 +7,38 @@ export type KubeResource = "endpoints" | "customresourcedefinitions" | "horizontalpodautoscalers" | "podsecuritypolicies" | "poddisruptionbudgets"; export interface KubeApiResource { - resource: KubeResource; // valid resource name + kind: string; // resource type (e.g. "Namespace") + apiName: KubeResource; // valid api resource name (e.g. "namespaces") group?: string; // api-group } // TODO: auto-populate all resources dynamically (see: kubectl api-resources -o=wide -v=7) export const apiResources: KubeApiResource[] = [ - { resource: "configmaps" }, - { resource: "cronjobs", group: "batch" }, - { resource: "customresourcedefinitions", group: "apiextensions.k8s.io" }, - { resource: "daemonsets", group: "apps" }, - { resource: "deployments", group: "apps" }, - { resource: "endpoints" }, - { resource: "events" }, - { resource: "horizontalpodautoscalers" }, - { resource: "ingresses", group: "networking.k8s.io" }, - { resource: "jobs", group: "batch" }, - { resource: "limitranges" }, - { resource: "namespaces" }, - { resource: "networkpolicies", group: "networking.k8s.io" }, - { resource: "nodes" }, - { resource: "persistentvolumes" }, - { resource: "persistentvolumeclaims" }, - { resource: "pods" }, - { resource: "poddisruptionbudgets" }, - { resource: "podsecuritypolicies" }, - { resource: "resourcequotas" }, - { resource: "replicasets", group: "apps" }, - { resource: "secrets" }, - { resource: "services" }, - { resource: "statefulsets", group: "apps" }, - { resource: "storageclasses", group: "storage.k8s.io" }, + { kind: "ConfigMap", apiName: "configmaps" }, + { kind: "CronJob", apiName: "cronjobs", group: "batch" }, + { kind: "CustomResourceDefinition", apiName: "customresourcedefinitions", group: "apiextensions.k8s.io" }, + { kind: "DaemonSet", apiName: "daemonsets", group: "apps" }, + { kind: "Deployment", apiName: "deployments", group: "apps" }, + { kind: "Endpoint", apiName: "endpoints" }, + { kind: "Event", apiName: "events" }, + { kind: "HorizontalPodAutoscaler", apiName: "horizontalpodautoscalers" }, + { kind: "Ingress", apiName: "ingresses", group: "networking.k8s.io" }, + { kind: "Job", apiName: "jobs", group: "batch" }, + { kind: "Namespace", apiName: "namespaces" }, + { kind: "LimitRange", apiName: "limitranges" }, + { kind: "NetworkPolicy", apiName: "networkpolicies", group: "networking.k8s.io" }, + { kind: "Node", apiName: "nodes" }, + { kind: "PersistentVolume", apiName: "persistentvolumes" }, + { kind: "PersistentVolumeClaim", apiName: "persistentvolumeclaims" }, + { kind: "Pod", apiName: "pods" }, + { kind: "PodDisruptionBudget", apiName: "poddisruptionbudgets" }, + { kind: "PodSecurityPolicy", apiName: "podsecuritypolicies" }, + { kind: "ResourceQuota", apiName: "resourcequotas" }, + { kind: "ReplicaSet", apiName: "replicasets", group: "apps" }, + { kind: "Secret", apiName: "secrets" }, + { kind: "Service", apiName: "services" }, + { kind: "StatefulSet", apiName: "statefulsets", group: "apps" }, + { kind: "StorageClass", apiName: "storageclasses", group: "storage.k8s.io" }, ]; export function isAllowedResource(resources: KubeResource | KubeResource[]) { diff --git a/src/common/search-store.ts b/src/common/search-store.ts index f17d120403..86a6054af3 100644 --- a/src/common/search-store.ts +++ b/src/common/search-store.ts @@ -140,4 +140,4 @@ export class SearchStore { } } -export const searchStore = new SearchStore; \ No newline at end of file +export const searchStore = new SearchStore; diff --git a/src/common/user-store.ts b/src/common/user-store.ts index cf271a011d..b0294d9e5a 100644 --- a/src/common/user-store.ts +++ b/src/common/user-store.ts @@ -84,6 +84,15 @@ export class UserStore extends BaseStore { return semver.gt(getAppVersion(), this.lastSeenAppVersion); } + @action + setHiddenTableColumns(tableId: string, names: Set | string[]) { + this.preferences.hiddenTableColumns[tableId] = Array.from(names); + } + + getHiddenTableColumns(tableId: string): Set { + return new Set(this.preferences.hiddenTableColumns[tableId]); + } + @action resetKubeConfigPath() { this.kubeConfigPath = kubeConfigDefaultPath; diff --git a/src/common/utils/__tests__/splitArray.test.ts b/src/common/utils/__tests__/splitArray.test.ts index a401e07701..1e1589fee2 100644 --- a/src/common/utils/__tests__/splitArray.test.ts +++ b/src/common/utils/__tests__/splitArray.test.ts @@ -28,4 +28,4 @@ describe("split array on element tests", () => { test("ten elements, in end array", () => { expect(splitArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)).toStrictEqual([[0, 1, 2, 3, 4, 5, 6, 7, 8], [], true]); }); -}); \ No newline at end of file +}); diff --git a/src/common/utils/singleton.ts b/src/common/utils/singleton.ts index 61269d10b1..caa5471072 100644 --- a/src/common/utils/singleton.ts +++ b/src/common/utils/singleton.ts @@ -26,4 +26,4 @@ class Singleton { } export { Singleton }; -export default Singleton; \ No newline at end of file +export default Singleton; diff --git a/src/common/workspace-store.ts b/src/common/workspace-store.ts index 7688516af2..921a9126a9 100644 --- a/src/common/workspace-store.ts +++ b/src/common/workspace-store.ts @@ -58,14 +58,7 @@ export class Workspace implements WorkspaceModel, WorkspaceState { * @observable */ @observable ownerRef?: string; - /** - * Is workspace enabled - * - * Workspaces that don't have ownerRef will be enabled by default. Workspaces with ownerRef need to explicitly enable a workspace. - * - * @observable - */ - @observable enabled: boolean; + /** * Last active cluster id * @@ -73,6 +66,9 @@ export class Workspace implements WorkspaceModel, WorkspaceState { */ @observable lastActiveClusterId?: ClusterId; + + @observable private _enabled: boolean; + constructor(data: WorkspaceModel) { Object.assign(this, data); @@ -83,6 +79,21 @@ export class Workspace implements WorkspaceModel, WorkspaceState { } } + /** + * Is workspace enabled + * + * Workspaces that don't have ownerRef will be enabled by default. Workspaces with ownerRef need to explicitly enable a workspace. + * + * @observable + */ + get enabled(): boolean { + return !this.isManaged || this._enabled; + } + + set enabled(enabled: boolean) { + this._enabled = enabled; + } + /** * Is workspace managed by an extension */ @@ -134,10 +145,18 @@ export class WorkspaceStore extends BaseStore { static readonly defaultId: WorkspaceId = "default"; private static stateRequestChannel = "workspace:states"; + @observable currentWorkspaceId = WorkspaceStore.defaultId; + @observable workspaces = observable.map(); + private constructor() { super({ configName: "lens-workspace-store", }); + + this.workspaces.set(WorkspaceStore.defaultId, new Workspace({ + id: WorkspaceStore.defaultId, + name: "default" + })); } async load() { @@ -186,15 +205,6 @@ export class WorkspaceStore extends BaseStore { ipcRenderer.removeAllListeners("workspace:state"); } - @observable currentWorkspaceId = WorkspaceStore.defaultId; - - @observable workspaces = observable.map({ - [WorkspaceStore.defaultId]: new Workspace({ - id: WorkspaceStore.defaultId, - name: "default" - }) - }); - @computed get currentWorkspace(): Workspace { return this.getById(this.currentWorkspaceId); } diff --git a/src/extensions/interfaces/index.ts b/src/extensions/interfaces/index.ts index c91d8cdd19..7b1c601537 100644 --- a/src/extensions/interfaces/index.ts +++ b/src/extensions/interfaces/index.ts @@ -1 +1 @@ -export * from "./registrations"; \ No newline at end of file +export * from "./registrations"; diff --git a/src/extensions/interfaces/registrations.ts b/src/extensions/interfaces/registrations.ts index 47c63062ea..ff51d9a824 100644 --- a/src/extensions/interfaces/registrations.ts +++ b/src/extensions/interfaces/registrations.ts @@ -5,4 +5,4 @@ export type { KubeObjectMenuRegistration, KubeObjectMenuComponents } from "../re export type { KubeObjectStatusRegistration } from "../registries/kube-object-status-registry"; export type { PageRegistration, RegisteredPage, PageParams, PageComponentProps, PageComponents, PageTarget } from "../registries/page-registry"; export type { PageMenuRegistration, ClusterPageMenuRegistration, PageMenuComponents } from "../registries/page-menu-registry"; -export type { StatusBarRegistration } from "../registries/status-bar-registry"; \ No newline at end of file +export type { StatusBarRegistration } from "../registries/status-bar-registry"; diff --git a/src/extensions/renderer-api/kube-object-status.ts b/src/extensions/renderer-api/kube-object-status.ts index f609d736fe..616ead1bb2 100644 --- a/src/extensions/renderer-api/kube-object-status.ts +++ b/src/extensions/renderer-api/kube-object-status.ts @@ -8,4 +8,4 @@ export enum KubeObjectStatusLevel { INFO = 1, WARNING = 2, CRITICAL = 3 -} \ No newline at end of file +} diff --git a/src/extensions/renderer-api/theming.ts b/src/extensions/renderer-api/theming.ts index f819036803..b3da69bdbc 100644 --- a/src/extensions/renderer-api/theming.ts +++ b/src/extensions/renderer-api/theming.ts @@ -2,4 +2,4 @@ import { themeStore } from "../../renderer/theme.store"; export function getActiveTheme() { return themeStore.activeTheme; -} \ No newline at end of file +} diff --git a/src/main/cluster-detectors/base-cluster-detector.ts b/src/main/cluster-detectors/base-cluster-detector.ts index 9d52e1a70e..885f96c33e 100644 --- a/src/main/cluster-detectors/base-cluster-detector.ts +++ b/src/main/cluster-detectors/base-cluster-detector.ts @@ -31,4 +31,4 @@ export class BaseClusterDetector { }, }); } -} \ No newline at end of file +} diff --git a/src/main/cluster-detectors/cluster-id-detector.ts b/src/main/cluster-detectors/cluster-id-detector.ts index 2e0cc694ff..810955afae 100644 --- a/src/main/cluster-detectors/cluster-id-detector.ts +++ b/src/main/cluster-detectors/cluster-id-detector.ts @@ -23,4 +23,4 @@ export class ClusterIdDetector extends BaseClusterDetector { return response.metadata.uid; } -} \ No newline at end of file +} diff --git a/src/main/cluster-detectors/detector-registry.ts b/src/main/cluster-detectors/detector-registry.ts index 43c56153c9..b1d1b73447 100644 --- a/src/main/cluster-detectors/detector-registry.ts +++ b/src/main/cluster-detectors/detector-registry.ts @@ -48,4 +48,4 @@ detectorRegistry.add(ClusterIdDetector); detectorRegistry.add(LastSeenDetector); detectorRegistry.add(VersionDetector); detectorRegistry.add(DistributionDetector); -detectorRegistry.add(NodesCountDetector); \ No newline at end of file +detectorRegistry.add(NodesCountDetector); diff --git a/src/main/cluster-detectors/last-seen-detector.ts b/src/main/cluster-detectors/last-seen-detector.ts index e648d5f2f9..0a9bcf9f74 100644 --- a/src/main/cluster-detectors/last-seen-detector.ts +++ b/src/main/cluster-detectors/last-seen-detector.ts @@ -11,4 +11,4 @@ export class LastSeenDetector extends BaseClusterDetector { return { value: new Date().toJSON(), accuracy: 100 }; } -} \ No newline at end of file +} diff --git a/src/main/cluster-detectors/nodes-count-detector.ts b/src/main/cluster-detectors/nodes-count-detector.ts index 0ece5dd080..45584df5bd 100644 --- a/src/main/cluster-detectors/nodes-count-detector.ts +++ b/src/main/cluster-detectors/nodes-count-detector.ts @@ -16,4 +16,4 @@ export class NodesCountDetector extends BaseClusterDetector { return response.items.length; } -} \ No newline at end of file +} diff --git a/src/main/cluster-detectors/version-detector.ts b/src/main/cluster-detectors/version-detector.ts index 8080ef57a1..b19979db8a 100644 --- a/src/main/cluster-detectors/version-detector.ts +++ b/src/main/cluster-detectors/version-detector.ts @@ -16,4 +16,4 @@ export class VersionDetector extends BaseClusterDetector { return response.gitVersion; } -} \ No newline at end of file +} diff --git a/src/main/cluster-manager.ts b/src/main/cluster-manager.ts index 5717c7278d..1b468e3bb6 100644 --- a/src/main/cluster-manager.ts +++ b/src/main/cluster-manager.ts @@ -14,7 +14,7 @@ export class ClusterManager extends Singleton { // auto-init clusters autorun(() => { clusterStore.enabledClustersList.forEach(cluster => { - if (!cluster.initialized) { + if (!cluster.initialized && !cluster.initializing) { logger.info(`[CLUSTER-MANAGER]: init cluster`, cluster.getMeta()); cluster.init(port); } diff --git a/src/main/cluster.ts b/src/main/cluster.ts index b9ff62e8ac..956164e10c 100644 --- a/src/main/cluster.ts +++ b/src/main/cluster.ts @@ -84,6 +84,14 @@ export class Cluster implements ClusterModel, ClusterState { whenInitialized = when(() => this.initialized); whenReady = when(() => this.ready); + /** + * Is cluster object initializinng on-going + * + * @observable + */ + @observable initializing = false; + + /** * Is cluster object initialized * @@ -182,7 +190,7 @@ export class Cluster implements ClusterModel, ClusterState { */ @observable metadata: ClusterMetadata = {}; /** - * List of allowed namespaces + * List of allowed namespaces verified via K8S::SelfSubjectAccessReview api * * @observable */ @@ -195,7 +203,7 @@ export class Cluster implements ClusterModel, ClusterState { */ @observable allowedResources: string[] = []; /** - * List of accessible namespaces + * List of accessible namespaces provided by user in the Cluster Settings * * @observable */ @@ -216,7 +224,7 @@ export class Cluster implements ClusterModel, ClusterState { * @computed */ @computed get name() { - return this.preferences.clusterName || this.contextName; + return this.preferences.clusterName || this.contextName; } /** @@ -271,8 +279,10 @@ export class Cluster implements ClusterModel, ClusterState { * @param port port where internal auth proxy is listening * @internal */ - @action async init(port: number) { + @action + async init(port: number) { try { + this.initializing = true; this.contextHandler = new ContextHandler(this); this.kubeconfigManager = await KubeconfigManager.create(this, this.contextHandler, port); this.kubeProxyUrl = `http://localhost:${port}${apiKubePrefix}`; @@ -287,6 +297,8 @@ export class Cluster implements ClusterModel, ClusterState { id: this.id, error: err, }); + } finally { + this.initializing = false; } } @@ -323,7 +335,8 @@ export class Cluster implements ClusterModel, ClusterState { * @param force force activation * @internal */ - @action async activate(force = false) { + @action + async activate(force = false) { if (this.activated && !force) { return this.pushState(); } @@ -362,7 +375,8 @@ export class Cluster implements ClusterModel, ClusterState { /** * @internal */ - @action async reconnect() { + @action + async reconnect() { logger.info(`[CLUSTER]: reconnect`, this.getMeta()); this.contextHandler?.stopServer(); await this.contextHandler?.ensureServer(); @@ -389,7 +403,8 @@ export class Cluster implements ClusterModel, ClusterState { * @internal * @param opts refresh options */ - @action async refresh(opts: ClusterRefreshOptions = {}) { + @action + async refresh(opts: ClusterRefreshOptions = {}) { logger.info(`[CLUSTER]: refresh`, this.getMeta()); await this.whenInitialized; await this.refreshConnectionStatus(); @@ -409,7 +424,8 @@ export class Cluster implements ClusterModel, ClusterState { /** * @internal */ - @action async refreshMetadata() { + @action + async refreshMetadata() { logger.info(`[CLUSTER]: refreshMetadata`, this.getMeta()); const metadata = await detectorRegistry.detectForCluster(this); const existingMetadata = this.metadata; @@ -420,7 +436,8 @@ export class Cluster implements ClusterModel, ClusterState { /** * @internal */ - @action async refreshConnectionStatus() { + @action + async refreshConnectionStatus() { const connectionStatus = await this.getConnectionStatus(); this.online = connectionStatus > ClusterStatus.Offline; @@ -430,7 +447,8 @@ export class Cluster implements ClusterModel, ClusterState { /** * @internal */ - @action async refreshAllowedResources() { + @action + async refreshAllowedResources() { this.allowedNamespaces = await this.getAllowedNamespaces(); this.allowedResources = await this.getAllowedResources(); } @@ -657,7 +675,7 @@ export class Cluster implements ClusterModel, ClusterState { for (const namespace of this.allowedNamespaces.slice(0, 10)) { if (!this.resourceAccessStatuses.get(apiResource)) { const result = await this.canI({ - resource: apiResource.resource, + resource: apiResource.apiName, group: apiResource.group, verb: "list", namespace @@ -672,9 +690,19 @@ export class Cluster implements ClusterModel, ClusterState { return apiResources .filter((resource) => this.resourceAccessStatuses.get(resource)) - .map(apiResource => apiResource.resource); + .map(apiResource => apiResource.apiName); } catch (error) { return []; } } + + isAllowedResource(kind: string): boolean { + const apiResource = apiResources.find(resource => resource.kind === kind || resource.apiName === kind); + + if (apiResource) { + return this.allowedResources.includes(apiResource.apiName); + } + + return true; // allowed by default for other resources + } } diff --git a/src/migrations/cluster-store/index.ts b/src/migrations/cluster-store/index.ts index c546fdaeda..4a71d4f7ad 100644 --- a/src/migrations/cluster-store/index.ts +++ b/src/migrations/cluster-store/index.ts @@ -18,4 +18,4 @@ export default { ...version270Beta1, ...version360Beta1, ...snap -}; \ No newline at end of file +}; diff --git a/src/renderer/api/__tests__/kube-api.test.ts b/src/renderer/api/__tests__/kube-api.test.ts index 41078e77a3..7481bd096a 100644 --- a/src/renderer/api/__tests__/kube-api.test.ts +++ b/src/renderer/api/__tests__/kube-api.test.ts @@ -79,4 +79,4 @@ describe("KubeApi", () => { expect(kubeApi.apiPrefix).toEqual("/apis"); expect(kubeApi.apiGroup).toEqual("extensions"); }); -}); \ No newline at end of file +}); diff --git a/src/renderer/api/endpoints/helm-charts.api.ts b/src/renderer/api/endpoints/helm-charts.api.ts index a1fd497798..8beff01779 100644 --- a/src/renderer/api/endpoints/helm-charts.api.ts +++ b/src/renderer/api/endpoints/helm-charts.api.ts @@ -86,7 +86,7 @@ export class HelmChart { tillerVersion?: string; getId() { - return this.digest; + return `${this.apiVersion}/${this.name}@${this.getAppVersion()}`; } getName() { diff --git a/src/renderer/api/kube-watch-api.ts b/src/renderer/api/kube-watch-api.ts index 78ca25256e..fe35a04baa 100644 --- a/src/renderer/api/kube-watch-api.ts +++ b/src/renderer/api/kube-watch-api.ts @@ -11,7 +11,7 @@ import { apiPrefix, isDevelopment } from "../../common/vars"; import { getHostedCluster } from "../../common/cluster-store"; export interface IKubeWatchEvent { - type: "ADDED" | "MODIFIED" | "DELETED"; + type: "ADDED" | "MODIFIED" | "DELETED" | "ERROR"; object?: T; } @@ -62,27 +62,41 @@ export class KubeWatchApi { }); } - protected getQuery(): Partial { - const { isAdmin, allowedNamespaces } = getHostedCluster(); + // FIXME: use POST to send apis for subscribing (list could be huge) + // TODO: try to use normal fetch res.body stream to consume watch-api updates + // https://github.com/lensapp/lens/issues/1898 + protected async getQuery() { + const { namespaceStore } = await import("../components/+namespaces/namespace.store"); + + await namespaceStore.whenReady; + const { isAdmin } = getHostedCluster(); return { api: this.activeApis.map(api => { - if (isAdmin) return api.getWatchUrl(); + if (isAdmin && !api.isNamespaced) { + return api.getWatchUrl(); + } - return allowedNamespaces.map(namespace => api.getWatchUrl(namespace)); + if (api.isNamespaced) { + return namespaceStore.getContextNamespaces().map(namespace => api.getWatchUrl(namespace)); + } + + return []; }).flat() }; } // todo: maybe switch to websocket to avoid often reconnects @autobind() - protected connect() { + protected async connect() { if (this.evtSource) this.disconnect(); // close previous connection - if (!this.activeApis.length) { + const query = await this.getQuery(); + + if (!this.activeApis.length || !query.api.length) { return; } - const query = this.getQuery(); + const apiUrl = `${apiPrefix}/watch?${stringify(query)}`; this.evtSource = new EventSource(apiUrl); @@ -158,6 +172,10 @@ export class KubeWatchApi { addListener(store: KubeObjectStore, callback: (evt: IKubeWatchEvent) => void) { const listener = (evt: IKubeWatchEvent) => { + if (evt.type === "ERROR") { + return; // e.g. evt.object.message == "too old resource version" + } + const { namespace, resourceVersion } = evt.object.metadata; const api = apiManager.getApiByKind(evt.object.kind, evt.object.apiVersion); diff --git a/src/renderer/api/workload-kube-object.ts b/src/renderer/api/workload-kube-object.ts index e0c6d3f121..185d3d502c 100644 --- a/src/renderer/api/workload-kube-object.ts +++ b/src/renderer/api/workload-kube-object.ts @@ -1,7 +1,7 @@ import get from "lodash/get"; import { KubeObject } from "./kube-object"; -interface IToleration { +export interface IToleration { key?: string; operator?: string; effect?: string; @@ -82,4 +82,4 @@ export class WorkloadKubeObject extends KubeObject { return Object.keys(affinity).length; } -} \ No newline at end of file +} diff --git a/src/renderer/components/+apps-helm-charts/helm-charts.route.ts b/src/renderer/components/+apps-helm-charts/helm-charts.route.ts index 9b8aecc499..97a0923d97 100644 --- a/src/renderer/components/+apps-helm-charts/helm-charts.route.ts +++ b/src/renderer/components/+apps-helm-charts/helm-charts.route.ts @@ -11,4 +11,4 @@ export interface IHelmChartsRouteParams { repo?: string; } -export const helmChartsURL = buildURL(helmChartsRoute.path); \ No newline at end of file +export const helmChartsURL = buildURL(helmChartsRoute.path); diff --git a/src/renderer/components/+apps-helm-charts/index.ts b/src/renderer/components/+apps-helm-charts/index.ts index a9403c097c..c0649f3f38 100644 --- a/src/renderer/components/+apps-helm-charts/index.ts +++ b/src/renderer/components/+apps-helm-charts/index.ts @@ -1,2 +1,2 @@ export * from "./helm-charts"; -export * from "./helm-charts.route"; \ No newline at end of file +export * from "./helm-charts.route"; diff --git a/src/renderer/components/+apps-releases/index.ts b/src/renderer/components/+apps-releases/index.ts index 32a4871769..bd80c60404 100644 --- a/src/renderer/components/+apps-releases/index.ts +++ b/src/renderer/components/+apps-releases/index.ts @@ -1,2 +1,2 @@ export * from "./releases"; -export * from "./release.route"; \ No newline at end of file +export * from "./release.route"; diff --git a/src/renderer/components/+apps-releases/release.store.ts b/src/renderer/components/+apps-releases/release.store.ts index b6d5c2fb5f..6f7ed39fed 100644 --- a/src/renderer/components/+apps-releases/release.store.ts +++ b/src/renderer/components/+apps-releases/release.store.ts @@ -5,7 +5,7 @@ import { HelmRelease, helmReleasesApi, IReleaseCreatePayload, IReleaseUpdatePayl import { ItemStore } from "../../item.store"; import { Secret } from "../../api/endpoints"; import { secretsStore } from "../+config-secrets/secrets.store"; -import { getHostedCluster } from "../../../common/cluster-store"; +import { namespaceStore } from "../+namespaces/namespace.store"; @autobind() export class ReleaseStore extends ItemStore { @@ -60,30 +60,23 @@ export class ReleaseStore extends ItemStore { @action async loadAll() { this.isLoading = true; - let items; try { - const { isAdmin, allowedNamespaces } = getHostedCluster(); + const items = await this.loadItems(namespaceStore.getContextNamespaces()); - items = await this.loadItems(!isAdmin ? allowedNamespaces : null); - } finally { - if (items) { - items = this.sortItems(items); - this.items.replace(items); - } + this.items.replace(this.sortItems(items)); this.isLoaded = true; + } catch (error) { + console.error(`Loading Helm Chart releases has failed: ${error}`); + } finally { this.isLoading = false; } } - async loadItems(namespaces?: string[]) { - if (!namespaces) { - return helmReleasesApi.list(); - } else { - return Promise - .all(namespaces.map(namespace => helmReleasesApi.list(namespace))) - .then(items => items.flat()); - } + async loadItems(namespaces: string[]) { + return Promise + .all(namespaces.map(namespace => helmReleasesApi.list(namespace))) + .then(items => items.flat()); } async create(payload: IReleaseCreatePayload) { diff --git a/src/renderer/components/+apps/index.ts b/src/renderer/components/+apps/index.ts index 70c0169777..330891b2b1 100644 --- a/src/renderer/components/+apps/index.ts +++ b/src/renderer/components/+apps/index.ts @@ -1,2 +1,2 @@ export * from "./apps"; -export * from "./apps.route"; \ No newline at end of file +export * from "./apps.route"; diff --git a/src/renderer/components/+cluster-settings/components/cluster-home-dir-setting.tsx b/src/renderer/components/+cluster-settings/components/cluster-home-dir-setting.tsx index 35c18cc5e5..10aabf3ff7 100644 --- a/src/renderer/components/+cluster-settings/components/cluster-home-dir-setting.tsx +++ b/src/renderer/components/+cluster-settings/components/cluster-home-dir-setting.tsx @@ -48,4 +48,4 @@ export class ClusterHomeDirSetting extends React.Component { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/+cluster-settings/components/cluster-name-setting.tsx b/src/renderer/components/+cluster-settings/components/cluster-name-setting.tsx index 631c6d54ef..9d953ef9ca 100644 --- a/src/renderer/components/+cluster-settings/components/cluster-name-setting.tsx +++ b/src/renderer/components/+cluster-settings/components/cluster-name-setting.tsx @@ -45,4 +45,4 @@ export class ClusterNameSetting extends React.Component { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/+cluster-settings/components/cluster-proxy-setting.tsx b/src/renderer/components/+cluster-settings/components/cluster-proxy-setting.tsx index 3887487816..eb122ac444 100644 --- a/src/renderer/components/+cluster-settings/components/cluster-proxy-setting.tsx +++ b/src/renderer/components/+cluster-settings/components/cluster-proxy-setting.tsx @@ -45,4 +45,4 @@ export class ClusterProxySetting extends React.Component { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/+cluster-settings/general.tsx b/src/renderer/components/+cluster-settings/general.tsx index 1d498bc94b..91fce05164 100644 --- a/src/renderer/components/+cluster-settings/general.tsx +++ b/src/renderer/components/+cluster-settings/general.tsx @@ -25,4 +25,4 @@ export class General extends React.Component { ; } -} \ No newline at end of file +} diff --git a/src/renderer/components/+cluster-settings/removal.tsx b/src/renderer/components/+cluster-settings/removal.tsx index 7d97e9c515..495fb71fe8 100644 --- a/src/renderer/components/+cluster-settings/removal.tsx +++ b/src/renderer/components/+cluster-settings/removal.tsx @@ -17,4 +17,4 @@ export class Removal extends React.Component { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/+cluster-settings/status.tsx b/src/renderer/components/+cluster-settings/status.tsx index 7f21d19aba..d43cfe5c35 100644 --- a/src/renderer/components/+cluster-settings/status.tsx +++ b/src/renderer/components/+cluster-settings/status.tsx @@ -58,4 +58,4 @@ export class Status extends React.Component { ; } -} \ No newline at end of file +} diff --git a/src/renderer/components/+cluster/cluster-issues.tsx b/src/renderer/components/+cluster/cluster-issues.tsx index eb85bf79f8..0aabebaa27 100644 --- a/src/renderer/components/+cluster/cluster-issues.tsx +++ b/src/renderer/components/+cluster/cluster-issues.tsx @@ -23,11 +23,13 @@ interface IWarning extends ItemObject { kind: string; message: string; selfLink: string; + age: string | number; } enum sortBy { type = "type", - object = "object" + object = "object", + age = "age", } @observer @@ -35,6 +37,7 @@ export class ClusterIssues extends React.Component { private sortCallbacks = { [sortBy.type]: (warning: IWarning) => warning.kind, [sortBy.object]: (warning: IWarning) => warning.getName(), + [sortBy.age]: (warning: IWarning) => warning.age || "", }; @computed get warnings() { @@ -42,15 +45,16 @@ export class ClusterIssues extends React.Component { // Node bad conditions nodesStore.items.forEach(node => { - const { kind, selfLink, getId, getName } = node; + const { kind, selfLink, getId, getName, getAge } = node; node.getWarningConditions().forEach(({ message }) => { warnings.push({ - kind, + age: getAge(), getId, getName, - selfLink, + kind, message, + selfLink, }); }); }); @@ -59,12 +63,13 @@ export class ClusterIssues extends React.Component { const events = eventStore.getWarnings(); events.forEach(error => { - const { message, involvedObject } = error; + const { message, involvedObject, getAge } = error; const { uid, name, kind } = involvedObject; warnings.push({ getId: () => uid, getName: () => name, + age: getAge(), message, kind, selfLink: lookupApiLink(involvedObject, error), @@ -78,7 +83,7 @@ export class ClusterIssues extends React.Component { getTableRow(uid: string) { const { warnings } = this; const warning = warnings.find(warn => warn.getId() == uid); - const { getId, getName, message, kind, selfLink } = warning; + const { getId, getName, message, kind, selfLink, age } = warning; return ( { {kind} + + {age} + ); } @@ -139,6 +147,7 @@ export class ClusterIssues extends React.Component { Message Object Type + Age diff --git a/src/renderer/components/+cluster/cluster-metrics.tsx b/src/renderer/components/+cluster/cluster-metrics.tsx index 6461bae7f3..2bdaded8b7 100644 --- a/src/renderer/components/+cluster/cluster-metrics.tsx +++ b/src/renderer/components/+cluster/cluster-metrics.tsx @@ -95,4 +95,4 @@ export const ClusterMetrics = observer(() => { {renderMetrics()} ); -}); \ No newline at end of file +}); diff --git a/src/renderer/components/+landing-page/index.tsx b/src/renderer/components/+landing-page/index.tsx index 4bdb2a706c..c7eacf1bd0 100644 --- a/src/renderer/components/+landing-page/index.tsx +++ b/src/renderer/components/+landing-page/index.tsx @@ -1,2 +1,2 @@ export * from "./landing-page.route"; -export * from "./landing-page"; \ No newline at end of file +export * from "./landing-page"; diff --git a/src/renderer/components/+namespaces/namespace.store.ts b/src/renderer/components/+namespaces/namespace.store.ts index ad02dd137c..50ec2c8038 100644 --- a/src/renderer/components/+namespaces/namespace.store.ts +++ b/src/renderer/components/+namespaces/namespace.store.ts @@ -1,53 +1,120 @@ -import { action, comparer, observable, reaction } from "mobx"; +import { action, comparer, IReactionDisposer, IReactionOptions, observable, reaction, toJS, when } from "mobx"; import { autobind, createStorage } from "../../utils"; -import { KubeObjectStore } from "../../kube-object.store"; -import { Namespace, namespacesApi } from "../../api/endpoints"; +import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store"; +import { Namespace, namespacesApi } from "../../api/endpoints/namespaces.api"; import { createPageParam } from "../../navigation"; import { apiManager } from "../../api/api-manager"; -import { isAllowedResource } from "../../../common/rbac"; -import { getHostedCluster } from "../../../common/cluster-store"; +import { clusterStore, getHostedCluster } from "../../../common/cluster-store"; -const storage = createStorage("context_namespaces", []); +const storage = createStorage("context_namespaces"); export const namespaceUrlParam = createPageParam({ name: "namespaces", isSystem: true, multiValues: true, get defaultValue() { - return storage.get(); // initial namespaces coming from URL or local-storage (default) + return storage.get() ?? []; // initial namespaces coming from URL or local-storage (default) } }); +export function getDummyNamespace(name: string) { + return new Namespace({ + kind: Namespace.kind, + apiVersion: "v1", + metadata: { + name, + uid: "", + resourceVersion: "", + selfLink: `/api/v1/namespaces/${name}` + } + }); +} + @autobind() export class NamespaceStore extends KubeObjectStore { api = namespacesApi; - contextNs = observable.array(); + + @observable contextNs = observable.array(); + @observable isReady = false; + + whenReady = when(() => this.isReady); constructor() { super(); this.init(); } - private init() { - this.setContext(this.initNamespaces); + private async init() { + await clusterStore.whenLoaded; + if (!getHostedCluster()) return; + await getHostedCluster().whenReady; // wait for cluster-state from main - return reaction(() => this.contextNs.toJS(), namespaces => { + this.setContext(this.initialNamespaces); + this.autoLoadAllowedNamespaces(); + this.autoUpdateUrlAndLocalStorage(); + + this.isReady = true; + } + + public onContextChange(callback: (contextNamespaces: string[]) => void, opts: IReactionOptions = {}): IReactionDisposer { + return reaction(() => this.contextNs.toJS(), callback, { + equals: comparer.shallow, + ...opts, + }); + } + + private autoUpdateUrlAndLocalStorage(): IReactionDisposer { + return this.onContextChange(namespaces => { storage.set(namespaces); // save to local-storage namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url }, { fireImmediately: true, - equals: comparer.identity, }); } - get initNamespaces() { - return namespaceUrlParam.get(); + private autoLoadAllowedNamespaces(): IReactionDisposer { + return reaction(() => this.allowedNamespaces, () => this.loadAll(), { + fireImmediately: true, + equals: comparer.shallow, + }); } - getContextParams() { - return { - namespaces: this.contextNs.toJS(), - }; + get allowedNamespaces(): string[] { + return toJS(getHostedCluster().allowedNamespaces); + } + + private get initialNamespaces(): string[] { + const allowed = new Set(this.allowedNamespaces); + const prevSelected = storage.get(); + + if (Array.isArray(prevSelected)) { + return prevSelected.filter(namespace => allowed.has(namespace)); + } + + // otherwise select "default" or first allowed namespace + if (allowed.has("default")) { + return ["default"]; + } else if (allowed.size) { + return [Array.from(allowed)[0]]; + } + + return []; + } + + getContextNamespaces(): string[] { + const namespaces = this.contextNs.toJS(); + + // show all namespaces when nothing selected + if (!namespaces.length) { + if (this.isLoaded) { + // return actual namespaces list since "allowedNamespaces" updating every 30s in cluster and thus might be stale + return this.items.map(namespace => namespace.getName()); + } + + return this.allowedNamespaces; + } + + return namespaces; } subscribe(apis = [this.api]) { @@ -61,31 +128,18 @@ export class NamespaceStore extends KubeObjectStore { return super.subscribe(apis); } - protected async loadItems(namespaces?: string[]) { - if (!isAllowedResource("namespaces")) { - if (namespaces) return namespaces.map(this.getDummyNamespace); + protected async loadItems(params: KubeObjectStoreLoadingParams) { + const { allowedNamespaces } = this; - return []; + let namespaces = await super.loadItems(params); + + namespaces = namespaces.filter(namespace => allowedNamespaces.includes(namespace.getName())); + + if (!namespaces.length && allowedNamespaces.length > 0) { + return allowedNamespaces.map(getDummyNamespace); } - if (namespaces) { - return Promise.all(namespaces.map(name => this.api.get({ name }))); - } else { - return super.loadItems(); - } - } - - protected getDummyNamespace(name: string) { - return new Namespace({ - kind: "Namespace", - apiVersion: "v1", - metadata: { - name, - uid: "", - resourceVersion: "", - selfLink: `/api/v1/namespaces/${name}` - } - }); + return namespaces; } @action @@ -105,12 +159,6 @@ export class NamespaceStore extends KubeObjectStore { else this.contextNs.push(namespace); } - @action - reset() { - super.reset(); - this.contextNs.clear(); - } - @action async remove(item: Namespace) { await super.remove(item); diff --git a/src/renderer/components/+nodes/nodes.tsx b/src/renderer/components/+nodes/nodes.tsx index edfa5c4026..1ca12343b5 100644 --- a/src/renderer/components/+nodes/nodes.tsx +++ b/src/renderer/components/+nodes/nodes.tsx @@ -51,6 +51,10 @@ export class Nodes extends React.Component { if (!metrics || !metrics[1]) return ; const usage = metrics[0]; const cores = metrics[1]; + const cpuUsagePercent = Math.ceil(usage * 100) / cores; + const cpuUsagePercentLabel: String = cpuUsagePercent % 1 === 0 + ? cpuUsagePercent.toString() + : cpuUsagePercent.toFixed(2); return ( { value={usage} tooltip={{ preferredPositions: TooltipPosition.BOTTOM, - children: `CPU: ${Math.ceil(usage * 100) / cores}\%, cores: ${cores}` + children: `CPU: ${cpuUsagePercentLabel}\%, cores: ${cores}` }} /> ); diff --git a/src/renderer/components/+pod-security-policies/index.ts b/src/renderer/components/+pod-security-policies/index.ts index d037873b5b..c9379d3381 100644 --- a/src/renderer/components/+pod-security-policies/index.ts +++ b/src/renderer/components/+pod-security-policies/index.ts @@ -1,3 +1,3 @@ export * from "./pod-security-policies.route"; export * from "./pod-security-policies"; -export * from "./pod-security-policy-details"; \ No newline at end of file +export * from "./pod-security-policy-details"; diff --git a/src/renderer/components/+user-management-roles-bindings/role-bindings.store.ts b/src/renderer/components/+user-management-roles-bindings/role-bindings.store.ts index f293dea6f0..71890acc44 100644 --- a/src/renderer/components/+user-management-roles-bindings/role-bindings.store.ts +++ b/src/renderer/components/+user-management-roles-bindings/role-bindings.store.ts @@ -1,7 +1,7 @@ import difference from "lodash/difference"; import uniqBy from "lodash/uniqBy"; import { clusterRoleBindingApi, IRoleBindingSubject, RoleBinding, roleBindingApi } from "../../api/endpoints"; -import { KubeObjectStore } from "../../kube-object.store"; +import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store"; import { autobind } from "../../utils"; import { apiManager } from "../../api/api-manager"; @@ -26,15 +26,13 @@ export class RoleBindingsStore extends KubeObjectStore { return clusterRoleBindingApi.get(params); } - protected loadItems(namespaces?: string[]) { - if (namespaces) { - return Promise.all( - namespaces.map(namespace => roleBindingApi.list({ namespace })) - ).then(items => items.flat()); - } else { - return Promise.all([clusterRoleBindingApi.list(), roleBindingApi.list()]) - .then(items => items.flat()); - } + protected async loadItems(params: KubeObjectStoreLoadingParams): Promise { + const items = await Promise.all([ + super.loadItems({ ...params, api: clusterRoleBindingApi }), + super.loadItems({ ...params, api: roleBindingApi }), + ]); + + return items.flat(); } protected async createItem(params: { name: string; namespace?: string }, data?: Partial) { diff --git a/src/renderer/components/+user-management-roles/roles.store.ts b/src/renderer/components/+user-management-roles/roles.store.ts index 6af33deacb..7d2e90dd38 100644 --- a/src/renderer/components/+user-management-roles/roles.store.ts +++ b/src/renderer/components/+user-management-roles/roles.store.ts @@ -1,6 +1,6 @@ import { clusterRoleApi, Role, roleApi } from "../../api/endpoints"; import { autobind } from "../../utils"; -import { KubeObjectStore } from "../../kube-object.store"; +import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store"; import { apiManager } from "../../api/api-manager"; @autobind() @@ -24,15 +24,13 @@ export class RolesStore extends KubeObjectStore { return clusterRoleApi.get(params); } - protected loadItems(namespaces?: string[]): Promise { - if (namespaces) { - return Promise.all( - namespaces.map(namespace => roleApi.list({ namespace })) - ).then(items => items.flat()); - } else { - return Promise.all([clusterRoleApi.list(), roleApi.list()]) - .then(items => items.flat()); - } + protected async loadItems(params: KubeObjectStoreLoadingParams): Promise { + const items = await Promise.all([ + super.loadItems({ ...params, api: clusterRoleApi }), + super.loadItems({ ...params, api: roleApi }), + ]); + + return items.flat(); } protected async createItem(params: { name: string; namespace?: string }, data?: Partial) { @@ -49,4 +47,4 @@ export const rolesStore = new RolesStore(); apiManager.registerStore(rolesStore, [ roleApi, clusterRoleApi, -]); \ No newline at end of file +]); diff --git a/src/renderer/components/+user-management-service-accounts/index.ts b/src/renderer/components/+user-management-service-accounts/index.ts index fd45e28288..bd81292bf1 100644 --- a/src/renderer/components/+user-management-service-accounts/index.ts +++ b/src/renderer/components/+user-management-service-accounts/index.ts @@ -1,3 +1,3 @@ export * from "./service-accounts"; export * from "./service-accounts-details"; -export * from "./create-service-account-dialog"; \ No newline at end of file +export * from "./create-service-account-dialog"; diff --git a/src/renderer/components/+user-management/index.ts b/src/renderer/components/+user-management/index.ts index 6f29869b9b..4ff825df97 100644 --- a/src/renderer/components/+user-management/index.ts +++ b/src/renderer/components/+user-management/index.ts @@ -1,2 +1,2 @@ export * from "./user-management"; -export * from "./user-management.route"; \ No newline at end of file +export * from "./user-management.route"; diff --git a/src/renderer/components/+workloads-overview/overview-statuses.tsx b/src/renderer/components/+workloads-overview/overview-statuses.tsx index 78adecb6df..33e5aa37c5 100644 --- a/src/renderer/components/+workloads-overview/overview-statuses.tsx +++ b/src/renderer/components/+workloads-overview/overview-statuses.tsx @@ -27,7 +27,7 @@ export class OverviewStatuses extends React.Component { @autobind() renderWorkload(resource: KubeResource): React.ReactElement { const store = workloadStores[resource]; - const items = store.getAllByNs(namespaceStore.contextNs); + const items = store.getAllByNs(namespaceStore.getContextNamespaces()); return (
diff --git a/src/renderer/components/+workloads-overview/overview.tsx b/src/renderer/components/+workloads-overview/overview.tsx index 318ad53f77..351b57462c 100644 --- a/src/renderer/components/+workloads-overview/overview.tsx +++ b/src/renderer/components/+workloads-overview/overview.tsx @@ -17,81 +17,65 @@ import { cronJobStore } from "../+workloads-cronjobs/cronjob.store"; import { Events } from "../+events"; import { KubeObjectStore } from "../../kube-object.store"; import { isAllowedResource } from "../../../common/rbac"; +import { namespaceStore } from "../+namespaces/namespace.store"; interface Props extends RouteComponentProps { } @observer export class WorkloadsOverview extends React.Component { + @observable isLoading = false; @observable isUnmounting = false; async componentDidMount() { - const stores: KubeObjectStore[] = []; + const stores: KubeObjectStore[] = [ + isAllowedResource("pods") && podsStore, + isAllowedResource("deployments") && deploymentStore, + isAllowedResource("daemonsets") && daemonSetStore, + isAllowedResource("statefulsets") && statefulSetStore, + isAllowedResource("replicasets") && replicaSetStore, + isAllowedResource("jobs") && jobStore, + isAllowedResource("cronjobs") && cronJobStore, + isAllowedResource("events") && eventStore, + ].filter(Boolean); - if (isAllowedResource("pods")) { - stores.push(podsStore); - } + const unsubscribeMap = new Map void>(); - if (isAllowedResource("deployments")) { - stores.push(deploymentStore); - } + const loadStores = async () => { + this.isLoading = true; - if (isAllowedResource("daemonsets")) { - stores.push(daemonSetStore); - } + for (const store of stores) { + if (this.isUnmounting) break; - if (isAllowedResource("statefulsets")) { - stores.push(statefulSetStore); - } + try { + await store.loadAll(); + unsubscribeMap.get(store)?.(); // unsubscribe previous watcher + unsubscribeMap.set(store, store.subscribe()); + } catch (error) { + console.error("loading store error", error); + } + } + this.isLoading = false; + }; - if (isAllowedResource("replicasets")) { - stores.push(replicaSetStore); - } + namespaceStore.onContextChange(loadStores, { + fireImmediately: true, + }); - if (isAllowedResource("jobs")) { - stores.push(jobStore); - } - - if (isAllowedResource("cronjobs")) { - stores.push(cronJobStore); - } - - if (isAllowedResource("events")) { - stores.push(eventStore); - } - - const unsubscribeList: Array<() => void> = []; - - for (const store of stores) { - await store.loadAll(); - unsubscribeList.push(store.subscribe()); - } - - await when(() => this.isUnmounting); - unsubscribeList.forEach(dispose => dispose()); + await when(() => this.isUnmounting && !this.isLoading); + unsubscribeMap.forEach(dispose => dispose()); + unsubscribeMap.clear(); } componentWillUnmount() { this.isUnmounting = true; } - get contents() { - return ( - <> - - { isAllowedResource("events") && } - - ); - } - render() { return (
- {this.contents} + + {isAllowedResource("events") && }
); } diff --git a/src/renderer/components/+workloads-pods/__tests__/pod-tolerations.test.tsx b/src/renderer/components/+workloads-pods/__tests__/pod-tolerations.test.tsx new file mode 100644 index 0000000000..dbde813e5a --- /dev/null +++ b/src/renderer/components/+workloads-pods/__tests__/pod-tolerations.test.tsx @@ -0,0 +1,59 @@ +/** + * @jest-environment jsdom + */ + +import React from "react"; +import "@testing-library/jest-dom/extend-expect"; +import { fireEvent, render } from "@testing-library/react"; +import { IToleration } from "../../../api/workload-kube-object"; +import { PodTolerations } from "../pod-tolerations"; + +const tolerations: IToleration[] =[ + { + key: "CriticalAddonsOnly", + operator: "Exist", + effect: "NoExecute", + tolerationSeconds: 3600 + }, + { + key: "node.kubernetes.io/not-ready", + operator: "NoExist", + effect: "NoSchedule", + tolerationSeconds: 7200 + }, +]; + +describe("", () => { + it("renders w/o errors", () => { + const { container } = render(); + + expect(container).toBeInstanceOf(HTMLElement); + }); + + it("shows all tolerations", () => { + const { container } = render(); + const rows = container.querySelectorAll(".TableRow"); + + expect(rows[0].querySelector(".key").textContent).toBe("CriticalAddonsOnly"); + expect(rows[0].querySelector(".operator").textContent).toBe("Exist"); + expect(rows[0].querySelector(".effect").textContent).toBe("NoExecute"); + expect(rows[0].querySelector(".seconds").textContent).toBe("3600"); + + expect(rows[1].querySelector(".key").textContent).toBe("node.kubernetes.io/not-ready"); + expect(rows[1].querySelector(".operator").textContent).toBe("NoExist"); + expect(rows[1].querySelector(".effect").textContent).toBe("NoSchedule"); + expect(rows[1].querySelector(".seconds").textContent).toBe("7200"); + }); + + it("sorts table properly", () => { + const { container, getByText } = render(); + const headCell = getByText("Key"); + + fireEvent.click(headCell); + fireEvent.click(headCell); + + const rows = container.querySelectorAll(".TableRow"); + + expect(rows[0].querySelector(".key").textContent).toBe("node.kubernetes.io/not-ready"); + }); +}); diff --git a/src/renderer/components/+workloads-pods/index.ts b/src/renderer/components/+workloads-pods/index.ts index f3181cb3a2..cc7782911c 100644 --- a/src/renderer/components/+workloads-pods/index.ts +++ b/src/renderer/components/+workloads-pods/index.ts @@ -1,2 +1,2 @@ export * from "./pods"; -export * from "./pod-details"; \ No newline at end of file +export * from "./pod-details"; diff --git a/src/renderer/components/+workloads-pods/pod-details-statuses.tsx b/src/renderer/components/+workloads-pods/pod-details-statuses.tsx index 5ce8465e72..1e0f765381 100644 --- a/src/renderer/components/+workloads-pods/pod-details-statuses.tsx +++ b/src/renderer/components/+workloads-pods/pod-details-statuses.tsx @@ -27,4 +27,4 @@ export class PodDetailsStatuses extends React.Component {
); } -} \ No newline at end of file +} diff --git a/src/renderer/components/+workloads-pods/pod-details-tolerations.scss b/src/renderer/components/+workloads-pods/pod-details-tolerations.scss index 0aa68fa1d6..1ac932cd9d 100644 --- a/src/renderer/components/+workloads-pods/pod-details-tolerations.scss +++ b/src/renderer/components/+workloads-pods/pod-details-tolerations.scss @@ -1,5 +1,23 @@ .PodDetailsTolerations { - .toleration { - margin-bottom: $margin; + grid-template-columns: auto; + + .PodTolerations { + margin-top: var(--margin); + } + + // Expanding value cell to cover 2 columns (whole Drawer width) + + > .name { + grid-row-start: 1; + grid-column-start: 1; + } + + > .value { + grid-row-start: 1; + grid-column-start: 1; + } + + .DrawerParamToggler > .params { + margin-left: var(--drawer-item-title-width); } } \ No newline at end of file diff --git a/src/renderer/components/+workloads-pods/pod-details-tolerations.tsx b/src/renderer/components/+workloads-pods/pod-details-tolerations.tsx index 8b67502e26..67bd5a07d0 100644 --- a/src/renderer/components/+workloads-pods/pod-details-tolerations.tsx +++ b/src/renderer/components/+workloads-pods/pod-details-tolerations.tsx @@ -1,10 +1,11 @@ import "./pod-details-tolerations.scss"; import React from "react"; -import { Pod, Deployment, DaemonSet, StatefulSet, ReplicaSet, Job } from "../../api/endpoints"; import { DrawerParamToggler, DrawerItem } from "../drawer"; +import { WorkloadKubeObject } from "../../api/workload-kube-object"; +import { PodTolerations } from "./pod-tolerations"; interface Props { - workload: Pod | Deployment | DaemonSet | StatefulSet | ReplicaSet | Job; + workload: WorkloadKubeObject; } export class PodDetailsTolerations extends React.Component { @@ -17,20 +18,7 @@ export class PodDetailsTolerations extends React.Component { return ( - { - tolerations.map((toleration, index) => { - const { key, operator, effect, tolerationSeconds } = toleration; - - return ( -
- {key} - {operator && {operator}} - {effect && {effect}} - {!!tolerationSeconds && {tolerationSeconds}} -
- ); - }) - } +
); diff --git a/src/renderer/components/+workloads-pods/pod-tolerations.scss b/src/renderer/components/+workloads-pods/pod-tolerations.scss new file mode 100644 index 0000000000..b840697685 --- /dev/null +++ b/src/renderer/components/+workloads-pods/pod-tolerations.scss @@ -0,0 +1,14 @@ +.PodTolerations { + .TableHead { + background-color: var(--drawerSubtitleBackground); + } + + .TableCell { + white-space: normal; + word-break: normal; + + &.key { + flex-grow: 3; + } + } +} \ No newline at end of file diff --git a/src/renderer/components/+workloads-pods/pod-tolerations.tsx b/src/renderer/components/+workloads-pods/pod-tolerations.tsx new file mode 100644 index 0000000000..e8d3d7d099 --- /dev/null +++ b/src/renderer/components/+workloads-pods/pod-tolerations.tsx @@ -0,0 +1,63 @@ +import "./pod-tolerations.scss"; +import React from "react"; +import uniqueId from "lodash/uniqueId"; + +import { IToleration } from "../../api/workload-kube-object"; +import { Table, TableCell, TableHead, TableRow } from "../table"; + +interface Props { + tolerations: IToleration[]; +} + +enum sortBy { + Key = "key", + Operator = "operator", + Effect = "effect", + Seconds = "seconds", +} + +const sortingCallbacks = { + [sortBy.Key]: (toleration: IToleration) => toleration.key, + [sortBy.Operator]: (toleration: IToleration) => toleration.operator, + [sortBy.Effect]: (toleration: IToleration) => toleration.effect, + [sortBy.Seconds]: (toleration: IToleration) => toleration.tolerationSeconds, +}; + +const getTableRow = (toleration: IToleration) => { + const { key, operator, effect, tolerationSeconds } = toleration; + + return ( + + {key} + {operator} + {effect} + {tolerationSeconds} + + ); +}; + +export function PodTolerations({ tolerations }: Props) { + return ( + + + Key + Operator + Effect + Seconds + + { + tolerations.map(getTableRow) + } +
+ ); +} diff --git a/src/renderer/components/+workloads-pods/pods.tsx b/src/renderer/components/+workloads-pods/pods.tsx index 2296b98317..a59c9d79d2 100644 --- a/src/renderer/components/+workloads-pods/pods.tsx +++ b/src/renderer/components/+workloads-pods/pods.tsx @@ -19,8 +19,7 @@ import { lookupApiLink } from "../../api/kube-api"; import { KubeObjectStatusIcon } from "../kube-object-status-icon"; import { Badge } from "../badge"; - -enum sortBy { +enum columnId { name = "name", namespace = "namespace", containers = "containers", @@ -77,15 +76,15 @@ export class Pods extends React.Component { tableId = "workloads_pods" isConfigurable sortingCallbacks={{ - [sortBy.name]: (pod: Pod) => pod.getName(), - [sortBy.namespace]: (pod: Pod) => pod.getNs(), - [sortBy.containers]: (pod: Pod) => pod.getContainers().length, - [sortBy.restarts]: (pod: Pod) => pod.getRestartsCount(), - [sortBy.owners]: (pod: Pod) => pod.getOwnerRefs().map(ref => ref.kind), - [sortBy.qos]: (pod: Pod) => pod.getQosClass(), - [sortBy.node]: (pod: Pod) => pod.getNodeName(), - [sortBy.age]: (pod: Pod) => pod.metadata.creationTimestamp, - [sortBy.status]: (pod: Pod) => pod.getStatusMessage(), + [columnId.name]: (pod: Pod) => pod.getName(), + [columnId.namespace]: (pod: Pod) => pod.getNs(), + [columnId.containers]: (pod: Pod) => pod.getContainers().length, + [columnId.restarts]: (pod: Pod) => pod.getRestartsCount(), + [columnId.owners]: (pod: Pod) => pod.getOwnerRefs().map(ref => ref.kind), + [columnId.qos]: (pod: Pod) => pod.getQosClass(), + [columnId.node]: (pod: Pod) => pod.getNodeName(), + [columnId.age]: (pod: Pod) => pod.metadata.creationTimestamp, + [columnId.status]: (pod: Pod) => pod.getStatusMessage(), }} searchFilters={[ (pod: Pod) => pod.getSearchFields(), @@ -95,16 +94,16 @@ export class Pods extends React.Component { ]} renderHeaderTitle="Pods" renderTableHeader={[ - { title: "Name", className: "name", sortBy: sortBy.name }, - { className: "warning", showWithColumn: "name" }, - { title: "Namespace", className: "namespace", sortBy: sortBy.namespace }, - { title: "Containers", className: "containers", sortBy: sortBy.containers }, - { title: "Restarts", className: "restarts", sortBy: sortBy.restarts }, - { title: "Controlled By", className: "owners", sortBy: sortBy.owners }, - { title: "Node", className: "node", sortBy: sortBy.node }, - { title: "QoS", className: "qos", sortBy: sortBy.qos }, - { title: "Age", className: "age", sortBy: sortBy.age }, - { title: "Status", className: "status", sortBy: sortBy.status }, + { title: "Name", className: "name", sortBy: columnId.name, id: columnId.name }, + { className: "warning", showWithColumn: columnId.name }, + { title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace }, + { title: "Containers", className: "containers", sortBy: columnId.containers, id: columnId.containers }, + { title: "Restarts", className: "restarts", sortBy: columnId.restarts, id: columnId.restarts }, + { title: "Controlled By", className: "owners", sortBy: columnId.owners, id: columnId.owners }, + { title: "Node", className: "node", sortBy: columnId.node, id: columnId.node }, + { title: "QoS", className: "qos", sortBy: columnId.qos, id: columnId.qos }, + { title: "Age", className: "age", sortBy: columnId.age, id: columnId.age }, + { title: "Status", className: "status", sortBy: columnId.status, id: columnId.status }, ]} renderTableContents={(pod: Pod) => [ , diff --git a/src/renderer/components/+workloads-statefulsets/index.ts b/src/renderer/components/+workloads-statefulsets/index.ts index 1cb72d701a..af942b604f 100644 --- a/src/renderer/components/+workloads-statefulsets/index.ts +++ b/src/renderer/components/+workloads-statefulsets/index.ts @@ -1,2 +1,2 @@ export * from "./statefulsets"; -export * from "./statefulset-details"; \ No newline at end of file +export * from "./statefulset-details"; diff --git a/src/renderer/components/ace-editor/ace-editor.tsx b/src/renderer/components/ace-editor/ace-editor.tsx index 68ef92635a..2dceb48bba 100644 --- a/src/renderer/components/ace-editor/ace-editor.tsx +++ b/src/renderer/components/ace-editor/ace-editor.tsx @@ -154,4 +154,4 @@ export class AceEditor extends React.Component { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/ace-editor/index.ts b/src/renderer/components/ace-editor/index.ts index 7bfc7c01ea..173845abab 100644 --- a/src/renderer/components/ace-editor/index.ts +++ b/src/renderer/components/ace-editor/index.ts @@ -1 +1 @@ -export * from "./ace-editor"; \ No newline at end of file +export * from "./ace-editor"; diff --git a/src/renderer/components/add-remove-buttons/index.ts b/src/renderer/components/add-remove-buttons/index.ts index 825c59d7d2..fa2deb84ec 100644 --- a/src/renderer/components/add-remove-buttons/index.ts +++ b/src/renderer/components/add-remove-buttons/index.ts @@ -1 +1 @@ -export * from "./add-remove-buttons"; \ No newline at end of file +export * from "./add-remove-buttons"; diff --git a/src/renderer/components/animate/index.ts b/src/renderer/components/animate/index.ts index 080c5446c8..36d812de20 100644 --- a/src/renderer/components/animate/index.ts +++ b/src/renderer/components/animate/index.ts @@ -1 +1 @@ -export * from "./animate"; \ No newline at end of file +export * from "./animate"; diff --git a/src/renderer/components/chart/background-block.plugin.ts b/src/renderer/components/chart/background-block.plugin.ts index 1d39f71aed..ff4816c4dd 100644 --- a/src/renderer/components/chart/background-block.plugin.ts +++ b/src/renderer/components/chart/background-block.plugin.ts @@ -39,4 +39,4 @@ export const BackgroundBlock = { ctx.stroke(); ctx.restore(); } -}; \ No newline at end of file +}; diff --git a/src/renderer/components/chart/bar-chart.tsx b/src/renderer/components/chart/bar-chart.tsx index 69b65b10c9..4f80258703 100644 --- a/src/renderer/components/chart/bar-chart.tsx +++ b/src/renderer/components/chart/bar-chart.tsx @@ -220,4 +220,4 @@ export const cpuOptions: ChartOptions = { } } } -}; \ No newline at end of file +}; diff --git a/src/renderer/components/chart/chart.tsx b/src/renderer/components/chart/chart.tsx index b7e621be22..e42a308848 100644 --- a/src/renderer/components/chart/chart.tsx +++ b/src/renderer/components/chart/chart.tsx @@ -213,4 +213,4 @@ export class Chart extends React.Component { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/chart/index.ts b/src/renderer/components/chart/index.ts index a9db66c298..d75ddf7a2f 100644 --- a/src/renderer/components/chart/index.ts +++ b/src/renderer/components/chart/index.ts @@ -1,3 +1,3 @@ export * from "./chart"; export * from "./pie-chart"; -export * from "./bar-chart"; \ No newline at end of file +export * from "./bar-chart"; diff --git a/src/renderer/components/chart/pie-chart.tsx b/src/renderer/components/chart/pie-chart.tsx index 1c629ab505..939d6bb612 100644 --- a/src/renderer/components/chart/pie-chart.tsx +++ b/src/renderer/components/chart/pie-chart.tsx @@ -64,4 +64,4 @@ export class PieChart extends React.Component { ChartJS.Tooltip.positioners.cursor = function (elements: any, position: { x: number; y: number }) { return position; -}; \ No newline at end of file +}; diff --git a/src/renderer/components/chart/useRealTimeMetrics.ts b/src/renderer/components/chart/useRealTimeMetrics.ts index 69e4e3da7f..b01629e8e9 100644 --- a/src/renderer/components/chart/useRealTimeMetrics.ts +++ b/src/renderer/components/chart/useRealTimeMetrics.ts @@ -42,4 +42,4 @@ export function useRealTimeMetrics(metrics: IMetricValues, chartData: IChartData } return data; -} \ No newline at end of file +} diff --git a/src/renderer/components/chart/zebra-stripes.plugin.ts b/src/renderer/components/chart/zebra-stripes.plugin.ts index f934f88fb2..3a85f8d0a2 100644 --- a/src/renderer/components/chart/zebra-stripes.plugin.ts +++ b/src/renderer/components/chart/zebra-stripes.plugin.ts @@ -95,4 +95,4 @@ export const ZebraStripes = { cover.style.backgroundPositionX = `${-step * minutes}px`; } } -}; \ No newline at end of file +}; diff --git a/src/renderer/components/checkbox/checkbox.tsx b/src/renderer/components/checkbox/checkbox.tsx index f97740a874..8d452a1198 100644 --- a/src/renderer/components/checkbox/checkbox.tsx +++ b/src/renderer/components/checkbox/checkbox.tsx @@ -50,4 +50,4 @@ export class Checkbox extends React.PureComponent { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/checkbox/index.ts b/src/renderer/components/checkbox/index.ts index 7af8873e06..057f167821 100644 --- a/src/renderer/components/checkbox/index.ts +++ b/src/renderer/components/checkbox/index.ts @@ -1 +1 @@ -export * from "./checkbox"; \ No newline at end of file +export * from "./checkbox"; diff --git a/src/renderer/components/cluster-icon/index.ts b/src/renderer/components/cluster-icon/index.ts index 4e1858939f..7879490b85 100644 --- a/src/renderer/components/cluster-icon/index.ts +++ b/src/renderer/components/cluster-icon/index.ts @@ -1 +1 @@ -export * from "./cluster-icon"; \ No newline at end of file +export * from "./cluster-icon"; diff --git a/src/renderer/components/confirm-dialog/index.ts b/src/renderer/components/confirm-dialog/index.ts index dfcd83ded3..4627fd6882 100644 --- a/src/renderer/components/confirm-dialog/index.ts +++ b/src/renderer/components/confirm-dialog/index.ts @@ -1 +1 @@ -export * from "./confirm-dialog"; \ No newline at end of file +export * from "./confirm-dialog"; diff --git a/src/renderer/components/dock/dock-tabs.tsx b/src/renderer/components/dock/dock-tabs.tsx index 02e8f958e6..d0a3c3d125 100644 --- a/src/renderer/components/dock/dock-tabs.tsx +++ b/src/renderer/components/dock/dock-tabs.tsx @@ -48,4 +48,4 @@ export const DockTabs = ({ tabs, autoFocus, selectedTab, onChangeTab }: Props) = {tabs.map(tab => {renderTab(tab)})} ); -}; \ No newline at end of file +}; diff --git a/src/renderer/components/dock/info-panel.scss b/src/renderer/components/dock/info-panel.scss index 482dbee02d..cf9b3268b2 100644 --- a/src/renderer/components/dock/info-panel.scss +++ b/src/renderer/components/dock/info-panel.scss @@ -1,12 +1,16 @@ .InfoPanel { @include hidden-scrollbar; - background: $dockInfoBackground; - padding: $padding $padding * 2; + background: var(--dockInfoBackground); + padding: var(--padding) calc(var(--padding) * 2); flex-shrink: 0; .Spinner { - margin-right: $padding; + margin-right: var(--padding); + } + + .Badge { + background-color: var(--dockBadgeBackground); } > .controls { @@ -15,8 +19,8 @@ &:not(:empty) + .info { min-height: 25px; - padding-left: $padding; - padding-right: $padding; + padding-left: var(--padding); + padding-right: var(--padding); } } } \ No newline at end of file diff --git a/src/renderer/components/dock/log-controls.tsx b/src/renderer/components/dock/log-controls.tsx index 566dc15ba4..8400aef584 100644 --- a/src/renderer/components/dock/log-controls.tsx +++ b/src/renderer/components/dock/log-controls.tsx @@ -42,7 +42,12 @@ export const LogControls = observer((props: Props) => { return (
- {since && `Logs from ${new Date(since[0]).toLocaleString()}`} + {since && ( + + Logs from{" "} + {new Date(since[0]).toLocaleString()} + + )}
-
+
{label}
{link} diff --git a/src/renderer/components/drawer/drawer.scss b/src/renderer/components/drawer/drawer.scss index b34b3b5965..8b7fc27993 100644 --- a/src/renderer/components/drawer/drawer.scss +++ b/src/renderer/components/drawer/drawer.scss @@ -69,7 +69,6 @@ padding: var(--spacing); .Table .TableHead { - background-color: $contentColor; border-bottom: 1px solid $borderFaintColor; } } diff --git a/src/renderer/components/editable-list/index.ts b/src/renderer/components/editable-list/index.ts index cc0293acd6..1dc93d5df7 100644 --- a/src/renderer/components/editable-list/index.ts +++ b/src/renderer/components/editable-list/index.ts @@ -1 +1 @@ -export * from "./editable-list"; \ No newline at end of file +export * from "./editable-list"; diff --git a/src/renderer/components/error-boundary/index.ts b/src/renderer/components/error-boundary/index.ts index cdcf838466..90e954fb2e 100644 --- a/src/renderer/components/error-boundary/index.ts +++ b/src/renderer/components/error-boundary/index.ts @@ -1 +1 @@ -export * from "./error-boundary"; \ No newline at end of file +export * from "./error-boundary"; diff --git a/src/renderer/components/file-picker/file-picker.tsx b/src/renderer/components/file-picker/file-picker.tsx index 14cd6c07e8..1a52fe4973 100644 --- a/src/renderer/components/file-picker/file-picker.tsx +++ b/src/renderer/components/file-picker/file-picker.tsx @@ -209,4 +209,4 @@ export class FilePicker extends React.Component { return ; } } -} \ No newline at end of file +} diff --git a/src/renderer/components/file-picker/index.ts b/src/renderer/components/file-picker/index.ts index f58aec1470..28c490afab 100644 --- a/src/renderer/components/file-picker/index.ts +++ b/src/renderer/components/file-picker/index.ts @@ -1 +1 @@ -export * from "./file-picker"; \ No newline at end of file +export * from "./file-picker"; diff --git a/src/renderer/components/icon/index.ts b/src/renderer/components/icon/index.ts index 5cdcefa69c..b975409af4 100644 --- a/src/renderer/components/icon/index.ts +++ b/src/renderer/components/icon/index.ts @@ -1 +1 @@ -export * from "./icon"; \ No newline at end of file +export * from "./icon"; diff --git a/src/renderer/components/input/search-input-url.tsx b/src/renderer/components/input/search-input-url.tsx index 2b1045ede2..c0e00d6e56 100644 --- a/src/renderer/components/input/search-input-url.tsx +++ b/src/renderer/components/input/search-input-url.tsx @@ -54,4 +54,4 @@ export class SearchInputUrl extends React.Component { /> ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/item-object-list/index.tsx b/src/renderer/components/item-object-list/index.tsx index b0b106b298..87ba0e908a 100644 --- a/src/renderer/components/item-object-list/index.tsx +++ b/src/renderer/components/item-object-list/index.tsx @@ -1 +1 @@ -export * from "./item-list-layout"; \ No newline at end of file +export * from "./item-list-layout"; diff --git a/src/renderer/components/item-object-list/item-list-layout.scss b/src/renderer/components/item-object-list/item-list-layout.scss index 9bdc2f943d..0008ffd527 100644 --- a/src/renderer/components/item-object-list/item-list-layout.scss +++ b/src/renderer/components/item-object-list/item-list-layout.scss @@ -36,3 +36,14 @@ } } +.ItemListLayoutVisibilityMenu { + .MenuItem { + padding: 0; + } + + .Checkbox { + width: 100%; + padding: var(--spacing); + cursor: pointer; + } +} diff --git a/src/renderer/components/item-object-list/item-list-layout.tsx b/src/renderer/components/item-object-list/item-list-layout.tsx index 38e0e0218d..aaeb7438ea 100644 --- a/src/renderer/components/item-object-list/item-list-layout.tsx +++ b/src/renderer/components/item-object-list/item-list-layout.tsx @@ -1,12 +1,11 @@ import "./item-list-layout.scss"; -import "./table-menu.scss"; import groupBy from "lodash/groupBy"; import React, { ReactNode } from "react"; -import { computed, observable, reaction, toJS, when } from "mobx"; +import { computed, IReactionDisposer, observable, reaction, toJS } from "mobx"; import { disposeOnUnmount, observer } from "mobx-react"; import { ConfirmDialog, ConfirmDialogParams } from "../confirm-dialog"; -import { TableSortCallback, Table, TableCell, TableCellProps, TableHead, TableProps, TableRow, TableRowProps } from "../table"; +import { Table, TableCell, TableCellProps, TableHead, TableProps, TableRow, TableRowProps, TableSortCallback } from "../table"; import { autobind, createStorage, cssNames, IClassName, isReactNode, noop, prevDefault, stopPropagation } from "../../utils"; import { AddRemoveButtons, AddRemoveButtonsProps } from "../add-remove-buttons"; import { NoItems } from "../no-items"; @@ -19,11 +18,10 @@ import { PageFiltersList } from "./page-filters-list"; import { PageFiltersSelect } from "./page-filters-select"; import { NamespaceSelectFilter } from "../+namespaces/namespace-select"; import { themeStore } from "../../theme.store"; -import { MenuActions} from "../menu/menu-actions"; +import { MenuActions } from "../menu/menu-actions"; import { MenuItem } from "../menu"; import { Checkbox } from "../checkbox"; import { userStore } from "../../../common/user-store"; -import logger from "../../../main/logger"; // todo: refactor, split to small re-usable components @@ -98,10 +96,11 @@ interface ItemListLayoutUserSettings { @observer export class ItemListLayout extends React.Component { static defaultProps = defaultProps as object; - @observable hiddenColumnNames = new Set(); + + private watchDisposers: IReactionDisposer[] = []; + @observable isUnmounting = false; - // default user settings (ui show-hide tweaks mostly) @observable userSettings: ItemListLayoutUserSettings = { showAppliedFilters: false, }; @@ -120,31 +119,54 @@ export class ItemListLayout extends React.Component { } async componentDidMount() { - const { store, dependentStores, isClusterScoped, tableId } = this.props; + const { isClusterScoped, isConfigurable, tableId } = this.props; - if (this.canBeConfigured) this.hiddenColumnNames = new Set(userStore.preferences?.hiddenTableColumns?.[tableId]); + if (isConfigurable && !tableId) { + throw new Error("[ItemListLayout]: configurable list require props.tableId to be specified"); + } - const stores = [store, ...dependentStores]; + this.loadStores(); - if (!isClusterScoped) stores.push(namespaceStore); - - try { - stores.map(store => store.reset()); - await Promise.all(stores.map(store => store.loadAll())); - const subscriptions = stores.map(store => store.subscribe()); - - await when(() => this.isUnmounting); - subscriptions.forEach(dispose => dispose()); // unsubscribe all - } catch (error) { - console.log("catched", error); + if (!isClusterScoped) { + disposeOnUnmount(this, [ + namespaceStore.onContextChange(() => this.loadStores()) + ]); } } - componentWillUnmount() { + async componentWillUnmount() { this.isUnmounting = true; - const { store, isSelectable } = this.props; + this.unsubscribeStores(); + } - if (isSelectable) store.resetSelection(); + @computed get stores() { + const { store, dependentStores } = this.props; + + return new Set([store, ...dependentStores]); + } + + async loadStores() { + this.unsubscribeStores(); // reset first + + // load + for (const store of this.stores) { + if (this.isUnmounting) { + this.unsubscribeStores(); + break; + } + + try { + await store.loadAll(); + this.watchDisposers.push(store.subscribe()); + } catch (error) { + console.error("loading store error", error); + } + } + } + + unsubscribeStores() { + this.watchDisposers.forEach(dispose => dispose()); + this.watchDisposers.length = 0; } private filterCallbacks: { [type: string]: ItemsFilter } = { @@ -180,9 +202,7 @@ export class ItemListLayout extends React.Component { }; @computed get isReady() { - const { isReady, store } = this.props; - - return typeof isReady == "boolean" ? isReady : store.isLoaded; + return this.props.isReady ?? this.props.store.isLoaded; } @computed get filters() { @@ -228,42 +248,6 @@ export class ItemListLayout extends React.Component { return this.applyFilters(filterItems, allItems); } - updateColumnFilter(checkboxValue: boolean, columnName: string) { - if (checkboxValue){ - this.hiddenColumnNames.delete(columnName); - } else { - this.hiddenColumnNames.add(columnName); - } - - if (this.canBeConfigured) { - userStore.preferences.hiddenTableColumns[this.props.tableId] = Array.from(this.hiddenColumnNames); - } - } - - columnIsVisible(index: number): boolean { - const {renderTableHeader} = this.props; - - if (!this.canBeConfigured) return true; - - return !this.hiddenColumnNames.has(renderTableHeader[index].showWithColumn ?? renderTableHeader[index].className); - } - - get canBeConfigured(): boolean { - const { isConfigurable, tableId, renderTableHeader } = this.props; - - if (!isConfigurable || !tableId) { - return false; - } - - if (!renderTableHeader?.every(({ className }) => className)) { - logger.warning("[ItemObjectList]: cannot configure an object list without all headers being identifiable"); - - return false; - } - - return true; - } - @autobind() getRow(uid: string) { const { @@ -295,20 +279,18 @@ export class ItemListLayout extends React.Component { /> )} { - renderTableContents(item) - .map((content, index) => { - const cellProps: TableCellProps = isReactNode(content) ? { children: content } : content; + renderTableContents(item).map((content, index) => { + const cellProps: TableCellProps = isReactNode(content) ? { children: content } : content; + const headCell = renderTableHeader?.[index]; - if (copyClassNameFromHeadCells && renderTableHeader) { - const headCell = renderTableHeader[index]; + if (copyClassNameFromHeadCells && headCell) { + cellProps.className = cssNames(cellProps.className, headCell.className); + } - if (headCell) { - cellProps.className = cssNames(cellProps.className, headCell.className); - } - } - - return this.columnIsVisible(index) ? : null; - }) + if (!headCell || !this.isHiddenColumn(headCell)) { + return ; + } + }) } {renderItemMenu && ( @@ -347,16 +329,11 @@ export class ItemListLayout extends React.Component { return; } - return ; + return ; } renderNoItems() { - const { allItems, items, filters } = this; - const allItemsCount = allItems.length; - const itemsCount = items.length; - const isFiltered = filters.length > 0 && allItemsCount > itemsCount; - - if (isFiltered) { + if (this.filters.length > 0) { return ( No items found. @@ -369,7 +346,7 @@ export class ItemListLayout extends React.Component { ); } - return ; + return ; } renderHeaderContent(placeholders: IHeaderPlaceholders): ReactNode { @@ -413,12 +390,12 @@ export class ItemListLayout extends React.Component { title:
{title}
, info: this.renderInfo(), filters: <> - {!isClusterScoped && } + {!isClusterScoped && } + }}/> , - search: , + search: , }; let header = this.renderHeaderContent(placeholders); @@ -442,10 +419,40 @@ export class ItemListLayout extends React.Component { ); } + renderTableHeader() { + const { renderTableHeader, isSelectable, isConfigurable, store } = this.props; + + if (!renderTableHeader) { + return; + } + + return ( + + {isSelectable && ( + store.toggleSelectionAll(this.items))} + /> + )} + {renderTableHeader.map((cellProps, index) => { + if (!this.isHiddenColumn(cellProps)) { + return ; + } + })} + {isConfigurable && ( + + {this.renderColumnVisibilityMenu()} + + )} + + ); + } + renderList() { const { - isSelectable, tableProps = {}, renderTableHeader, renderItemMenu, - store, hasDetailsView, addRemoveButtons = {}, virtual, sortingCallbacks, detailsItem + store, hasDetailsView, addRemoveButtons = {}, virtual, sortingCallbacks, detailsItem, + tableProps = {}, } = this.props; const { isReady, removeItemsDialog, items } = this; const { selectedItems } = store; @@ -454,7 +461,7 @@ export class ItemListLayout extends React.Component { return (
{!isReady && ( - + )} {isReady && ( { className: cssNames("box grow", tableProps.className, themeStore.activeTheme.type), })} > - {renderTableHeader && ( - - {isSelectable && ( - store.toggleSelectionAll(items))} - /> - )} - {renderTableHeader.map((cellProps, index) => this.columnIsVisible(index) ? : null)} - { renderItemMenu && - - {this.canBeConfigured && this.renderColumnMenu()} - - } - - )} + {this.renderTableHeader()} { !virtual && items.map(item => this.getRow(item.getId())) } @@ -502,24 +493,47 @@ export class ItemListLayout extends React.Component { ); } - renderColumnMenu() { - const { renderTableHeader} = this.props; + @computed get hiddenColumns() { + return userStore.getHiddenTableColumns(this.props.tableId); + } + + isHiddenColumn({ id: columnId, showWithColumn }: TableCellProps): boolean { + if (!this.props.isConfigurable) { + return false; + } + + return this.hiddenColumns.has(columnId) || ( + showWithColumn && this.hiddenColumns.has(showWithColumn) + ); + } + + updateColumnVisibility({ id: columnId }: TableCellProps, isVisible: boolean) { + const hiddenColumns = new Set(this.hiddenColumns); + + if (!isVisible) { + hiddenColumns.add(columnId); + } else { + hiddenColumns.delete(columnId); + } + + userStore.setHiddenTableColumns(this.props.tableId, hiddenColumns); + } + + renderColumnVisibilityMenu() { + const { renderTableHeader } = this.props; return ( - + {renderTableHeader.map((cellProps, index) => ( - !cellProps.showWithColumn && + !cellProps.showWithColumn && ( - `} - className = "MenuCheckbox" - value ={!this.hiddenColumnNames.has(cellProps.className)} - onChange = {(v) => this.updateColumnFilter(v, cellProps.className)} + `} + value={!this.isHiddenColumn(cellProps)} + onChange={isVisible => this.updateColumnVisibility(cellProps, isVisible)} /> + ) ))} ); diff --git a/src/renderer/components/item-object-list/page-filters.store.ts b/src/renderer/components/item-object-list/page-filters.store.ts index 9bff008aa6..d931cd2575 100644 --- a/src/renderer/components/item-object-list/page-filters.store.ts +++ b/src/renderer/components/item-object-list/page-filters.store.ts @@ -34,14 +34,14 @@ export class PageFiltersStore { namespaceStore.setContext(filteredNs); } }), - reaction(() => namespaceStore.contextNs.toJS(), contextNs => { + namespaceStore.onContextChange(namespaces => { const filteredNs = this.getValues(FilterType.NAMESPACE); - const isChanged = contextNs.length !== filteredNs.length; + const isChanged = namespaces.length !== filteredNs.length; if (isChanged) { this.filters.replace([ ...this.filters.filter(({ type }) => type !== FilterType.NAMESPACE), - ...contextNs.map(ns => ({ type: FilterType.NAMESPACE, value: ns })), + ...namespaces.map(ns => ({ type: FilterType.NAMESPACE, value: ns })), ]); } }, { diff --git a/src/renderer/components/item-object-list/table-menu.scss b/src/renderer/components/item-object-list/table-menu.scss deleted file mode 100644 index b7e41f54ca..0000000000 --- a/src/renderer/components/item-object-list/table-menu.scss +++ /dev/null @@ -1,4 +0,0 @@ -.MenuCheckbox { - width: 100%; - height: 100%; -} diff --git a/src/renderer/components/kube-object-status-icon/index.ts b/src/renderer/components/kube-object-status-icon/index.ts index 36751596a0..3ef2e6b29c 100644 --- a/src/renderer/components/kube-object-status-icon/index.ts +++ b/src/renderer/components/kube-object-status-icon/index.ts @@ -1 +1 @@ -export * from "./kube-object-status-icon"; \ No newline at end of file +export * from "./kube-object-status-icon"; diff --git a/src/renderer/components/kubeconfig-dialog/index.ts b/src/renderer/components/kubeconfig-dialog/index.ts index fdd244fe98..cb8c90cc14 100644 --- a/src/renderer/components/kubeconfig-dialog/index.ts +++ b/src/renderer/components/kubeconfig-dialog/index.ts @@ -1 +1 @@ -export * from "./kubeconfig-dialog"; \ No newline at end of file +export * from "./kubeconfig-dialog"; diff --git a/src/renderer/components/layout/__test__/main-layout-header.test.tsx b/src/renderer/components/layout/__test__/main-layout-header.test.tsx index b2a7bb5d93..499839072c 100644 --- a/src/renderer/components/layout/__test__/main-layout-header.test.tsx +++ b/src/renderer/components/layout/__test__/main-layout-header.test.tsx @@ -46,4 +46,4 @@ describe("", () => { expect(getByText("minikube")).toBeInTheDocument(); }); -}); \ No newline at end of file +}); diff --git a/src/renderer/components/layout/login-layout.tsx b/src/renderer/components/layout/login-layout.tsx index 8aa9c08e0b..669f783769 100755 --- a/src/renderer/components/layout/login-layout.tsx +++ b/src/renderer/components/layout/login-layout.tsx @@ -34,4 +34,4 @@ export class LoginLayout extends React.Component { ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/layout/sidebar-context.ts b/src/renderer/components/layout/sidebar-context.ts index fff192cba3..7001bbc319 100644 --- a/src/renderer/components/layout/sidebar-context.ts +++ b/src/renderer/components/layout/sidebar-context.ts @@ -4,4 +4,4 @@ export const SidebarContext = React.createContext({ pinned: export type SidebarContextValue = { pinned: boolean; -}; \ No newline at end of file +}; diff --git a/src/renderer/components/line-progress/index.ts b/src/renderer/components/line-progress/index.ts index 91942d706a..bd76106dbb 100644 --- a/src/renderer/components/line-progress/index.ts +++ b/src/renderer/components/line-progress/index.ts @@ -1 +1 @@ -export * from "./line-progress"; \ No newline at end of file +export * from "./line-progress"; diff --git a/src/renderer/components/markdown-viewer/index.ts b/src/renderer/components/markdown-viewer/index.ts index e82c6ba3c3..3c42af15f4 100644 --- a/src/renderer/components/markdown-viewer/index.ts +++ b/src/renderer/components/markdown-viewer/index.ts @@ -1 +1 @@ -export * from "./markdown-viewer"; \ No newline at end of file +export * from "./markdown-viewer"; diff --git a/src/renderer/components/markdown-viewer/markdown-viewer.tsx b/src/renderer/components/markdown-viewer/markdown-viewer.tsx index b1a2334b97..08478cb5a9 100644 --- a/src/renderer/components/markdown-viewer/markdown-viewer.tsx +++ b/src/renderer/components/markdown-viewer/markdown-viewer.tsx @@ -34,4 +34,4 @@ export class MarkdownViewer extends Component { /> ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/radio/index.ts b/src/renderer/components/radio/index.ts index 577923ef9c..0df0f30e50 100644 --- a/src/renderer/components/radio/index.ts +++ b/src/renderer/components/radio/index.ts @@ -1 +1 @@ -export * from "./radio"; \ No newline at end of file +export * from "./radio"; diff --git a/src/renderer/components/resource-metrics/index.ts b/src/renderer/components/resource-metrics/index.ts index 5438f760b4..a50f74ea8e 100644 --- a/src/renderer/components/resource-metrics/index.ts +++ b/src/renderer/components/resource-metrics/index.ts @@ -1,2 +1,2 @@ export * from "./resource-metrics"; -export * from "./resource-metrics-text"; \ No newline at end of file +export * from "./resource-metrics-text"; diff --git a/src/renderer/components/select/select.scss b/src/renderer/components/select/select.scss index f3fd6e47b0..445e59d003 100644 --- a/src/renderer/components/select/select.scss +++ b/src/renderer/components/select/select.scss @@ -3,11 +3,9 @@ html { $menuBackgroundColor: $contentColor; - $menuSelectedOptionBgc: $layoutBackground; --select-menu-bgc: #{$menuBackgroundColor}; --select-menu-border-color: #{$halfGray}; - --select-option-selected-bgc: #{$menuSelectedOptionBgc}; --select-option-selected-color: #{$selectOptionHoveredColor}; --select-option-focused-bgc: #{$colorInfo}; --select-option-focused-color: #{$textColorAccent}; @@ -95,7 +93,7 @@ html { } &--is-selected { - background: var(--select-option-selected-bgc); + background: var(--menuSelectedOptionBgc); color: var(--select-option-selected-color); } @@ -148,7 +146,6 @@ html { &.theme-light { --select-menu-bgc: white; --select-option-selected-color: $textColorSecondary; - --select-option-selected-bgc: $textColorSecondary; .Select { &__multi-value { diff --git a/src/renderer/components/slider/index.ts b/src/renderer/components/slider/index.ts index bc79daa3ff..67c45bb063 100644 --- a/src/renderer/components/slider/index.ts +++ b/src/renderer/components/slider/index.ts @@ -1 +1 @@ -export * from "./slider"; \ No newline at end of file +export * from "./slider"; diff --git a/src/renderer/components/status-brick/index.ts b/src/renderer/components/status-brick/index.ts index e16a2a8093..cc6d3e8879 100644 --- a/src/renderer/components/status-brick/index.ts +++ b/src/renderer/components/status-brick/index.ts @@ -1 +1 @@ -export * from "./status-brick"; \ No newline at end of file +export * from "./status-brick"; diff --git a/src/renderer/components/status-brick/status-brick.tsx b/src/renderer/components/status-brick/status-brick.tsx index 34c835c9fa..ced04acca4 100644 --- a/src/renderer/components/status-brick/status-brick.tsx +++ b/src/renderer/components/status-brick/status-brick.tsx @@ -19,4 +19,4 @@ export class StatusBrick extends React.Component { /> ); } -} \ No newline at end of file +} diff --git a/src/renderer/components/table/table-cell.tsx b/src/renderer/components/table/table-cell.tsx index 97335078f1..81e2f9f85f 100644 --- a/src/renderer/components/table/table-cell.tsx +++ b/src/renderer/components/table/table-cell.tsx @@ -9,13 +9,14 @@ import { Checkbox } from "../checkbox"; export type TableCellElem = React.ReactElement; export interface TableCellProps extends React.DOMAttributes { + id?: string; // used for configuration visibility of columns className?: string; title?: ReactNode; checkbox?: boolean; // render cell with a checkbox isChecked?: boolean; // mark checkbox as checked or not renderBoolean?: boolean; // show "true" or "false" for all of the children elements are "typeof boolean" sortBy?: TableSortBy; // column name, must be same as key in sortable object
- showWithColumn?: string // className of another column, if it is not empty the current column is not shown in the filter menu, visibility of this one is the same as a specified column, applicable to headers only + showWithColumn?: string // id of the column which follow same visibility rules _sorting?: Partial; //
sorting state, don't use this prop outside (!) _sort?(sortBy: TableSortBy): void; //
sort function, don't use this prop outside (!) _nowrap?: boolean; // indicator, might come from parent , don't use this prop outside (!) @@ -73,7 +74,7 @@ export class TableCell extends React.Component { const content = displayBooleans(displayBoolean, title || children); return ( -
+
{this.renderCheckbox()} {_nowrap ?
{content}
: content} {this.renderSortIcon()} diff --git a/src/renderer/components/virtual-list/index.ts b/src/renderer/components/virtual-list/index.ts index 4e5b065f43..3fad81848e 100644 --- a/src/renderer/components/virtual-list/index.ts +++ b/src/renderer/components/virtual-list/index.ts @@ -1 +1 @@ -export * from "./virtual-list"; \ No newline at end of file +export * from "./virtual-list"; diff --git a/src/renderer/components/wizard/index.ts b/src/renderer/components/wizard/index.ts index b217e311a9..da693bd87f 100644 --- a/src/renderer/components/wizard/index.ts +++ b/src/renderer/components/wizard/index.ts @@ -1 +1 @@ -export * from "./wizard"; \ No newline at end of file +export * from "./wizard"; diff --git a/src/renderer/hooks/useInterval.ts b/src/renderer/hooks/useInterval.ts index d195fa279f..7ab604511b 100644 --- a/src/renderer/hooks/useInterval.ts +++ b/src/renderer/hooks/useInterval.ts @@ -16,4 +16,4 @@ export function useInterval(callback: () => void, delay: number) { return () => clearInterval(id); }, [delay]); -} \ No newline at end of file +} diff --git a/src/renderer/hooks/useOnUnmount.ts b/src/renderer/hooks/useOnUnmount.ts index 5af04e39b1..a8b6fdd1b4 100644 --- a/src/renderer/hooks/useOnUnmount.ts +++ b/src/renderer/hooks/useOnUnmount.ts @@ -2,4 +2,4 @@ import { useEffect } from "react"; export function useOnUnmount(callback: () => void) { useEffect(() => callback, []); -} \ No newline at end of file +} diff --git a/src/renderer/hooks/useStorage.ts b/src/renderer/hooks/useStorage.ts index 2af730fec8..97b0588d29 100644 --- a/src/renderer/hooks/useStorage.ts +++ b/src/renderer/hooks/useStorage.ts @@ -10,4 +10,4 @@ export function useStorage(key: string, initialValue?: T, options?: IStorageH }; return [storageValue, setValue] as [T, (value: T) => void]; -} \ No newline at end of file +} diff --git a/src/renderer/item.store.ts b/src/renderer/item.store.ts index 2105954d32..eccd2b52df 100644 --- a/src/renderer/item.store.ts +++ b/src/renderer/item.store.ts @@ -9,7 +9,7 @@ export interface ItemObject { @autobind() export abstract class ItemStore { - abstract loadAll(): Promise; + abstract loadAll(...args: any[]): Promise; protected defaultSorting = (item: T) => item.getName(); @@ -40,8 +40,7 @@ export abstract class ItemStore { if (item) { return item; - } - else { + } else { const items = this.sortItems([...this.items, newItem]); this.items.replace(items); @@ -83,8 +82,7 @@ export abstract class ItemStore { const index = this.items.findIndex(item => item === existingItem); this.items.splice(index, 1, item); - } - else { + } else { let items = [...this.items, item]; if (sortItems) items = this.sortItems(items); @@ -130,8 +128,7 @@ export abstract class ItemStore { toggleSelection(item: T) { if (this.isSelected(item)) { this.unselect(item); - } - else { + } else { this.select(item); } } @@ -142,8 +139,7 @@ export abstract class ItemStore { if (allSelected) { visibleItems.forEach(this.unselect); - } - else { + } else { visibleItems.forEach(this.select); } } diff --git a/src/renderer/kube-object.store.ts b/src/renderer/kube-object.store.ts index 2e0dfa7ff5..8a75bc7ae6 100644 --- a/src/renderer/kube-object.store.ts +++ b/src/renderer/kube-object.store.ts @@ -1,3 +1,4 @@ +import type { Cluster } from "../main/cluster"; import { action, observable, reaction } from "mobx"; import { autobind } from "./utils"; import { KubeObject } from "./api/kube-object"; @@ -6,7 +7,11 @@ import { ItemStore } from "./item.store"; import { apiManager } from "./api/api-manager"; import { IKubeApiQueryParams, KubeApi } from "./api/kube-api"; import { KubeJsonApiData } from "./api/kube-json-api"; -import { getHostedCluster } from "../common/cluster-store"; + +export interface KubeObjectStoreLoadingParams { + namespaces: string[]; + api?: KubeApi; +} @autobind() export abstract class KubeObjectStore extends ItemStore { @@ -75,14 +80,26 @@ export abstract class KubeObjectStore extends ItemSt } } - protected async loadItems(allowedNamespaces?: string[]): Promise { - if (!this.api.isNamespaced || !allowedNamespaces) { - return this.api.list({}, this.query); - } else { - return Promise - .all(allowedNamespaces.map(namespace => this.api.list({ namespace }))) - .then(items => items.flat()); + protected async resolveCluster(): Promise { + const { getHostedCluster } = await import("../common/cluster-store"); + + return getHostedCluster(); + } + + protected async loadItems({ namespaces, api }: KubeObjectStoreLoadingParams): Promise { + const cluster = await this.resolveCluster(); + + if (cluster.isAllowedResource(api.kind)) { + if (api.isNamespaced) { + return Promise + .all(namespaces.map(namespace => api.list({ namespace }))) + .then(items => items.flat()); + } + + return api.list({}, this.query); } + + return []; } protected filterItemsOnLoad(items: T[]) { @@ -90,30 +107,35 @@ export abstract class KubeObjectStore extends ItemSt } @action - async loadAll() { + async loadAll({ namespaces: contextNamespaces }: { namespaces?: string[] } = {}) { this.isLoading = true; - let items: T[]; try { - const { allowedNamespaces, accessibleNamespaces, isAdmin } = getHostedCluster(); + if (!contextNamespaces) { + const { namespaceStore } = await import("./components/+namespaces/namespace.store"); - if (isAdmin && accessibleNamespaces.length == 0) { - items = await this.loadItems(); - } else { - items = await this.loadItems(allowedNamespaces); + contextNamespaces = namespaceStore.getContextNamespaces(); } + let items = await this.loadItems({ namespaces: contextNamespaces, api: this.api }); + items = this.filterItemsOnLoad(items); - } finally { - if (items) { - items = this.sortItems(items); - this.items.replace(items); - } - this.isLoading = false; + items = this.sortItems(items); + + this.items.replace(items); this.isLoaded = true; + } catch (error) { + console.error("Loading store items failed", { error, store: this }); + this.resetOnError(error); + } finally { + this.isLoading = false; } } + protected resetOnError(error: any) { + if (error) this.reset(); + } + protected async loadItem(params: { name: string; namespace?: string }): Promise { return this.api.get(params); } @@ -198,7 +220,7 @@ export abstract class KubeObjectStore extends ItemSt // create latest non-observable copy of items to apply updates in one action (==single render) const items = this.items.toJS(); - for (const {type, object} of this.eventsBuffer.clear()) { + for (const { type, object } of this.eventsBuffer.clear()) { const index = items.findIndex(item => item.getId() === object.metadata?.uid); const item = items[index]; const api = apiManager.getApiByKind(object.kind, object.apiVersion); diff --git a/src/renderer/navigation/events.ts b/src/renderer/navigation/events.ts index 971465706d..1766a1e0d3 100644 --- a/src/renderer/navigation/events.ts +++ b/src/renderer/navigation/events.ts @@ -28,4 +28,4 @@ export function bindEvents() { subscribeToBroadcast("renderer:reload", () => { location.reload(); }); -} \ No newline at end of file +} diff --git a/src/renderer/navigation/helpers.ts b/src/renderer/navigation/helpers.ts index 378f6edb96..0eda77c629 100644 --- a/src/renderer/navigation/helpers.ts +++ b/src/renderer/navigation/helpers.ts @@ -33,4 +33,4 @@ export function getMatchedClusterId(): string { }); return matched?.params.clusterId; -} \ No newline at end of file +} diff --git a/src/renderer/navigation/index.ts b/src/renderer/navigation/index.ts index 70959c2dbd..94930fc994 100644 --- a/src/renderer/navigation/index.ts +++ b/src/renderer/navigation/index.ts @@ -5,4 +5,4 @@ import { bindEvents } from "./events"; export * from "./history"; export * from "./helpers"; -bindEvents(); \ No newline at end of file +bindEvents(); diff --git a/src/renderer/themes/lens-dark.json b/src/renderer/themes/lens-dark.json index 2cd16aec42..4a7a0f2f70 100644 --- a/src/renderer/themes/lens-dark.json +++ b/src/renderer/themes/lens-dark.json @@ -65,6 +65,7 @@ "dockEditorKeyword": "#ffffff", "dockEditorComment": "#808080", "dockEditorActiveLineBackground": "#3a3d41", + "dockBadgeBackground": "#36393e", "logsBackground": "#000000", "logsForeground": "#ffffff", "logRowHoverBackground": "#35373a", @@ -114,6 +115,7 @@ "lineProgressBackground": "#414448", "radioActiveBackground": "#36393e", "menuActiveBackground": "#36393e", + "menuSelectedOptionBgc": "#36393e", "scrollBarColor": "#5f6064" } } diff --git a/src/renderer/themes/lens-light.json b/src/renderer/themes/lens-light.json index d5740f1505..f59d3c9555 100644 --- a/src/renderer/themes/lens-light.json +++ b/src/renderer/themes/lens-light.json @@ -59,13 +59,14 @@ "colorVague": "#ededed", "colorTerminated": "#9dabb5", "dockHeadBackground": "#e8e8e8", - "dockInfoBackground": "#e8e8e8", + "dockInfoBackground": "#f3f3f3", "dockInfoBorderColor": "#c9cfd3", "dockEditorBackground": "#24292e", "dockEditorTag": "#8e97a3", "dockEditorKeyword": "#ffffff", "dockEditorComment": "#808080", "dockEditorActiveLineBackground": "#3a3d41", + "dockBadgeBackground": "#dedede", "logsBackground": "#24292e", "logsForeground": "#ffffff", "logRowHoverBackground": "#35373a", @@ -115,6 +116,7 @@ "lineProgressBackground": "#e8e8e8", "radioActiveBackground": "#f1f1f1", "menuActiveBackground": "#e8e8e8", + "menuSelectedOptionBgc": "#e8e8e8", "scrollBarColor": "#bbbbbb", "canvasBackground": "#24292e" } diff --git a/src/renderer/themes/theme-vars.scss b/src/renderer/themes/theme-vars.scss index b2953d3f64..6b556bdc88 100644 --- a/src/renderer/themes/theme-vars.scss +++ b/src/renderer/themes/theme-vars.scss @@ -67,6 +67,7 @@ $helmDescriptionPreColor: var(--helmDescriptionPreColor); $dockHeadBackground: var(--dockHeadBackground); $dockInfoBackground: var(--dockInfoBackground); $dockInfoBorderColor: var(--dockInfoBorderColor); +$dockBadgeBackground: var(--dockBadgeBackground); // Terminal $terminalBackground: var(--terminalBackground); @@ -129,4 +130,5 @@ $filterAreaBackground: var(--filterAreaBackground); $selectOptionHoveredColor: var(--selectOptionHoveredColor); $lineProgressBackground: var(--lineProgressBackground); $radioActiveBackground: var(--radioActiveBackground); -$menuActiveBackground: var(--menuActiveBackground); \ No newline at end of file +$menuActiveBackground: var(--menuActiveBackground); +$menuSelectedOptionBgc: var(--menuSelectedOptionBgc); \ No newline at end of file diff --git a/src/renderer/utils/__tests__/metricUnitsToNumber.test.ts b/src/renderer/utils/__tests__/metricUnitsToNumber.test.ts index e94c2f3b67..a22aa46790 100644 --- a/src/renderer/utils/__tests__/metricUnitsToNumber.test.ts +++ b/src/renderer/utils/__tests__/metricUnitsToNumber.test.ts @@ -12,4 +12,4 @@ describe("metricUnitsToNumber tests", () => { test("with m suffix", () => { expect(metricUnitsToNumber("124m")).toStrictEqual(124000000); }); -}); \ No newline at end of file +}); diff --git a/src/renderer/utils/formatDuration.ts b/src/renderer/utils/formatDuration.ts index 8864aba393..87da6cfa64 100644 --- a/src/renderer/utils/formatDuration.ts +++ b/src/renderer/utils/formatDuration.ts @@ -83,4 +83,4 @@ function getMeaningfulValues(values: number[], suffixes: string[], separator = " .filter(([dur]) => dur > 0) .map(([dur, suf]) => dur + suf) .join(separator); -} \ No newline at end of file +} diff --git a/src/renderer/utils/jsonPath.ts b/src/renderer/utils/jsonPath.ts index ea31ffa80e..79075500f9 100644 --- a/src/renderer/utils/jsonPath.ts +++ b/src/renderer/utils/jsonPath.ts @@ -32,4 +32,4 @@ function convertToIndexNotation(key: string, firstItem = false) { return `${prefix}${key}`; } -} \ No newline at end of file +} diff --git a/types/command-exists.d.ts b/types/command-exists.d.ts index b5375ae390..634d2a035e 100644 --- a/types/command-exists.d.ts +++ b/types/command-exists.d.ts @@ -13,4 +13,4 @@ declare function commandExists( declare namespace commandExists { function sync(commandName: string): boolean; -} \ No newline at end of file +} diff --git a/yarn.lock b/yarn.lock index d9d4729536..dd9ec0c1c9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -536,6 +536,13 @@ "@hapi/pez" "^5.0.1" "@hapi/wreck" "17.x.x" +"@hapi/topo@^5.0.0": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@hapi/topo/-/topo-5.0.0.tgz#c19af8577fa393a06e9c77b60995af959be721e7" + integrity sha512-tFJlT47db0kMqVm3H4nQYgn6Pwg10GTZHb1pwmSiv1K4ks6drQOtfEF5ZnPjkvC+y4/bUPHK+bc87QvLcL+WMw== + dependencies: + "@hapi/hoek" "^9.0.0" + "@hapi/vise@4.x.x": version "4.0.0" resolved "https://registry.yarnpkg.com/@hapi/vise/-/vise-4.0.0.tgz#c6a94fe121b94a53bf99e7489f7fcc74c104db02" @@ -918,6 +925,23 @@ schema-utils "^2.6.5" source-map "^0.7.3" +"@sideway/address@^4.1.0": + version "4.1.0" + resolved "https://registry.yarnpkg.com/@sideway/address/-/address-4.1.0.tgz#0b301ada10ac4e0e3fa525c90615e0b61a72b78d" + integrity sha512-wAH/JYRXeIFQRsxerIuLjgUu2Xszam+O5xKeatJ4oudShOOirfmsQ1D6LL54XOU2tizpCYku+s1wmU0SYdpoSA== + dependencies: + "@hapi/hoek" "^9.0.0" + +"@sideway/formula@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@sideway/formula/-/formula-3.0.0.tgz#fe158aee32e6bd5de85044be615bc08478a0a13c" + integrity sha512-vHe7wZ4NOXVfkoRb8T5otiENVlT7a3IAiw7H5M2+GO+9CDgcVUUsX1zalAztCmwyOr2RUTGJdgB+ZvSVqmdHmg== + +"@sideway/pinpoint@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@sideway/pinpoint/-/pinpoint-2.0.0.tgz#cff8ffadc372ad29fd3f78277aeb29e632cc70df" + integrity sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ== + "@sindresorhus/is@^0.14.0": version "0.14.0" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-0.14.0.tgz#9fb3a3cf3132328151f353de4632e01e52102bea" @@ -1207,19 +1231,19 @@ dependencies: "@types/node" "*" -"@types/hapi@^18.0.3": - version "18.0.3" - resolved "https://registry.yarnpkg.com/@types/hapi/-/hapi-18.0.3.tgz#e74c019f6a1b1c7f647fe014d3890adec9c0214a" - integrity sha512-UM03myDZ2UWbpqLSZqboK4L98F9r4GCcd9JOr2auhgC3iOd/69mvDggivOHhOYJKWHeCW/dECPHIB7DwQz00dw== +"@types/hapi@^18.0.5": + version "18.0.5" + resolved "https://registry.yarnpkg.com/@types/hapi/-/hapi-18.0.5.tgz#7573fc83ec1d8ecf127b93bd326266da533fe30b" + integrity sha512-OnBslvAL//tsTZemW8wSGrVUj7BgtS16kBicgKCtEpHle9A3pOd7X4ViykKv/X3rh7g636mDzoqQ27+Ols5GQw== dependencies: "@types/boom" "*" "@types/catbox" "*" "@types/iron" "*" - "@types/joi" "*" "@types/mimos" "*" "@types/node" "*" "@types/podium" "*" "@types/shot" "*" + joi "^17.3.0" "@types/history@*", "@types/history@^4.7.3": version "4.7.6" @@ -1331,11 +1355,6 @@ jest-diff "^25.2.1" pretty-format "^25.2.1" -"@types/joi@*": - version "14.3.4" - resolved "https://registry.yarnpkg.com/@types/joi/-/joi-14.3.4.tgz#eed1e14cbb07716079c814138831a520a725a1e0" - integrity sha512-1TQNDJvIKlgYXGNIABfgFp9y0FziDpuGrd799Q5RcnsDu+krD+eeW/0Fs5PHARvWWFelOhIG2OPCo6KbadBM4A== - "@types/js-yaml@^3.12.1", "@types/js-yaml@^3.12.4": version "3.12.4" resolved "https://registry.yarnpkg.com/@types/js-yaml/-/js-yaml-3.12.4.tgz#7d3b534ec35a0585128e2d332db1403ebe057e25" @@ -1438,12 +1457,7 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-10.17.24.tgz#c57511e3a19c4b5e9692bb2995c40a3a52167944" integrity sha512-5SCfvCxV74kzR3uWgTYiGxrd69TbT1I6+cMx1A5kEly/IVveJBimtAMlXiEyVFn5DvUFewQWxOOiJhlxeQwxgA== -"@types/node@^12.0.12": - version "12.12.44" - resolved "https://registry.yarnpkg.com/@types/node/-/node-12.12.44.tgz#0d400a1453adcb359b133acceae4dd8bb0e0a159" - integrity sha512-jM6QVv0Sm5d3nW+nUD5jSzPcO6oPqboitSNcwgBay9hifVq/Rauq1PYnROnsmuw45JMBiTnsPAno0bKu2e2xrg== - -"@types/node@^12.12.45": +"@types/node@^12.0.12", "@types/node@^12.12.45": version "12.12.45" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.12.45.tgz#33d550d6da243652004b00cbf4f15997456a38e3" integrity sha512-9w50wqeS0qQH9bo1iIRcQhDXRxoDzyAqCL5oJG+Nuu7cAoe6omGo+YDE0spAGK5sPrdLDhQLbQxq0DnxyndPKA== @@ -4829,9 +4843,9 @@ electron@^9.4.0: extract-zip "^1.0.3" elliptic@^6.0.0, elliptic@^6.5.2: - version "6.5.2" - resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.2.tgz#05c5678d7173c049d8ca433552224a495d0e3762" - integrity sha512-f4x70okzZbIQl/NSRLkI/+tteV/9WqL98zx+SQ69KbXxmVrmjwsNUPn/gYJJ0sHvEak24cZgHIPegRePAtA/xw== + version "6.5.3" + resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.3.tgz#cb59eb2efdaf73a0bd78ccd7015a62ad6e0f93d6" + integrity sha512-IMqzv5wNQf+E6aHeIqATs0tOLeOTwj1QKbRcS3jBbYkl5oLAserA8yJTT7/VyHUYG91PRmPyeQDObKLPpeS4dw== dependencies: bn.js "^4.4.0" brorand "^1.0.1" @@ -6886,9 +6900,9 @@ inherits@2.0.3: integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4= ini@^1.3.4, ini@^1.3.5, ini@~1.3.0: - version "1.3.5" - resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927" - integrity sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw== + version "1.3.8" + resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" + integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== init-package-json@^1.10.3: version "1.10.3" @@ -7909,6 +7923,17 @@ jest@^26.0.1: import-local "^3.0.2" jest-cli "^26.0.1" +joi@^17.3.0: + version "17.3.0" + resolved "https://registry.yarnpkg.com/joi/-/joi-17.3.0.tgz#f1be4a6ce29bc1716665819ac361dfa139fff5d2" + integrity sha512-Qh5gdU6niuYbUIUV5ejbsMiiFmBdw8Kcp8Buj2JntszCkCfxJ9Cz76OtHxOZMPXrt5810iDIXs+n1nNVoquHgg== + dependencies: + "@hapi/hoek" "^9.0.0" + "@hapi/topo" "^5.0.0" + "@sideway/address" "^4.1.0" + "@sideway/formula" "^3.0.0" + "@sideway/pinpoint" "^2.0.0" + jose@^1.27.1: version "1.27.1" resolved "https://registry.yarnpkg.com/jose/-/jose-1.27.1.tgz#a1de2ecb5b3ae1ae28f0d9d0cc536349ada27ec8" @@ -8773,10 +8798,10 @@ make-fetch-happen@^5.0.0: socks-proxy-agent "^4.0.0" ssri "^6.0.0" -make-plural@^6.2.1: - version "6.2.1" - resolved "https://registry.yarnpkg.com/make-plural/-/make-plural-6.2.1.tgz#2790af1d05fb2fc35a111ce759ffdb0aca1339a3" - integrity sha512-AmkruwJ9EjvyTv6AM8MBMK3TAeOJvhgTv5YQXzF0EP2qawhpvMjDpHvsdOIIT0Vn+BB0+IogmYZ1z+Ulm/m0Fg== +make-plural@^6.2.2: + version "6.2.2" + resolved "https://registry.yarnpkg.com/make-plural/-/make-plural-6.2.2.tgz#beb5fd751355e72660eeb2218bb98eec92853c6c" + integrity sha512-8iTuFioatnTTmb/YJjywkVIHLjcwkFD9Ms0JpxjEm9Mo8eQYkh1z+55dwv4yc1jQ8ftVBxWQbihvZL1DfzGGWA== makeerror@1.0.x: version "1.0.11" @@ -8814,10 +8839,10 @@ marked@^0.8.0: resolved "https://registry.yarnpkg.com/marked/-/marked-0.8.2.tgz#4faad28d26ede351a7a1aaa5fec67915c869e355" integrity sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw== -marked@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/marked/-/marked-1.1.0.tgz#62504ad4d11550c942935ccc5e39d64e5a4c4e50" - integrity sha512-EkE7RW6KcXfMHy2PA7Jg0YJE1l8UPEZE8k45tylzmZM30/r1M1MUXWQfJlrSbsTeh7m/XTwHbWUENvAJZpp1YA== +marked@^1.2.7: + version "1.2.7" + resolved "https://registry.yarnpkg.com/marked/-/marked-1.2.7.tgz#6e14b595581d2319cdcf033a24caaf41455a01fb" + integrity sha512-No11hFYcXr/zkBvL6qFmAp1z6BKY3zqLMHny/JN/ey+al7qwCM2+CMBL9BOgqMxZU36fz4cCWfn2poWIf7QRXA== matcher@^3.0.0: version "3.0.0" @@ -12165,10 +12190,10 @@ shebang-regex@^3.0.0: resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== -shell-env@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/shell-env/-/shell-env-3.0.0.tgz#42484ebd0798ee321ba69f6151f2aeab13fde1d4" - integrity sha512-zE0lGldowbCLnnorLnOUO6gLSwEoW4u+qWcEV1HH2qje5sIg0PvBd+8ro74EgSZv0MBEP2dROD6vSKhGDbUIMQ== +shell-env@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/shell-env/-/shell-env-3.0.1.tgz#515a62f6cbd5e139365be2535745e8e53438ce77" + integrity sha512-b09fpMipAQ9ObwvIeKoQFLDXcEcCpYUUZanlad4OYQscw2I49C/u97OPQg9jWYo36bRDn62fbe07oWYqovIvKA== dependencies: default-shell "^1.0.1" execa "^1.0.0"