navBarTree.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { createSlice, PayloadAction } from '@reduxjs/toolkit';
  2. import { NavModelItem } from '@grafana/data';
  3. import config from 'app/core/config';
  4. export const initialState: NavModelItem[] = config.bootData?.navTree ?? [];
  5. const navTreeSlice = createSlice({
  6. name: 'navBarTree',
  7. initialState,
  8. reducers: {
  9. setStarred: (state, action: PayloadAction<{ id: string; title: string; url: string; isStarred: boolean }>) => {
  10. const starredItems = state.find((navItem) => navItem.id === 'starred');
  11. const { id, title, url, isStarred } = action.payload;
  12. if (isStarred) {
  13. const newStarredItem: NavModelItem = {
  14. id,
  15. text: title,
  16. url,
  17. };
  18. starredItems?.children?.push(newStarredItem);
  19. starredItems?.children?.sort((a, b) => a.text.localeCompare(b.text));
  20. } else {
  21. const index = starredItems?.children?.findIndex((item) => item.id === id) ?? -1;
  22. if (index > -1) {
  23. starredItems?.children?.splice(index, 1);
  24. }
  25. }
  26. },
  27. updateDashboardName: (state, action: PayloadAction<{ id: string; title: string; url: string }>) => {
  28. const { id, title, url } = action.payload;
  29. const starredItems = state.find((navItem) => navItem.id === 'starred');
  30. const navItem = starredItems?.children?.find((navItem) => navItem.id === id);
  31. if (navItem) {
  32. navItem.text = title;
  33. navItem.url = url;
  34. starredItems?.children?.sort((a, b) => a.text.localeCompare(b.text));
  35. }
  36. },
  37. },
  38. });
  39. export const { setStarred, updateDashboardName } = navTreeSlice.actions;
  40. export const navTreeReducer = navTreeSlice.reducer;