NestedFolderPicker: Migrate to app platform API (#106926)

* Add /children endpoint

* Update folder client

* Add comment

* Add feature toggle

* Add new version of useFoldersQuery

* Error handling

* Format

* Rename feature toggle

* Remove options and move root folder constant

* Fix feature toggle merge

* Add feature toggle again

* Rename useFoldersQuery files

* Update API spec

* Fix test

* Add test

* Better typings

---------

Co-authored-by: Clarity-89 <homes89@ukr.net>
iortega/new-ds-model-backup^2
Andrej Ocenas 2 weeks ago committed by GitHub
parent 185ce90a4b
commit e76f470b44
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 5
      packages/grafana-data/src/types/featureToggles.gen.ts
  2. 5
      pkg/registry/apis/folders/register.go
  3. 73
      pkg/registry/apis/folders/sub_children.go
  4. 10
      pkg/services/featuremgmt/registry.go
  5. 1
      pkg/services/featuremgmt/toggles_gen.csv
  6. 4
      pkg/services/featuremgmt/toggles_gen.go
  7. 16
      pkg/services/featuremgmt/toggles_gen.json
  8. 9
      pkg/tests/apis/folder/folders_test.go
  9. 49
      pkg/tests/apis/openapi_snapshots/folder.grafana.app-v1beta1.json
  10. 439
      public/app/api/clients/folder/v1beta1/endpoints.gen.ts
  11. 2
      public/app/api/clients/folder/v1beta1/index.ts
  12. 3
      public/app/core/components/NestedFolderPicker/NestedFolderPicker.tsx
  13. 116
      public/app/core/components/NestedFolderPicker/useFoldersQuery.test.tsx
  14. 198
      public/app/core/components/NestedFolderPicker/useFoldersQuery.ts
  15. 164
      public/app/core/components/NestedFolderPicker/useFoldersQueryAppPlatform.ts
  16. 191
      public/app/core/components/NestedFolderPicker/useFoldersQueryLegacy.ts
  17. 9
      public/app/core/components/NestedFolderPicker/utils.ts
  18. 1
      scripts/generate-rtk-apis.ts

@ -1012,4 +1012,9 @@ export interface FeatureToggles {
* @default false
*/
enableAppChromeExtensions?: boolean;
/**
* Enables use of app platform API for folders
* @default false
*/
foldersAppPlatformAPI?: boolean;
}

@ -192,6 +192,11 @@ func (b *FolderAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver.API
storage[resourceInfo.StoragePath("counts")] = &subCountREST{searcher: b.searcher}
storage[resourceInfo.StoragePath("access")] = &subAccessREST{b.folderSvc, b.ac}
// Adds a path to return children of a given folder
storage[resourceInfo.StoragePath("children")] = &subChildrenREST{
lister: storage[resourceInfo.StoragePath()].(rest.Lister),
}
apiGroupInfo.VersionedResourcesStorageMap[folders.VERSION] = storage
b.storage = storage[resourceInfo.StoragePath()].(grafanarest.Storage)
return nil

@ -0,0 +1,73 @@
package folders
import (
"context"
"fmt"
"net/http"
"k8s.io/apimachinery/pkg/apis/meta/internalversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/rest"
folders "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1"
)
type subChildrenREST struct {
lister rest.Lister
}
var _ = rest.Connecter(&subChildrenREST{})
var _ = rest.StorageMetadata(&subChildrenREST{})
// RootFolderName Hardcoded magic const to get root folders without parent.
var RootFolderName = "general"
func (r *subChildrenREST) New() runtime.Object {
return &folders.FolderList{}
}
func (r *subChildrenREST) Destroy() {
}
func (r *subChildrenREST) ProducesMIMETypes(verb string) []string {
return nil
}
func (r *subChildrenREST) ProducesObject(verb string) interface{} {
return &folders.FolderList{}
}
func (r *subChildrenREST) ConnectMethods() []string {
return []string{"GET"}
}
func (r *subChildrenREST) NewConnectOptions() (runtime.Object, bool, string) {
return nil, false, "" // true means you can use the trailing path as a variable
}
func (r *subChildrenREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {
obj, err := r.lister.List(ctx, &internalversion.ListOptions{})
if err != nil {
return nil, err
}
allFolders, ok := obj.(*folders.FolderList)
if !ok {
return nil, fmt.Errorf("could not list folders")
}
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
children := &folders.FolderList{}
parentName := ""
if name != RootFolderName {
parentName = name
}
for _, folder := range allFolders.Items {
if parentName == getParent(&folder) {
children.Items = append(children.Items, folder)
}
}
responder.Object(http.StatusOK, children)
}), nil
}

@ -1734,6 +1734,16 @@ var (
FrontendOnly: true,
Expression: "false", // extensions will be disabled by default
},
{
Name: "foldersAppPlatformAPI",
Description: "Enables use of app platform API for folders",
Stage: FeatureStageExperimental,
Owner: grafanaFrontendSearchNavOrganise,
HideFromAdminPage: true,
HideFromDocs: true,
FrontendOnly: true,
Expression: "false",
},
}
)

@ -226,3 +226,4 @@ preferLibraryPanelTitle,privatePreview,@grafana/dashboards-squad,false,false,fal
tabularNumbers,GA,@grafana/grafana-frontend-platform,false,false,false
newInfluxDSConfigPageDesign,privatePreview,@grafana/partner-datasources,false,false,false
enableAppChromeExtensions,experimental,@grafana/plugins-platform-backend,false,false,true
foldersAppPlatformAPI,experimental,@grafana/grafana-search-navigate-organise,false,false,true

1 Name Stage Owner requiresDevMode RequiresRestart FrontendOnly
226 tabularNumbers GA @grafana/grafana-frontend-platform false false false
227 newInfluxDSConfigPageDesign privatePreview @grafana/partner-datasources false false false
228 enableAppChromeExtensions experimental @grafana/plugins-platform-backend false false true
229 foldersAppPlatformAPI experimental @grafana/grafana-search-navigate-organise false false true

@ -914,4 +914,8 @@ const (
// FlagEnableAppChromeExtensions
// Set this to true to enable all app chrome extensions registered by plugins.
FlagEnableAppChromeExtensions = "enableAppChromeExtensions"
// FlagFoldersAppPlatformAPI
// Enables use of app platform API for folders
FlagFoldersAppPlatformAPI = "foldersAppPlatformAPI"
)

@ -1257,6 +1257,22 @@
"hideFromDocs": true
}
},
{
"metadata": {
"name": "foldersAppPlatformAPI",
"resourceVersion": "1751377081192",
"creationTimestamp": "2025-07-01T13:38:01Z"
},
"spec": {
"description": "Enables use of app platform API for folders",
"stage": "experimental",
"codeowner": "@grafana/grafana-search-navigate-organise",
"frontend": true,
"hideFromAdminPage": true,
"hideFromDocs": true,
"expression": "false"
}
},
{
"metadata": {
"name": "formatString",

@ -88,6 +88,15 @@ func TestIntegrationFoldersApp(t *testing.T) {
"get"
]
},
{
"name": "folders/children",
"singularName": "",
"namespaced": true,
"kind": "FolderList",
"verbs": [
"get"
]
},
{
"name": "folders/counts",
"singularName": "",

@ -915,6 +915,55 @@
}
]
},
"/apis/folder.grafana.app/v1beta1/namespaces/{namespace}/folders/{name}/children": {
"get": {
"tags": [
"Folder"
],
"description": "connect GET requests to children of Folder",
"operationId": "getFolderChildren",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"$ref": "#/components/schemas/com.github.grafana.grafana.apps.folder.pkg.apis.folder.v1beta1.FolderList"
}
}
}
}
},
"x-kubernetes-action": "connect",
"x-kubernetes-group-version-kind": {
"group": "folder.grafana.app",
"version": "v1beta1",
"kind": "FolderList"
}
},
"parameters": [
{
"name": "name",
"in": "path",
"description": "name of the FolderList",
"required": true,
"schema": {
"type": "string",
"uniqueItems": true
}
},
{
"name": "namespace",
"in": "path",
"description": "object name and auth scope, such as for teams and projects",
"required": true,
"schema": {
"type": "string",
"uniqueItems": true
}
}
]
},
"/apis/folder.grafana.app/v1beta1/namespaces/{namespace}/folders/{name}/counts": {
"get": {
"tags": [

@ -1,11 +1,71 @@
import { api } from './baseAPI';
export const addTagTypes = ['Folder'] as const;
export const addTagTypes = ['API Discovery', 'Folder'] as const;
const injectedRtkApi = api
.enhanceEndpoints({
addTagTypes,
})
.injectEndpoints({
endpoints: (build) => ({
getApiResources: build.query<GetApiResourcesApiResponse, GetApiResourcesApiArg>({
query: () => ({ url: `/apis/folder.grafana.app/v1beta1/` }),
providesTags: ['API Discovery'],
}),
listFolder: build.query<ListFolderApiResponse, ListFolderApiArg>({
query: (queryArg) => ({
url: `/folders`,
params: {
pretty: queryArg.pretty,
allowWatchBookmarks: queryArg.allowWatchBookmarks,
continue: queryArg['continue'],
fieldSelector: queryArg.fieldSelector,
labelSelector: queryArg.labelSelector,
limit: queryArg.limit,
resourceVersion: queryArg.resourceVersion,
resourceVersionMatch: queryArg.resourceVersionMatch,
sendInitialEvents: queryArg.sendInitialEvents,
timeoutSeconds: queryArg.timeoutSeconds,
watch: queryArg.watch,
},
}),
providesTags: ['Folder'],
}),
createFolder: build.mutation<CreateFolderApiResponse, CreateFolderApiArg>({
query: (queryArg) => ({
url: `/folders`,
method: 'POST',
body: queryArg.folder,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
},
}),
invalidatesTags: ['Folder'],
}),
deletecollectionFolder: build.mutation<DeletecollectionFolderApiResponse, DeletecollectionFolderApiArg>({
query: (queryArg) => ({
url: `/folders`,
method: 'DELETE',
params: {
pretty: queryArg.pretty,
continue: queryArg['continue'],
dryRun: queryArg.dryRun,
fieldSelector: queryArg.fieldSelector,
gracePeriodSeconds: queryArg.gracePeriodSeconds,
ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential,
labelSelector: queryArg.labelSelector,
limit: queryArg.limit,
orphanDependents: queryArg.orphanDependents,
propagationPolicy: queryArg.propagationPolicy,
resourceVersion: queryArg.resourceVersion,
resourceVersionMatch: queryArg.resourceVersionMatch,
sendInitialEvents: queryArg.sendInitialEvents,
timeoutSeconds: queryArg.timeoutSeconds,
},
}),
invalidatesTags: ['Folder'],
}),
getFolder: build.query<GetFolderApiResponse, GetFolderApiArg>({
query: (queryArg) => ({
url: `/folders/${queryArg.name}`,
@ -15,10 +75,183 @@ const injectedRtkApi = api
}),
providesTags: ['Folder'],
}),
replaceFolder: build.mutation<ReplaceFolderApiResponse, ReplaceFolderApiArg>({
query: (queryArg) => ({
url: `/folders/${queryArg.name}`,
method: 'PUT',
body: queryArg.folder,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
},
}),
invalidatesTags: ['Folder'],
}),
deleteFolder: build.mutation<DeleteFolderApiResponse, DeleteFolderApiArg>({
query: (queryArg) => ({
url: `/folders/${queryArg.name}`,
method: 'DELETE',
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
gracePeriodSeconds: queryArg.gracePeriodSeconds,
ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential,
orphanDependents: queryArg.orphanDependents,
propagationPolicy: queryArg.propagationPolicy,
},
}),
invalidatesTags: ['Folder'],
}),
updateFolder: build.mutation<UpdateFolderApiResponse, UpdateFolderApiArg>({
query: (queryArg) => ({
url: `/folders/${queryArg.name}`,
method: 'PATCH',
body: queryArg.patch,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
force: queryArg.force,
},
}),
invalidatesTags: ['Folder'],
}),
getFolderAccess: build.query<GetFolderAccessApiResponse, GetFolderAccessApiArg>({
query: (queryArg) => ({ url: `/folders/${queryArg.name}/access` }),
providesTags: ['Folder'],
}),
getFolderChildren: build.query<GetFolderChildrenApiResponse, GetFolderChildrenApiArg>({
query: (queryArg) => ({ url: `/folders/${queryArg.name}/children` }),
providesTags: ['Folder'],
}),
getFolderCounts: build.query<GetFolderCountsApiResponse, GetFolderCountsApiArg>({
query: (queryArg) => ({ url: `/folders/${queryArg.name}/counts` }),
providesTags: ['Folder'],
}),
getFolderParents: build.query<GetFolderParentsApiResponse, GetFolderParentsApiArg>({
query: (queryArg) => ({ url: `/folders/${queryArg.name}/parents` }),
providesTags: ['Folder'],
}),
}),
overrideExisting: false,
});
export { injectedRtkApi as generatedAPI };
export type GetApiResourcesApiResponse = /** status 200 OK */ ApiResourceList;
export type GetApiResourcesApiArg = void;
export type ListFolderApiResponse = /** status 200 OK */ FolderList;
export type ListFolderApiArg = {
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */
allowWatchBookmarks?: boolean;
/** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key".
This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */
continue?: string;
/** A selector to restrict the list of returned objects by their fields. Defaults to everything. */
fieldSelector?: string;
/** A selector to restrict the list of returned objects by their labels. Defaults to everything. */
labelSelector?: string;
/** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */
limit?: number;
/** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
Defaults to unset */
resourceVersion?: string;
/** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
Defaults to unset */
resourceVersionMatch?: string;
/** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.
When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan
is interpreted as "data at least as new as the provided `resourceVersion`"
and the bookmark event is send when the state is synced
to a `resourceVersion` at least as fresh as the one provided by the ListOptions.
If `resourceVersion` is unset, this is interpreted as "consistent read" and the
bookmark event is send when the state is synced at least to the moment
when request started being processed.
- `resourceVersionMatch` set to any other value or unset
Invalid error is returned.
Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */
sendInitialEvents?: boolean;
/** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */
timeoutSeconds?: number;
/** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */
watch?: boolean;
};
export type CreateFolderApiResponse = /** status 200 OK */
| Folder
| /** status 201 Created */ Folder
| /** status 202 Accepted */ Folder;
export type CreateFolderApiArg = {
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
dryRun?: string;
/** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */
fieldManager?: string;
/** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */
fieldValidation?: string;
folder: Folder;
};
export type DeletecollectionFolderApiResponse = /** status 200 OK */ Status;
export type DeletecollectionFolderApiArg = {
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key".
This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */
continue?: string;
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
dryRun?: string;
/** A selector to restrict the list of returned objects by their fields. Defaults to everything. */
fieldSelector?: string;
/** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */
gracePeriodSeconds?: number;
/** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */
ignoreStoreReadErrorWithClusterBreakingPotential?: boolean;
/** A selector to restrict the list of returned objects by their labels. Defaults to everything. */
labelSelector?: string;
/** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */
limit?: number;
/** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */
orphanDependents?: boolean;
/** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */
propagationPolicy?: string;
/** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
Defaults to unset */
resourceVersion?: string;
/** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
Defaults to unset */
resourceVersionMatch?: string;
/** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.
When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan
is interpreted as "data at least as new as the provided `resourceVersion`"
and the bookmark event is send when the state is synced
to a `resourceVersion` at least as fresh as the one provided by the ListOptions.
If `resourceVersion` is unset, this is interpreted as "consistent read" and the
bookmark event is send when the state is synced at least to the moment
when request started being processed.
- `resourceVersionMatch` set to any other value or unset
Invalid error is returned.
Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */
sendInitialEvents?: boolean;
/** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */
timeoutSeconds?: number;
};
export type GetFolderApiResponse = /** status 200 OK */ Folder;
export type GetFolderApiArg = {
/** name of the Folder */
@ -26,6 +259,105 @@ export type GetFolderApiArg = {
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
};
export type ReplaceFolderApiResponse = /** status 200 OK */ Folder | /** status 201 Created */ Folder;
export type ReplaceFolderApiArg = {
/** name of the Folder */
name: string;
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
dryRun?: string;
/** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */
fieldManager?: string;
/** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */
fieldValidation?: string;
folder: Folder;
};
export type DeleteFolderApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status;
export type DeleteFolderApiArg = {
/** name of the Folder */
name: string;
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
dryRun?: string;
/** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */
gracePeriodSeconds?: number;
/** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */
ignoreStoreReadErrorWithClusterBreakingPotential?: boolean;
/** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */
orphanDependents?: boolean;
/** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */
propagationPolicy?: string;
};
export type UpdateFolderApiResponse = /** status 200 OK */ Folder | /** status 201 Created */ Folder;
export type UpdateFolderApiArg = {
/** name of the Folder */
name: string;
/** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */
pretty?: string;
/** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */
dryRun?: string;
/** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */
fieldManager?: string;
/** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */
fieldValidation?: string;
/** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */
force?: boolean;
patch: Patch;
};
export type GetFolderAccessApiResponse = /** status 200 OK */ FolderAccessInfo;
export type GetFolderAccessApiArg = {
/** name of the FolderAccessInfo */
name: string;
};
export type GetFolderChildrenApiResponse = /** status 200 OK */ FolderList;
export type GetFolderChildrenApiArg = {
/** name of the FolderList */
name: string;
};
export type GetFolderCountsApiResponse = /** status 200 OK */ DescendantCounts;
export type GetFolderCountsApiArg = {
/** name of the DescendantCounts */
name: string;
};
export type GetFolderParentsApiResponse = /** status 200 OK */ FolderInfoList;
export type GetFolderParentsApiArg = {
/** name of the FolderInfoList */
name: string;
};
export type ApiResource = {
/** categories is a list of the grouped resources this resource belongs to (e.g. 'all') */
categories?: string[];
/** group is the preferred group of the resource. Empty implies the group of the containing resource list. For subresources, this may have a different value, for example: Scale". */
group?: string;
/** kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo') */
kind: string;
/** name is the plural name of the resource. */
name: string;
/** namespaced indicates if a resource is namespaced or not. */
namespaced: boolean;
/** shortNames is a list of suggested short names of the resource. */
shortNames?: string[];
/** singularName is the singular name of the resource. This allows clients to handle plural and singular opaquely. The singularName is more correct for reporting status on a single item and both singular and plural are allowed from the kubectl CLI interface. */
singularName: string;
/** The hash value of the storage version, the version this resource is converted to when written to the data store. Value must be treated as opaque by clients. Only equality comparison on the value is valid. This is an alpha feature and may change or be removed in the future. The field is populated by the apiserver only if the StorageVersionHash feature gate is enabled. This field will remain optional even if it graduates. */
storageVersionHash?: string;
/** verbs is a list of supported kube verbs (this includes get, list, watch, create, update, patch, delete, deletecollection, and proxy) */
verbs: string[];
/** version is the preferred version of the resource. Empty implies the version of the containing resource list For subresources, this may have a different value, for example: v1 (while inside a v1beta1 version of the core resource's group)". */
version?: string;
};
export type ApiResourceList = {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
apiVersion?: string;
/** groupVersion is the group and version this APIResourceList is for. */
groupVersion: string;
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind?: string;
/** resources contains the name of the resources and if they are namespaced. */
resources: ApiResource[];
};
export type Time = string;
export type FieldsV1 = object;
export type ManagedFieldsEntry = {
@ -123,3 +455,108 @@ export type Folder = {
spec: FolderSpec;
status: FolderStatus;
};
export type ListMeta = {
/** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */
continue?: string;
/** remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. */
remainingItemCount?: number;
/** String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */
resourceVersion?: string;
/** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */
selfLink?: string;
};
export type FolderList = {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
apiVersion?: string;
items: Folder[];
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind?: string;
metadata: ListMeta;
};
export type StatusCause = {
/** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.
Examples:
"name" - the field "name" on the current resource
"items[0].name" - the field "name" on the first array entry in "items" */
field?: string;
/** A human-readable description of the cause of the error. This field may be presented as-is to a reader. */
message?: string;
/** A machine-readable description of the cause of the error. If this value is empty there is no information available. */
reason?: string;
};
export type StatusDetails = {
/** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */
causes?: StatusCause[];
/** The group attribute of the resource associated with the status StatusReason. */
group?: string;
/** The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind?: string;
/** The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). */
name?: string;
/** If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. */
retryAfterSeconds?: number;
/** UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
uid?: string;
};
export type Status = {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
apiVersion?: string;
/** Suggested HTTP return code for this status, 0 if not set. */
code?: number;
/** Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. */
details?: StatusDetails;
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind?: string;
/** A human-readable description of the status of this operation. */
message?: string;
/** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
metadata?: ListMeta;
/** A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. */
reason?: string;
/** Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status */
status?: string;
};
export type Patch = object;
export type FolderAccessInfo = {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
apiVersion?: string;
canAdmin: boolean;
canDelete: boolean;
canEdit: boolean;
canSave: boolean;
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind?: string;
};
export type ResourceStats = {
count: number;
group: string;
resource: string;
};
export type DescendantCounts = {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
apiVersion?: string;
counts: ResourceStats[];
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind?: string;
};
export type FolderInfo = {
/** The folder description */
description?: string;
/** This folder does not resolve */
detached?: boolean;
/** Name is the k8s name (eg, the unique identifier) for a folder */
name: string;
/** The parent folder UID */
parent?: string;
/** Title is the display value */
title: string;
};
export type FolderInfoList = {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
apiVersion?: string;
items: FolderInfo[];
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
kind?: string;
metadata?: ListMeta;
};

@ -5,4 +5,4 @@ export const folderAPIv1beta1 = generatedAPI.enhanceEndpoints({});
export const { useGetFolderQuery } = folderAPIv1beta1;
// eslint-disable-next-line no-barrel-files/no-barrel-files
export { type Folder } from './endpoints.gen';
export { type Folder, type FolderList } from './endpoints.gen';

@ -20,8 +20,9 @@ import { PermissionLevelString } from 'app/types';
import { FolderRepo } from './FolderRepo';
import { getDOMId, NestedFolderList } from './NestedFolderList';
import Trigger from './Trigger';
import { ROOT_FOLDER_ITEM, useFoldersQuery } from './useFoldersQuery';
import { useFoldersQuery } from './useFoldersQuery';
import { useTreeInteractions } from './useTreeInteractions';
import { ROOT_FOLDER_ITEM } from './utils';
export interface NestedFolderPickerProps {
/* Folder UID to show as selected */

@ -0,0 +1,116 @@
import { act, renderHook } from '@testing-library/react';
import { GrafanaConfig } from '@grafana/data';
import * as runtime from '@grafana/runtime';
import { DashboardsTreeItem } from 'app/features/browse-dashboards/types';
import { DashboardViewItem } from '../../../features/search/types';
import { useFoldersQuery } from './useFoldersQuery';
import { ROOT_FOLDER_ITEM } from './utils';
const PAGE_SIZE = 10;
const legacyResponse = {
status: 'fulfilled',
originalArgs: { parentUid: undefined, page: 1, limit: PAGE_SIZE, permission: 'Edit' },
data: [{ title: 'Legacy Folder', uid: 'legacy1', managedBy: undefined }],
};
// Mock the legacy API client
jest.mock('app/features/browse-dashboards/api/browseDashboardsAPI', () => {
const PAGE_SIZE = 10;
return {
PAGE_SIZE,
browseDashboardsAPI: {
endpoints: {
listFolders: {
select: jest.fn(() => () => legacyResponse),
initiate: jest.fn(() => ({
arg: { parentUid: undefined, page: 1, limit: PAGE_SIZE, permission: 'Edit' },
unsubscribe: jest.fn(),
})),
},
},
},
};
});
const appPlatfromResponse = {
status: 'fulfilled',
originalArgs: { name: 'general' },
data: {
items: [
{
metadata: { name: 'app1', annotations: {} },
spec: { title: 'AppPlatform Folder' },
},
],
},
};
// Mock the appPlatform API client
jest.mock('app/api/clients/folder/v1beta1', () => ({
folderAPIv1beta1: {
endpoints: {
getFolderChildren: {
select: jest.fn(() => () => appPlatfromResponse),
initiate: jest.fn((arg: unknown) => ({
arg,
unsubscribe: jest.fn(),
})),
},
},
},
}));
// Mock getPaginationPlaceholders to return empty array for simplicity
jest.mock('app/features/browse-dashboards/state/utils', () => ({
getPaginationPlaceholders: jest.fn((): DashboardsTreeItem[] => []),
}));
// Mock useDispatch and useSelector to just pass through
jest.mock('app/types/store', () => {
const mod = jest.requireActual('app/types/store');
return {
...mod,
useDispatch: () => (val: unknown) => val,
useSelector: (selector: Function) => selector(),
};
});
describe('useFoldersQuery', () => {
let configBackup: GrafanaConfig;
beforeAll(() => {
configBackup = { ...runtime.config };
});
afterAll(() => {
runtime.config.featureToggles = configBackup.featureToggles;
});
it('returns data using legacy api', () => {
runtime.config.featureToggles.foldersAppPlatformAPI = false;
const items = testFn();
expect((items[1].item as DashboardViewItem).title).toBe('Legacy Folder');
});
it('returns appPlatform hook result when foldersAppPlatformAPI is on', () => {
runtime.config.featureToggles.foldersAppPlatformAPI = true;
const items = testFn();
expect((items[1].item as DashboardViewItem).title).toBe('AppPlatform Folder');
});
});
function testFn() {
const { result } = renderHook(() => useFoldersQuery(true, {}));
expect(result.current.items).toEqual([ROOT_FOLDER_ITEM]);
expect(result.current.isLoading).toBe(false);
act(() => {
result.current.requestNextPage(undefined);
});
expect(result.current.items.length).toBe(2);
return result.current.items;
}

@ -1,199 +1,19 @@
import { createSelector } from '@reduxjs/toolkit';
import { QueryDefinition, BaseQueryFn, QueryActionCreatorResult } from '@reduxjs/toolkit/query';
import { RequestOptions } from 'http';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { config } from '@grafana/runtime';
import { ListFolderQueryArgs, browseDashboardsAPI } from 'app/features/browse-dashboards/api/browseDashboardsAPI';
import { PAGE_SIZE } from 'app/features/browse-dashboards/api/services';
import { getPaginationPlaceholders } from 'app/features/browse-dashboards/state/utils';
import { DashboardViewItemWithUIItems, DashboardsTreeItem } from 'app/features/browse-dashboards/types';
import { FolderListItemDTO, PermissionLevelString } from 'app/types';
import { useDispatch, useSelector } from 'app/types/store';
import { PermissionLevelString } from '../../../types';
type ListFoldersQuery = ReturnType<ReturnType<typeof browseDashboardsAPI.endpoints.listFolders.select>>;
type ListFoldersRequest = QueryActionCreatorResult<
QueryDefinition<
ListFolderQueryArgs,
BaseQueryFn<RequestOptions>,
'getFolder',
FolderListItemDTO[],
'browseDashboardsAPI'
>
>;
import { useFoldersQueryAppPlatform } from './useFoldersQueryAppPlatform';
import { useFoldersQueryLegacy } from './useFoldersQueryLegacy';
const PENDING_STATUS = 'pending';
/**
* Returns whether the set of pages are 'fully loaded', the last page number, and if the last page is currently loading
*/
function getPagesLoadStatus(pages: ListFoldersQuery[]): [boolean, number | undefined, boolean] {
const lastPage = pages.at(-1);
const lastPageNumber = lastPage?.originalArgs?.page;
const lastPageLoading = lastPage?.status === PENDING_STATUS;
if (!lastPage?.data) {
// If there's no pages yet, or the last page is still loading
return [false, lastPageNumber, lastPageLoading];
} else {
return [lastPage.data.length < lastPage.originalArgs.limit, lastPageNumber, lastPageLoading];
}
}
/**
* Returns a loaded folder hierarchy as a flat list and a function to load more pages.
*/
export function useFoldersQuery(
isBrowsing: boolean,
openFolders: Record<string, boolean>,
permission?: PermissionLevelString
) {
const dispatch = useDispatch();
// Keep a list of all request subscriptions so we can unsubscribe from them when the component is unmounted
const requestsRef = useRef<ListFoldersRequest[]>([]);
// Keep a list of selectors for dynamic state selection
const [selectors, setSelectors] = useState<
Array<ReturnType<typeof browseDashboardsAPI.endpoints.listFolders.select>>
>([]);
const listAllFoldersSelector = useMemo(() => {
return createSelector(selectors, (...pages) => {
let isLoading = false;
const rootPages: ListFoldersQuery[] = [];
const pagesByParent: Record<string, ListFoldersQuery[]> = {};
for (const page of pages) {
if (page.status === PENDING_STATUS) {
isLoading = true;
}
const parentUid = page.originalArgs?.parentUid;
if (parentUid) {
if (!pagesByParent[parentUid]) {
pagesByParent[parentUid] = [];
}
pagesByParent[parentUid].push(page);
} else {
rootPages.push(page);
}
}
return {
isLoading,
rootPages,
pagesByParent,
};
});
}, [selectors]);
const state = useSelector(listAllFoldersSelector);
// Loads the next page of folders for the given parent UID by inspecting the
// state to determine what the next page is
const requestNextPage = useCallback(
(parentUid: string | undefined) => {
const pages = parentUid ? state.pagesByParent[parentUid] : state.rootPages;
const [fullyLoaded, pageNumber, lastPageLoading] = getPagesLoadStatus(pages ?? []);
// If fully loaded or the last page is still loading, don't request a new page
if (fullyLoaded || lastPageLoading) {
return;
}
const args = { parentUid, page: (pageNumber ?? 0) + 1, limit: PAGE_SIZE, permission };
const subscription = dispatch(browseDashboardsAPI.endpoints.listFolders.initiate(args));
const resultLegacy = useFoldersQueryLegacy(isBrowsing, openFolders, permission);
const resultAppPlatform = useFoldersQueryAppPlatform(isBrowsing, openFolders);
const selector = browseDashboardsAPI.endpoints.listFolders.select({
parentUid: subscription.arg.parentUid,
page: subscription.arg.page,
limit: subscription.arg.limit,
permission: subscription.arg.permission,
});
setSelectors((pages) => pages.concat(selector));
// the subscriptions are saved in a ref so they can be unsubscribed on unmount
requestsRef.current = requestsRef.current.concat([subscription]);
},
[state, dispatch, permission]
);
// Unsubscribe from all requests when the component is unmounted
useEffect(() => {
return () => {
for (const req of requestsRef.current) {
req.unsubscribe();
}
};
}, []);
// Convert the individual responses into a flat list of folders, with level indicating
// the depth in the hierarchy.
const treeList = useMemo(() => {
if (!isBrowsing) {
return [];
}
function createFlatList(
parentUid: string | undefined,
pages: ListFoldersQuery[],
level: number
): Array<DashboardsTreeItem<DashboardViewItemWithUIItems>> {
const flatList = pages.flatMap((page) => {
const pageItems = page.data ?? [];
return pageItems.flatMap((item) => {
const folderIsOpen = openFolders[item.uid];
const flatItem: DashboardsTreeItem<DashboardViewItemWithUIItems> = {
isOpen: Boolean(folderIsOpen),
level: level,
item: {
kind: 'folder' as const,
title: item.title,
uid: item.uid,
managedBy: item.managedBy,
},
};
const childPages = folderIsOpen && state.pagesByParent[item.uid];
if (childPages) {
const childFlatItems = createFlatList(item.uid, childPages, level + 1);
return [flatItem, ...childFlatItems];
}
return flatItem;
});
});
const [fullyLoaded] = getPagesLoadStatus(pages);
if (!fullyLoaded) {
flatList.push(...getPaginationPlaceholders(PAGE_SIZE, parentUid, level));
}
return flatList;
}
const rootFlatTree = createFlatList(undefined, state.rootPages, 1);
rootFlatTree.unshift(ROOT_FOLDER_ITEM);
return rootFlatTree;
}, [state, isBrowsing, openFolders]);
return {
items: treeList,
isLoading: state.isLoading,
requestNextPage,
};
// Running the hooks themselves don't have any side effects, so we can just conditionally use one or the other
// requestNextPage function from the result
return config.featureToggles.foldersAppPlatformAPI ? resultAppPlatform : resultLegacy;
}
export const ROOT_FOLDER_ITEM = {
isOpen: true,
level: 0,
item: {
kind: 'folder' as const,
title: 'Dashboards',
uid: '',
},
};

@ -0,0 +1,164 @@
import { createSelector } from '@reduxjs/toolkit';
import { QueryStatus } from '@reduxjs/toolkit/query';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { folderAPIv1beta1 } from 'app/api/clients/folder/v1beta1';
import { DashboardViewItemWithUIItems, DashboardsTreeItem } from 'app/features/browse-dashboards/types';
import { useDispatch, useSelector } from 'app/types/store';
import { AnnoKeyManagerKind, ManagerKind } from '../../../features/apiserver/types';
import { PAGE_SIZE } from '../../../features/browse-dashboards/api/services';
import { getPaginationPlaceholders } from '../../../features/browse-dashboards/state/utils';
import { ROOT_FOLDER_ITEM } from './utils';
type GetFolderChildrenQuery = ReturnType<ReturnType<typeof folderAPIv1beta1.endpoints.getFolderChildren.select>>;
type GetFolderChildrenRequest = {
unsubscribe: () => void;
};
const rootFolderToken = 'general';
const collator = new Intl.Collator();
/**
* Returns a loaded folder hierarchy as a flat list and a function to load folders.
* This version uses the getFolderChildren API from the folder v1beta1 API. Compared to legacy API, the v1beta1 API
* does not have pagination at the moment.
*/
export function useFoldersQueryAppPlatform(isBrowsing: boolean, openFolders: Record<string, boolean>) {
const dispatch = useDispatch();
// Keep a list of all request subscriptions so we can unsubscribe from them when the component is unmounted
const requestsRef = useRef<GetFolderChildrenRequest[]>([]);
// Keep a list of selectors for dynamic state selection
const [selectors, setSelectors] = useState<
Array<ReturnType<typeof folderAPIv1beta1.endpoints.getFolderChildren.select>>
>([]);
// This is an aggregated dynamic selector of all the selectors for all the request issued while loading the folder
// tree and returns the whole tree that was loaded so far.
const listAllFoldersSelector = useMemo(() => {
return createSelector(selectors, (...responses) => {
// Returns loading true if any of the responses is still loading
let isLoading = false;
const responseByParent: Record<string, GetFolderChildrenQuery> = {};
for (const response of responses) {
if (response.status === QueryStatus.pending) {
isLoading = true;
}
const parentName = response.originalArgs?.name;
if (parentName) {
responseByParent[parentName] = response;
}
}
return {
isLoading,
responseByParent,
};
});
}, [selectors]);
const state = useSelector(listAllFoldersSelector);
// Loads folders for the given parent UID
const requestNextPage = useCallback(
(parentUid: string | undefined) => {
const finalParentUid = parentUid ?? rootFolderToken;
const response = state.responseByParent[finalParentUid];
const isLoading = response?.status === QueryStatus.pending;
// If already loading, don't request again
if (isLoading) {
return;
}
const args = { name: finalParentUid };
// Make a request
const subscription = dispatch(folderAPIv1beta1.endpoints.getFolderChildren.initiate(args));
// Add selector for the response to the list so we can then have an aggregated selector for all the folders
const selector = folderAPIv1beta1.endpoints.getFolderChildren.select(args);
setSelectors((selectors) => selectors.concat(selector));
// the subscriptions are saved in a ref so they can be unsubscribed on unmount
requestsRef.current = requestsRef.current.concat([subscription]);
},
[state, dispatch]
);
// Unsubscribe from all requests when the component is unmounted
useEffect(() => {
return () => {
for (const req of requestsRef.current) {
req.unsubscribe();
}
};
}, []);
// Convert the individual responses into a flat list of folders, with level indicating
// the depth in the hierarchy.
const treeList = useMemo(() => {
if (!isBrowsing) {
return [];
}
function createFlatList(
parentUid: string | undefined,
response: GetFolderChildrenQuery | undefined,
level: number
): Array<DashboardsTreeItem<DashboardViewItemWithUIItems>> {
let folders = response?.data?.items ? [...response.data.items] : [];
folders.sort((a, b) => collator.compare(a.spec.title, b.spec.title));
const list = folders.flatMap((item) => {
const name = item.metadata.name!;
const folderIsOpen = openFolders[name];
const flatItem: DashboardsTreeItem<DashboardViewItemWithUIItems> = {
isOpen: Boolean(folderIsOpen),
level: level,
item: {
kind: 'folder' as const,
title: item.spec.title,
// We use resource name as UID because well, not sure what metadata.uid would be used for now as you cannot
// query by it.
uid: name,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
managedBy: item.metadata?.annotations?.[AnnoKeyManagerKind] as ManagerKind | undefined,
},
};
const childResponse = folderIsOpen && state.responseByParent[name];
if (childResponse) {
const childFlatItems = createFlatList(name, childResponse, level + 1);
return [flatItem, ...childFlatItems];
}
return flatItem;
});
if (!response) {
// The pagination placeholders are what actually triggers the call to the next page. So if there is no response,
// meaning to request for some children, we add these placeholders, and they will trigger the load.
list.push(...getPaginationPlaceholders(PAGE_SIZE, parentUid, level));
}
return list;
}
const rootFlatTree = createFlatList(rootFolderToken, state.responseByParent[rootFolderToken], 1);
rootFlatTree.unshift(ROOT_FOLDER_ITEM);
return rootFlatTree;
}, [state, isBrowsing, openFolders]);
return {
items: treeList,
isLoading: state.isLoading,
requestNextPage,
};
}

@ -0,0 +1,191 @@
import { createSelector } from '@reduxjs/toolkit';
import { QueryDefinition, BaseQueryFn, QueryActionCreatorResult } from '@reduxjs/toolkit/query';
import { RequestOptions } from 'http';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ListFolderQueryArgs, browseDashboardsAPI } from 'app/features/browse-dashboards/api/browseDashboardsAPI';
import { PAGE_SIZE } from 'app/features/browse-dashboards/api/services';
import { getPaginationPlaceholders } from 'app/features/browse-dashboards/state/utils';
import { DashboardViewItemWithUIItems, DashboardsTreeItem } from 'app/features/browse-dashboards/types';
import { FolderListItemDTO, PermissionLevelString } from 'app/types';
import { useDispatch, useSelector } from 'app/types/store';
import { ROOT_FOLDER_ITEM } from './utils';
type ListFoldersQuery = ReturnType<ReturnType<typeof browseDashboardsAPI.endpoints.listFolders.select>>;
type ListFoldersRequest = QueryActionCreatorResult<
QueryDefinition<
ListFolderQueryArgs,
BaseQueryFn<RequestOptions>,
'getFolder',
FolderListItemDTO[],
'browseDashboardsAPI'
>
>;
const PENDING_STATUS = 'pending';
/**
* Returns whether the set of pages are 'fully loaded', the last page number, and if the last page is currently loading
*/
function getPagesLoadStatus(pages: ListFoldersQuery[]): [boolean, number | undefined, boolean] {
const lastPage = pages.at(-1);
const lastPageNumber = lastPage?.originalArgs?.page;
const lastPageLoading = lastPage?.status === PENDING_STATUS;
if (!lastPage?.data) {
// If there's no pages yet, or the last page is still loading
return [false, lastPageNumber, lastPageLoading];
} else {
return [lastPage.data.length < lastPage.originalArgs.limit, lastPageNumber, lastPageLoading];
}
}
/**
* Returns a loaded folder hierarchy as a flat list and a function to load more pages.
*/
export function useFoldersQueryLegacy(
isBrowsing: boolean,
openFolders: Record<string, boolean>,
permission?: PermissionLevelString
) {
const dispatch = useDispatch();
// Keep a list of all request subscriptions so we can unsubscribe from them when the component is unmounted
const requestsRef = useRef<ListFoldersRequest[]>([]);
// Keep a list of selectors for dynamic state selection
const [selectors, setSelectors] = useState<
Array<ReturnType<typeof browseDashboardsAPI.endpoints.listFolders.select>>
>([]);
const listAllFoldersSelector = useMemo(() => {
return createSelector(selectors, (...pages) => {
let isLoading = false;
const rootPages: ListFoldersQuery[] = [];
const pagesByParent: Record<string, ListFoldersQuery[]> = {};
for (const page of pages) {
if (page.status === PENDING_STATUS) {
isLoading = true;
}
const parentUid = page.originalArgs?.parentUid;
if (parentUid) {
if (!pagesByParent[parentUid]) {
pagesByParent[parentUid] = [];
}
pagesByParent[parentUid].push(page);
} else {
rootPages.push(page);
}
}
return {
isLoading,
rootPages,
pagesByParent,
};
});
}, [selectors]);
const state = useSelector(listAllFoldersSelector);
// Loads the next page of folders for the given parent UID by inspecting the
// state to determine what the next page is
const requestNextPage = useCallback(
(parentUid: string | undefined) => {
const pages = parentUid ? state.pagesByParent[parentUid] : state.rootPages;
const [fullyLoaded, pageNumber, lastPageLoading] = getPagesLoadStatus(pages ?? []);
// If fully loaded or the last page is still loading, don't request a new page
if (fullyLoaded || lastPageLoading) {
return;
}
const args = { parentUid, page: (pageNumber ?? 0) + 1, limit: PAGE_SIZE, permission };
const subscription = dispatch(browseDashboardsAPI.endpoints.listFolders.initiate(args));
const selector = browseDashboardsAPI.endpoints.listFolders.select({
parentUid: subscription.arg.parentUid,
page: subscription.arg.page,
limit: subscription.arg.limit,
permission: subscription.arg.permission,
});
setSelectors((pages) => pages.concat(selector));
// the subscriptions are saved in a ref so they can be unsubscribed on unmount
requestsRef.current = requestsRef.current.concat([subscription]);
},
[state, dispatch, permission]
);
// Unsubscribe from all requests when the component is unmounted
useEffect(() => {
return () => {
for (const req of requestsRef.current) {
req.unsubscribe();
}
};
}, []);
// Convert the individual responses into a flat list of folders, with level indicating
// the depth in the hierarchy.
const treeList = useMemo(() => {
if (!isBrowsing) {
return [];
}
function createFlatList(
parentUid: string | undefined,
pages: ListFoldersQuery[],
level: number
): Array<DashboardsTreeItem<DashboardViewItemWithUIItems>> {
const flatList = pages.flatMap((page) => {
const pageItems = page.data ?? [];
return pageItems.flatMap((item) => {
const folderIsOpen = openFolders[item.uid];
const flatItem: DashboardsTreeItem<DashboardViewItemWithUIItems> = {
isOpen: Boolean(folderIsOpen),
level: level,
item: {
kind: 'folder' as const,
title: item.title,
uid: item.uid,
managedBy: item.managedBy,
},
};
const childPages = folderIsOpen && state.pagesByParent[item.uid];
if (childPages) {
const childFlatItems = createFlatList(item.uid, childPages, level + 1);
return [flatItem, ...childFlatItems];
}
return flatItem;
});
});
const [fullyLoaded] = getPagesLoadStatus(pages);
if (!fullyLoaded) {
flatList.push(...getPaginationPlaceholders(PAGE_SIZE, parentUid, level));
}
return flatList;
}
const rootFlatTree = createFlatList(undefined, state.rootPages, 1);
rootFlatTree.unshift(ROOT_FOLDER_ITEM);
return rootFlatTree;
}, [state, isBrowsing, openFolders]);
return {
items: treeList,
isLoading: state.isLoading,
requestNextPage,
};
}

@ -0,0 +1,9 @@
export const ROOT_FOLDER_ITEM = {
isOpen: true,
level: 0,
item: {
kind: 'folder' as const,
title: 'Dashboards',
uid: '',
},
};

@ -57,7 +57,6 @@ const config: ConfigFile = {
'../public/app/api/clients/folder/v1beta1/endpoints.gen.ts': {
apiFile: '../public/app/api/clients/folder/v1beta1/baseAPI.ts',
schemaFile: '../data/openapi/folder.grafana.app-v1beta1.json',
filterEndpoints: ['getFolder'],
tag: true,
},
'../public/app/api/clients/advisor/v0alpha1/endpoints.gen.ts': {

Loading…
Cancel
Save