Feat dock stacks and dock node#75
Open
Its4Nik wants to merge 19 commits into70-dockstore-refactor-into-dockstat-repositoryfrom
Open
Feat dock stacks and dock node#75Its4Nik wants to merge 19 commits into70-dockstore-refactor-into-dockstat-repositoryfrom
Its4Nik wants to merge 19 commits into70-dockstore-refactor-into-dockstat-repositoryfrom
Conversation
…agement - Introduce Dockerfile for containerizing the DockNode application. - Develop a comprehensive StackHandler for Docker Compose stack management, including: - CRUD operations (create, get, list, update, delete, rename, export). - Lifecycle commands (up, down, stop, restart, pull). - Information commands (ps, logs, config, network stats, version). - Execution commands (exec, run, rm, kill, port). - Expose stack management functionalities via new `/api/stacks` endpoints. - Integrate `docker-compose` for orchestration and `dockerode` for Docker API interaction. - Add `.dockerignore`, `.npmignore`, and update `.gitignore` for relevant file exclusions. - Update `README.md` with DockNode description and API examples. - Introduce application-specific logger and utility functions. - Configure `tsconfig.json` for ESNext and bundler module resolution. - Add necessary dependencies for Docker client, logger, typings, utilities, and OpenAPI.
…structor options The `DockerClient` class is now directly exportable and importable via `@dockstat/docker-client/client`, allowing for more flexible usage without needing to instantiate the `DockerClientManager`. Additionally, the `options` parameter in the `DockerClientBase` constructor has been made required, ensuring explicit configuration for client instances. The package version has been incremented to `2.0.1`.
…lass
Moved all source files into a dedicated 'src/' directory to improve project structure and maintainability. This refactor also includes a significant modularization of the 'DB' class.
Key changes include:
* All core logic previously in 'index.ts' has been moved to 'src/index.ts'.
* Extracted various concerns from the 'DB' class into new helper modules under 'src/lib':
* Backup and restore operations moved to 'src/lib/backup'.
* Index creation and dropping moved to 'src/lib/index'.
* SQL helper functions like 'isSQLFunction' moved to 'src/lib/sql'.
* Table creation logic ('buildColumnSQL', 'buildTableConstraints', 'isTableSchema', 'setTableComment', 'getTableComment') moved to 'src/lib/table'.
* Updated all relative imports in test files to point to the new 'src/' paths.
* Adjusted 'package.json' and 'tsconfig.json' to reflect the new file structure and module resolution.
* Bumped package version to 1.3.3.
- Renamed package from 'dockstore-cli' to '@dockstat/repo-cli' for consistent branding.
- Completely rewrote the README to provide comprehensive usage documentation:
- Added detailed installation instructions.
- Documented 'init', 'bundle', 'badges', and 'serve' commands with their options, descriptions, and requirement status.
- Included license information.
- Bumped package version to 1.0.4.
…on and WHERE methods - Introduce `safeStringify` utility in `WhereQueryBuilder` to robustly serialize complex values (including RegExp) for logging. - Add info-level logs to `SelectQueryBuilder` execution methods (`all`, `get`, `count`, `exists`, `value`, `pluck`) to display built queries, parameters, and results. - Add info-level logs to `WhereQueryBuilder` methods (`where`, `whereRgx`, `whereExpr`, `whereIn`, `whereOp`, `whereBetween`, `whereNull`, etc.) to track the construction of WHERE clauses and their parameters. - Remove duplicate `safeStringify` implementation from `SelectQueryBuilder` to utilize the new base class helper. - Bump package version to 1.3.4.
* feat(query-builder): Add detailed info-level logging to query execution and WHERE methods
- Introduce `safeStringify` utility in `WhereQueryBuilder` to robustly serialize complex values (including RegExp) for logging.
- Add info-level logs to `SelectQueryBuilder` execution methods (`all`, `get`, `count`, `exists`, `value`, `pluck`) to display built queries, parameters, and results.
- Add info-level logs to `WhereQueryBuilder` methods (`where`, `whereRgx`, `whereExpr`, `whereIn`, `whereOp`, `whereBetween`, `whereNull`, etc.) to track the construction of WHERE clauses and their parameters.
- Remove duplicate `safeStringify` implementation from `SelectQueryBuilder` to utilize the new base class helper.
- Bump package version to 1.3.4.
* formatting
* feat(theme-handler): Introduce theme-handler package for managing UI themes
This commit introduces the new `@dockstat/theme-handler` package, providing a comprehensive solution for managing UI themes across the application.
Key features include:
- **Client-side utilities**:
- React context (`ThemeContext`) for easily accessing theme data.
- Functions to dynamically apply theme variables (CSS custom properties) to the document.
- Local storage integration for persisting user theme preferences.
- **Server-side management**:
- `ThemeDB` class for robust SQLite database integration to store, retrieve, update, and delete themes.
- Elysia-based API routes (`/themes`) offering full CRUD capabilities for themes, including fetching by name or ID.
- **Default themes**:
- Ships with pre-defined "DockStat-Dark", "DockStat-Light", "DockStat-OLED", and "DockStat-UltraDark" themes, including their CSS variables and animation properties.
- **Bun & Elysia integration**:
- The package is set up with Bun for efficient dependency management and runtime, and Elysia for building high-performance API routes.
This package centralizes theme logic, making it easier to manage and apply consistent styling throughout the application.
* feat(ui): Add theme browser and selection functionality
This commit introduces a user interface for browsing and selecting application themes.
- **New `ThemeBrowser` Component**: A dedicated component is added to display available themes, each with a preview of its key color variables (background, primary text, accent, etc.). Users can select a theme from this browser.
- **Sidebar Integration**: The `Sidebar` component now includes a new 'Palette' icon button that opens a modal containing the `ThemeBrowser`.
- **`ThemeProps` Interface**: A `ThemeProps` interface is defined to facilitate passing theme-related data (list of themes, current theme ID, selection handler, open callback) from parent components to the `Sidebar` and subsequently to the `ThemeBrowser`.
- **Navbar Update**: The `Navbar` component is updated to accept and forward `themeProps` to the `Sidebar`, ensuring theme management can be controlled from higher up the component tree.
- Refactored the loading state check for pinned items in the Sidebar to use `mutationFn.isBusy` for a cleaner approach.
- Exports `ThemeBrowser` components for broader use within the `ui` package.
* refactor(sqlite-wrapper): Truncate excessively long stringified condition values
Introduce a `truncate` utility function to limit the length of strings.
Apply this utility within the `WhereQueryBuilder.safeStringify` method to prevent excessively long stringified values (e.g., from `JSON.stringify` or `String()`) from being returned. This improves readability in debugging logs or contexts where these values might be displayed, ensuring they don't consume too much space. The maximum length for truncated strings is set to 100 characters.
* feat(dockstat): Implement client-side theme management and provider
Introduce `ThemeProvider` to manage and apply themes within the DockStat UI. This includes:
- Adding `@dockstat/theme-handler` dependency.
- Creating `ThemeProviderContext` and `useTheme` hook for global theme state and access.
- Implementing `ThemeProvider` to handle theme fetching (by name/ID) from the API, applying themes to the document using `@dockstat/theme-handler/client` functions (`applyThemeToDocument`), and persisting user preferences (`saveThemePreference`, `loadThemePreference`).
- Integrating the `ThemeProvider` at the application root in `src/providers/index.tsx`.
- Updating `layout.tsx` to consume theme data and functions from `useTheme`, enabling theme selection capabilities in the sidebar.
- Adding a new `/stacks` route and a placeholder `StacksIndex` page.
* feat(api): Add theme management endpoints
* feat(docknode): Implement API key authentication
Introduces API key-based authentication to the docknode application. This implementation leverages the 'better-auth' library, configured to accept API keys via the 'x-docknode-key' header.
Key changes include:
- Addition of the 'better-auth' dependency to apps/docknode.
- Creation of 'src/auth/index.ts' to define the authentication setup.
- Updates to '.env.example' for `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` configuration.
- Minor updates to `bun.lock` and import reordering across various packages (e.g., `dockstat`, `sqlite-wrapper`, `theme-handler`) for consistency and dependency management.
* docs(all): Standardize formatting and add new content
- Refactored RSS feed websocket subscription path to `api.api.v2.misc.stats.rss` in `apps/dockstat/src/lib/websocketEffects/README.md`.
- Introduced a new documentation page for `Eden Query & Mutation Hooks` under `apps/docs/dockstat/patterns`, detailing `useEdenQuery` and `useEdenMutation` with code examples and type inference.
- Documented the `createIndex` method in `@dockstat/sqlite-wrapper`, providing comprehensive usage, options, and examples for index creation.
- Standardized Markdown table formatting across all documentation files for improved readability and consistency.
- Addressed minor formatting issues, including trailing commas in code snippets and ensuring all Markdown files end with a newline.
* Update apps/dockstat/src/providers/theme.tsx
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* fix(db): Remove incomplete createIndex call
* refactor(dockstat/theme): Simplify API calls in theme provider
Remove `useEdenQuery` hooks from `ThemeProvider` and replace them with direct calls to the `api` client. This streamlines data fetching for themes (by name, by ID, and all themes) by eliminating an intermediate hook layer.
Consolidate theme application and persistence logic into a new `applyAndPersistTheme` callback for improved code reuse and clarity.
The `useTheme` hook also removes its explicit error throw for usage outside `ThemeProvider`, relying on `useContext` to return `undefined` when the context is not available.
* refactor(theme-handler): modularize server API routes and models
The `theme-handler` server API has been refactored into a more modular and organized structure.
Previously, all theme API routes and associated response models were defined in a single large file (`src/server/api.ts`). This commit breaks down this monolithic file into a clear directory structure:
* **`src/server/api/models/`**: Contains schema definitions for theme data (`themeModel.ts`), mutation payloads (`themePost.ts`), and standardized API responses (`themeResponses.ts`).
* **`src/server/api/routes/`**: Contains individual files for each set of API operations: `queries.ts` (GET), `mutations.ts` (POST), `update.ts` (PUT), and `delete.ts` (DELETE).
The main `createThemeRoutes` function now composes these smaller, focused route modules, improving maintainability and readability.
Additionally, the top-level `src/index.ts` has been updated to re-export `client` and `server` modules as namespaces (`export * as client from "./client"`), providing a clearer and more explicit import structure for consumers of the package.
This refactoring aims to improve code organization, reusability of API models, and overall maintainability of the `theme-handler` package.
* refactor(query-builder/logging): Centralize logging in Select and Where builders
Refactor logging logic within `SelectQueryBuilder` and `WhereQueryBuilder` by introducing dedicated private/protected helper methods.
This change:
- Consolidates common logging patterns for query initiation and results in `SelectQueryBuilder` into `logSelectStart` and `logSelectReturn`.
- Introduces `logColumnReturn` for consistent logging in `pluck` and `value` methods.
- Centralizes logging of `where` conditions and internal state in `WhereQueryBuilder` using `logWhere` and `logWhereState`.
- Improves consistency and readability of log messages across different query execution and condition building methods.
- Reduces code duplication for logging statements, making the code more maintainable.
* feat(ui, api, theme-handler): Implement user feedback toasts and enhance theme preview
- **`dockstat`**: Added toast notifications for successful pin/unpin operations and theme selection, providing immediate user feedback.
- **`ui`**: Overhauled the `ThemeBrowser` component to display a more dynamic and accurate color preview using validated theme variables. Extracted color constants and created a `getValidColors` utility.
- **`theme-handler`**:
- Introduced `onFinish` callback to `applyThemeToDocument` for client-side feedback integration.
- Corrected the logic in the theme creation route to prevent creating themes with duplicate names (bug fix).
- Updated theme response models to use `ThemeModel` consistently and refined the delete route's response type.
- **`api`**: Improved request completion logging by including the request URL path, enhancing observability.
* Update apps/docs/dockstat/patterns/eden-query-&-mutation-hooks/README.md
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: ItsNik <info@itsnik.de>
* refactor(components): Remove unused props and refine component types
Omit 'paths' from `RepoCard` props definition to align with actual usage.
Remove 'isLoading' from `ThemeProps` in `Sidebar` as it is no longer required.
Perform minor whitespace cleanup in the `WhereQueryBuilder`.
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…gging, and add DockNode authentication
This commit introduces a comprehensive theme management system, integrates robust authentication into DockNode, and significantly enhances logging across the API and database layers for improved debuggability.
Key changes include:
**Theme Management:**
* **New `@dockstat/theme-handler` package:** Provides core logic for theme definition, storage, and application on both server and client.
* **API Integration (`apps/api`):** Adds new `/api/v2/themes` routes for CRUD operations on themes, enabling listing, retrieval, creation, updating, and deletion of custom themes.
* **Frontend Integration (`apps/dockstat`, `packages/ui`):**
* Introduces `ThemeProvider` and `useTheme` hook to manage theme state, persist user preference, and dynamically apply themes to the UI.
* Adds a "Theme Browser" modal to the sidebar, allowing users to preview and select from available themes.
* Includes default themes (Dark, Light, OLED, UltraDark) for immediate use.
* **Database Schema:** `ThemeDB` in `@dockstat/theme-handler` now manages theme data using `@dockstat/sqlite-wrapper`.
**DockNode Authentication:**
* **`better-auth` Integration (`apps/docknode`):** Implements API key-based authentication for the DockNode agent using the `better-auth` package, improving security for remote operations.
* Updates `.env.example` with relevant `BETTER_AUTH` configuration.
**Logging & Debugging Improvements:**
* **Enhanced `sqlite-wrapper` logging:** Introduces detailed logging for `SELECT` queries, including query strings, parameters, and truncated results, to aid in debugging database interactions.
* **Log Message Truncation:** Adds a `truncate` utility to `sqlite-wrapper` to prevent excessively long log messages.
* **API Middleware Logging:** Improves request logging in `apps/api` to include the specific path of incoming requests.
* **Frontend Log Viewer (`packages/ui`):** The sidebar now includes a "View Backend Logs" modal, presenting real-time log entries from the API for direct debugging within the UI.
**Additional Enhancements:**
* **New `stacks` page (`apps/dockstat`):** Introduces a placeholder page and routing for future stack management functionality.
* **UI/UX refinements (`packages/ui`, `apps/dockstat`):**
* Adds toast notifications for pinning/unpinning items in the sidebar.
* Updates `RepoCard` props for improved type safety.
* **Documentation:** Updates table formatting across various `README.md` files and adds new documentation for `sqlite-wrapper`'s `createIndex` method and Eden query/mutation hooks.
* **Websocket API path fix (`apps/dockstat`):** Corrects a websocket API endpoint prefix in a `README.md` example.
Contributor
There was a problem hiding this comment.
Sorry @Its4Nik, your pull request is larger than the review limit of 150000 diff characters
…pages This commit brings significant updates including configurable hotkeys, a new DockNode section, and various UI enhancements. **Hotkeys:** - Add `hotkeys` field to the global configuration schema (`DockStatConfigTable`) and context (`ConfigProviderData`). - Define `HotkeyAction` type for better type safety of configurable hotkey actions (e.g., "open:quicklinks"). - Set a default hotkey `k` for opening quick links in the database defaults. - Integrate configurable hotkeys into the `Navbar` and `LinkLookup` components, allowing customization of the quick links modal hotkey. **DockNode & Stacks:** - Create new pages for `/node` (DockNode overview) and `/node/stacks` (Stacks within a DockNode). - Refactor and move the existing `/stacks` functionality to the new `/node/stacks` route, deleting the old `/stacks` page. - Update the application router and sidebar navigation to reflect the new DockNode structure. **UI & Accessibility:** - Enhance the `Card` component with a `tabIndex` prop to improve keyboard navigation and focus management. - Adjust tab indexing within the `LinkLookup` modal for better accessibility. - Apply minor styling and structure adjustments to sidebar items, including child item formatting. **Refactoring:** - Streamline theme loading state management in the main layout by removing unnecessary `isLoading` prop from `useTheme` consumer.
Create a new `useHotkey` React hook in `@dockstat/utils/react` to provide a centralized and declarative way for components to manage keyboard shortcuts.
- Migrate existing hotkey handling logic in `LinkLookup` component (for quick links modal) to utilize the new `useHotkey` hook.
- Integrate the `useHotkey` hook into the `Navbar` component to manage sidebar `open`, `close`, and `toggle` actions, making hotkey management consistent.
- Add `toggle:sidebar` hotkey (`b` by default) to the default application configuration in `packages/db`.
- Refactor utility imports across `apps/api` and `packages/plugin-handler` to use barrel exports from `@dockstat/utils` (e.g., `import { repo } from "@dockstat/utils"` instead of direct path imports).
- Update various project dependencies.
…e registration
This commit introduces a comprehensive system for managing DockNode instances from the main DockStat API and frontend. Users can now register, monitor, and remove external DockNode servers, enhancing distributed management capabilities.
**Key Changes:**
* **API (`apps/api`):**
* Added `@dockstat/docknode` and `@elysiajs/eden` dependencies.
* Implemented `DockNodeHandler` to manage DockNode registration within a new `docknode-register` SQLite table. This includes functionality for checking node reachability, creating, and deleting entries.
* Exposed new `/api/v2/node` endpoints (`GET`, `POST`, `DELETE`) for performing CRUD operations on DockNode registrations.
* Defined Elysia TypeBox models for robust API request validation.
* **DockNode (`apps/docknode`):**
* Added a `GET /api/status` endpoint, allowing the main API to perform health checks and determine if a registered DockNode is online.
* Configured the SQLite database to use Write-Ahead Logging (WAL) journal mode for improved performance and data integrity.
* **Frontend (`apps/dockstat`):**
* Created a new "DockNodes" page (`src/pages/node/index.tsx`) in the UI to list, create, and delete DockNode registrations.
* Developed the `DockNodeCard` React component to visually represent each registered node, displaying its status, host, port, SSL usage, and providing options for interaction.
* Integrated new `useEdenQuery` and `useEdenMutation` hooks for seamless interaction with the API.
* **Database & Typings (`packages/db`, `packages/typings`):**
* Refactored the `tls_certs_and_keys` field in the main `config` table to a more generic `keys` object.
* Extended the `keys` object to include a dedicated slot for `docknode` specific API keys, enabling future secure communication.
* Improved type definitions for foreign keys in `packages/sqlite-wrapper`.
* **Utilities (`packages/utils`):**
* Introduced a new set of React Query-based utility hooks (`useEdenQuery`, `useEdenMutation`, `useEdenRouteMutation`) for `elysia/eden` clients. These hooks simplify data fetching and mutations, providing standardized error handling, loading states, and automatic query invalidation.
* Added `@tanstack/react-query` as a dependency.
* **Build & Development:**
* Updated the `dev:dockstat` script to include `--filter=@dockstat/docknode` for integrated development.
* Updated various dependencies across the monorepo.
This feature lays the groundwork for centralized management of distributed DockNode services.
Refactor the `Slides` component in `@packages/ui` to dynamically measure and animate content height. This change leverages `ResizeObserver` to ensure that slides with dynamic content automatically adjust their height during transitions, resulting in a smoother and more responsive user experience. The previous `collapseVariants` animation logic is replaced with direct height and opacity animations. Additionally, the `overflow-hidden` class is removed from the `Slides` `CardBody` as `SlideContent` now manages its own overflow for animation.
Redesign the `DockNodeCard` component in the `dockstat` application, introducing significant visual and structural improvements:
- Updated layout and spacing for better readability.
- Refined typography and enhanced status badges.
- Improved presentation of connection details.
- Restyled `CardFooter` with updated action button presentation and text ("Visit" changed to "Open").
- Minor adjustments to event handling for the delete action, including explicit `e.stopPropagation()`.
…kStat into feat-DockStacks-and-DockNode
* feat(hotkeys): Implement configurable hotkey management
Introduce a comprehensive hotkey management system within the application settings.
- **API:** Added a new `POST /config/hotkey` endpoint to allow users to update and persist their hotkey preferences in the database.
- **Frontend (DockStat):**
- Created a new `SettingsPage` with a dedicated "Hotkeys" slide.
- The `HotkeysSlide` provides an intuitive UI for users to configure global hotkeys, including support for `CTRL + SHIFT + <key>` combinations.
- Integrates with the new API endpoint to save changes and provides immediate feedback.
- **Hotkeys Utility:** Enhanced the `useHotkey` hook to support `shift+key` combinations and a generic `toggle` function, making hotkey handling more flexible.
- **Configuration:** Updated default hotkey configurations to include new actions such as `open:sidebar` and `close:sidebar`.
- **UI Integration:** Adapted components like `Navbar` and `LinkLookup` to consume dynamic hotkey configurations.
- **Database/Typings:** Updated database models and type definitions (`DatabaseModel.hotkeyRes`, `DatabaseModel.hotkeyBody`, `HotkeyAction`) to reflect the new hotkey structure.
* refactor(codebase): Reorder imports and remove unused declarations
* feat(settings): Introduce General Settings page and API config management
This commit introduces a new "General Settings" page in the DockStat frontend and expands the backend API for configuration management.
Key changes include:
* **API & Database (`apps/api`, `packages/db`, `packages/typings`):**
* **Fix(config):** Corrected a widespread typo from `addtionalSettings` to `additionalSettings` in database schemas, typings, default configurations, and API models. This ensures consistency and correctness of the configuration object.
* Added `GET /db/details` and `GET /db/details/:tableName/all` endpoints for database introspection, providing schema information and raw table data.
* Implemented `POST /db/config/additionalSettings` for updating application-wide settings such as `showBackendRamUsageInNavbar`.
* Added TypeBox schemas for `additionalSettingsBody` and `additionalSettingsRes`.
* **Frontend (`apps/dockstat`):**
* Introduced the `GeneralSettingsSlide` component as the main entry point for general settings.
* Implemented `PinnedNavSection` to manage user-pinned navigation links.
* Developed `PinnableLinksSection` to allow users to discover and pin available dashboard links, including those provided by plugins.
* Added `PluginLinksSection` to display all detected plugin-provided routes.
* Created `AdditionalSettingsSection` to control specific application behaviors, starting with the option to display backend RAM usage in the navbar.
* Updated the `/settings` page to integrate the new `GeneralSettingsSlide`.
* Refactored the `ConfigProvider` to correctly handle `additionalSettings` and provide it to the application context.
* Minor UI adjustments in `HostsList` and `ClientsPage` for improved layout and consistency.
* Fixed hotkey display to correctly replace both `_` and `:` with spaces.
* **UI Library (`packages/ui`):**
* Expanded `Badge` component with an `xs` size option.
* Adjusted `Divider` vertical orientation to use `min-h-full` for better responsiveness.
* Enhanced `Slides` component with improved content transition animations and a `ResizeObserver` for dynamic height adjustments.
* Exported `SidebarPaths` and `PathItem` from Navbar for broader use in navigation.
* **Other:**
* Updated `apps/docknode/.gitignore` to include `docknode.db*` for better exclusion of database files and backups.
This comprehensive update streamlines configuration management and provides users with more control over their DockStat experience.
* chore(ci): Lint [skip ci]
* fix(formatting): adjusted imports
* fix(remove unwanted): remove database file from git tree
* feat(ui, api): Enhance UI components and streamline API error responses
Refactor:
- API: Removed redundant 'error' field from additional settings update error response in `db.ts` to ensure consistent error payload with `message`.
Dockstat App:
- UI/Hosts: Simplified the display for "no hosts configured" by removing an unnecessary card and icon.
- UI/Settings: Enhanced pinned navigation section with a fixed height, vertical resizing, and scroll functionality for improved usability.
UI Package:
- Badges: Corrected `xs` badge padding from `py-.5` to `py-0.5` for consistent styling.
- Slides: Fixed `useSlideState` by adding `activeSlide` to `useEffect` dependencies, ensuring proper re-measurement on slide changes.
- Theme Browser: Added `m-1` margin to `ThemePreviewCard` for improved visual spacing between theme previews.
* feat(db:migration): Implement automatic schema migration (#78)
* feat(db:migration): Implement automatic schema migration
This commit introduces automatic schema migration capabilities to the `sqlite-wrapper`.
The `db.createTable()` method now automatically detects schema changes when a table already exists and performs an atomic migration if differences are found. This process ensures smooth schema evolution without manual intervention, including:
- Creating a temporary table with the new schema.
- Copying existing data, mapping common columns and applying defaults for new ones.
- Recreating indexes, triggers, and foreign key constraints.
- Swapping the tables safely within a transaction.
**Key Migration Features & Options:**
- **Schema Detection**: Automatically identifies additions, removals, and changes in column constraints (NOT NULL, UNIQUE, Primary Key status) and types.
- **Data Preservation**: Data is preserved by default (`preserveData: true`), with options to control how constraint violations are handled (`onConflict: 'fail' | 'ignore' | 'replace'`).
- **Customization**: Supports `dropMissingColumns` and `tempTableSuffix` for fine-grained control.
- **Disabling Migration**: Migration can be explicitly disabled per table using `migrate: false` in `TableOptions`.
- **Type Handling**: Correctly migrates JSON and Boolean columns.
This feature significantly simplifies schema management for applications using `sqlite-wrapper`.
A new test suite (`__test__/migration.test.ts`) has been added to thoroughly validate various migration scenarios.
The `README.md` has been updated to document the new "Automatic Schema Migration" feature in detail, including usage examples and best practices. The package version is bumped to `1.3.5`.
* deps(bun): update @types/bun to 1.3.9
* fix(migration): improve migration robustness and add comprehensive tests
Migration robustness:
- Foreign key `PRAGMA` statements are now correctly handled outside the migration transaction, ensuring proper disabling and re-enabling of FK constraints for reliable table alterations.
- Improved logging in `schemasAreDifferent` to provide more detail on column count differences.
- The `currentSchema` is now passed to `migrateTable` from `checkAndMigrate` to avoid redundant database calls.
New migration tests:
- Added a test to verify that migration fails with the default `onConflict` strategy when constraints (e.g., `NOT NULL`) are violated.
- Added tests to confirm that no actual migration (ALTER TABLE) occurs when switching between type aliases (e.g., `TEXT` to `JSON`, `INTEGER` to `BOOLEAN`), ensuring data is preserved and correctly interpreted.
Type centralization:
- Moved `TableColumn`, `IndexInfo`, `ForeignKeyInfo`, and `ForeignKeyStatus` interfaces to `src/types.ts` for better organization and reusability.
Minor fixes and improvements:
- Corrected the in-memory database name check from `:memory` to `:memory:` in the `DB` class.
- Updated README.md to fix a typo from "Wrong packing" to "incorrect packaging".
- Removed the `dropMissingColumns` option from `MigrationOptions` as it was never implemented.
* Sqlite wrapper automatic table migration on schema change (#79)
* feat(db:migration): Implement automatic schema migration
This commit introduces automatic schema migration capabilities to the `sqlite-wrapper`.
The `db.createTable()` method now automatically detects schema changes when a table already exists and performs an atomic migration if differences are found. This process ensures smooth schema evolution without manual intervention, including:
- Creating a temporary table with the new schema.
- Copying existing data, mapping common columns and applying defaults for new ones.
- Recreating indexes, triggers, and foreign key constraints.
- Swapping the tables safely within a transaction.
**Key Migration Features & Options:**
- **Schema Detection**: Automatically identifies additions, removals, and changes in column constraints (NOT NULL, UNIQUE, Primary Key status) and types.
- **Data Preservation**: Data is preserved by default (`preserveData: true`), with options to control how constraint violations are handled (`onConflict: 'fail' | 'ignore' | 'replace'`).
- **Customization**: Supports `dropMissingColumns` and `tempTableSuffix` for fine-grained control.
- **Disabling Migration**: Migration can be explicitly disabled per table using `migrate: false` in `TableOptions`.
- **Type Handling**: Correctly migrates JSON and Boolean columns.
This feature significantly simplifies schema management for applications using `sqlite-wrapper`.
A new test suite (`__test__/migration.test.ts`) has been added to thoroughly validate various migration scenarios.
The `README.md` has been updated to document the new "Automatic Schema Migration" feature in detail, including usage examples and best practices. The package version is bumped to `1.3.5`.
* deps(bun): update @types/bun to 1.3.9
* fix(migration): improve migration robustness and add comprehensive tests
Migration robustness:
- Foreign key `PRAGMA` statements are now correctly handled outside the migration transaction, ensuring proper disabling and re-enabling of FK constraints for reliable table alterations.
- Improved logging in `schemasAreDifferent` to provide more detail on column count differences.
- The `currentSchema` is now passed to `migrateTable` from `checkAndMigrate` to avoid redundant database calls.
New migration tests:
- Added a test to verify that migration fails with the default `onConflict` strategy when constraints (e.g., `NOT NULL`) are violated.
- Added tests to confirm that no actual migration (ALTER TABLE) occurs when switching between type aliases (e.g., `TEXT` to `JSON`, `INTEGER` to `BOOLEAN`), ensuring data is preserved and correctly interpreted.
Type centralization:
- Moved `TableColumn`, `IndexInfo`, `ForeignKeyInfo`, and `ForeignKeyStatus` interfaces to `src/types.ts` for better organization and reusability.
Minor fixes and improvements:
- Corrected the in-memory database name check from `:memory` to `:memory:` in the `DB` class.
- Updated README.md to fix a typo from "Wrong packing" to "incorrect packaging".
- Removed the `dropMissingColumns` option from `MigrationOptions` as it was never implemented.
* refactor(sqlite-wrapper): Extract createTable helper methods
Introduces `normalizeMigrationOptions` to centralize the parsing of the `migrate` option into a standardized `{ enabled, options }` object.
Adds `shouldCheckExistingTable` to encapsulate the conditions for checking if a table already exists (e.g., excluding temporary or in-memory tables).
These private helper methods refactor the `createTable` method, improving its readability and maintainability by extracting complex conditional logic. This makes the `createTable` method more focused on its primary responsibility.
* feat(sqlite-wrapper): Introduce migration onConflict options and SQL-based schema comparison
**Migration Conflict Resolution:** Adds `onConflict` options (`ignore` and `replace`) to schema migration, allowing users to define how existing data is handled when new unique constraints are introduced during a migration.
**Robust Schema Comparison:** Reworks the `schemasAreDifferent` logic to compare the full `CREATE TABLE` SQL statements. This provides a more precise and comprehensive detection of schema changes, including intricate column definitions, constraints, and default values, greatly improving migration reliability.
**SQL Generation Refactoring:** Extracts the `CREATE TABLE` SQL generation into a new `buildTableSQL` utility function, enhancing modularity and reusability.
**Standardized Migration Options:** Normalizes the `migrate` option in `TableOptions` to always be a `MigrationOptions` object, providing a consistent API for configuring migration behavior.
Updates internal schema retrieval mechanisms and tests to leverage the full `CREATE TABLE` SQL for migration decisions.
* fix(sqlite-wrapper): Correct handling of 'migrate' option in migrateTable
* refactor(types): Relax column definition type constraints
The `InferTableSchema` type in `plugin-builder` and `PluginConfig['table']['columns']` (along with `DBPlugin`'s generic type) in `typings` were previously constrained to `Record<string, ColumnDefinition>`.
This commit relaxes these constraints to `Record<string, unknown>`. This change offers greater flexibility for defining columns within plugin configurations and during table schema inference, reducing tight coupling to the `ColumnDefinition` type from `@dockstat/sqlite-wrapper`. It allows for more generic or custom column definitions without needing to strictly conform to `ColumnDefinition` at the interface level.
Additionally, this commit includes minor import reordering in `sqlite-wrapper` and `migration` for consistency.
* feat(sqlite-wrapper): Prevent auto-migration for temporary and in-memory tables
The `createTable` method will no longer automatically apply schema migrations to certain types of tables.
This change introduces an `allowMigration` utility that determines if a table is eligible for automatic schema migration based on its properties and name. Migrations are now explicitly denied for:
- Tables created with the `temporary: true` option.
- In-memory tables (identified by the name `":memory:"`).
- Tables prefixed with `temp_` (which SQLite uses for internal temporary objects).
- Tables used internally by the migration process (matching `_migration_temp` suffix).
This ensures that only persistent, user-managed tables are subject to schema changes, preventing unintended modifications to ephemeral table structures.
Additionally, the `createTable` method now includes a `try...catch` block to handle `SQLiteError` with `errno === 1` (table already exists). This allows the method to gracefully proceed and return the `QueryBuilder` for an existing table even if a `CREATE TABLE` statement fails because the table already exists, ensuring robust behavior in various scenarios.
New tests have been added to validate that temporary and in-memory tables do not trigger automatic schema migrations.
---------
Signed-off-by: ItsNik <info@itsnik.de>
* 80 migrations always run when ifnotexists is true (#81)
* feat(migration): Implement automatic table schema migration and refactor logging
This release introduces robust automatic schema migration capabilities for tables managed by `sqlite-wrapper`, alongside a comprehensive refactor of the internal logging system.
**Automatic Schema Migration:**
* **Intelligent Detection**: `createTable` now automatically detects schema differences (column additions, removals, constraint changes, default values) between the existing table and the desired schema.
* **Data Preservation**: Migrations are performed without data loss by creating a temporary table, copying data, and re-creating the original table.
* **Flexible Conflict Handling**: Supports `onConflict` strategies (`ignore`, `replace`) during migration when adding unique constraints that might conflict with existing data.
* **Index and Foreign Key Preservation**: Ensures that existing indexes and foreign key constraints are re-established after migration.
* **Alias-Aware Type Handling**: Correctly identifies column type aliases (e.g., `JSON` as `TEXT`, `BOOLEAN` as `INTEGER`) to prevent unnecessary migrations.
* **Migration Control**: Introduces `migrate` options to explicitly enable/disable migration or customize the temporary table suffix.
* **Exclusion for Special Tables**: Automatically skips migration for `:memory:` databases and `TEMPORARY` tables.
* **Enhanced Comparison**: The `schemasAreDifferent` logic has been improved to normalize `CREATE TABLE` statements (removing `IF NOT EXISTS` and normalizing quoting) for more accurate comparisons.
**Logging Refactor:**
* **Unified Logger**: Migrated from a custom `SqliteLogger` to `@dockstat/logger` across the entire codebase.
* **Hierarchical Logging**: Implemented `logger.spawn()` to create child loggers for `DB`, `Table`, `Backup`, `Migration`, `QueryBuilder` (and its sub-builders like `Insert`, `Select`, `Update`, `Delete`), and `Transformer` components, providing clearer context in logs.
* **Detailed Messages**: Reviewed and refined log messages for all major operations to provide more informative debug, info, and error output.
**Other Enhancements:**
* **`InsertResult` Extension**: The `insert` and `batchInsert` methods now return an optional `insertedIDs` array in the `InsertResult` type, providing all IDs generated during a batch operation.
* **Comprehensive Testing**: Added extensive unit tests for migration logic, schema difference detection, and various migration scenarios to ensure reliability.
* refactor(logging): Standardize logging with @dockstat/logger
Removed the custom `SqliteLogger` implementation and its associated utilities from `src/utils/logger.ts`.
All logging within the `sqlite-wrapper` package now directly uses `Logger` from the `@dockstat/logger` package.
This change:
- Simplifies the codebase by eliminating a custom logging abstraction.
- Reduces maintenance overhead.
- Ensures consistent logging practices across the Dockstat ecosystem by leveraging a shared library.
- Updated relevant test files (`migration.test.ts`, `schemasAreDifferent.test.ts`) to use the new logger.
- Updated package description to reflect comprehensive features.
* chore(ci): Lint [skip ci]
* fix(sqlite-wrapper): Enhance schema comparison and standardize logging
- **Migration Module:**
- Implement `normalizeCreateTable` helper to robustly handle `IF NOT EXISTS` clauses and quoted identifiers during `CREATE TABLE` schema comparison.
- Update `schemasAreDifferent` to leverage the new normalization for consistent and accurate schema comparisons.
- Adjust test fixture `SCHEMA_WITH_IF_NOT_EXISTS` to include `IF NOT EXISTS` for migration tests.
- **Query Builder Module:**
- Improve logging consistency by using `JSON.stringify` for query parameters in `SelectQueryBuilder` and `UpdateQueryBuilder`.
- Correct logger scope from `INSERT` to `WHERE` in `WhereQueryBuilder`'s constructor.
- Fix "Resseting" typo to "Resetting" in `BaseQueryBuilder`'s `reset` and `resetWhereConditions` debug messages.
- **Package Metadata:**
- Bump package version to `1.3.11`.
- Correct "automati" typo to "automatic" in the package description.
* feat(core): Enhance UI with Framer Motion & refactor multi-client container stats
feat(ui):
- Integrate Framer Motion for smooth animations on buttons and navbar badges, improving overall UI responsiveness and interactivity.
- Redesign General Settings sections for better layout and clarity, introducing a new "Link Settings" header.
- Enhance Extensions page with an onboarding prompt to add the default repository for new users.
- Update Pinned Links icon to 'Pin' and refine sidebar item display by removing unnecessary prefixes.
feat(api):
- Refactor Docker client manager to aggregate container statistics across all initialized clients, providing a unified view via `getAllContainerStats`.
- Update API route `/all-containers` to utilize the new multi-client container stats aggregation.
feat(packages):
- Release `@dockstat/theme-handler` v2.0.0 as a public package, complete with a comprehensive README detailing its features, API, and usage.
chore(deps):
- Update `turbo` to `^2.8.10`.
- Update `@dockstat/sqlite-wrapper` to `1.3.8`.
style:
- Adjust various text colors to use `primary-text` for consistency across UI components.
- Standardize card variants to `flat` in several settings sections for a cleaner look.
- Refine toast success message for additional settings updates.
* fix(query-builder): Adjust logger hierarchy and inheritance
Previously, the `BaseQueryBuilder` would incorrectly spawn an additional "QB" logger from the `baseLogger` provided in its constructor, rather than using the `baseLogger` directly (which is already intended to be the QueryBuilder's logger).
Additionally, descendant query builders (Insert, Select, Update, Delete) would spawn their specific loggers (e.g., "INSERT") directly from the original `baseLogger` passed to `BaseQueryBuilder`. This resulted in these sub-loggers being siblings of the main "QB" logger, instead of children.
This commit corrects the logger initialization logic:
1. `BaseQueryBuilder` now directly uses the `baseLogger` if provided, assuming it is already the designated "QB" logger. If no `baseLogger` is provided, a new "QB" logger is created.
2. Sub-query builders now spawn their specific loggers from `this.log` (the QueryBuilder's main logger), ensuring the correct hierarchical structure: `Root Logger -> QB Logger -> [Delete/Insert/Select/Update] Logger`.
This change improves logging clarity and ensures proper inheritance of log hooks throughout the query builder stack.
* refactor(ui/Button): Extract button and spinner animations to dedicated files
Moved Framer Motion animation definitions for the `Button` component's active/inactive states and the loading spinner into `animations.ts`.
Encapsulated the loading spinner's `motion.span` and its animation logic into a new `ButtonSpinner` component, located in `spinner.tsx`.
This refactoring centralizes animation logic, enhancing modularity and reusability, and cleaning up the main `Button.tsx` file for improved readability and maintainability.
---------
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
* feat(ui/theme): Implement comprehensive theme customization and editor
This commit introduces a suite of features for advanced theme customization within DockStat.
Key changes include:
* **Theme Editor UI**: Added new `ThemeEditor` and `ThemeSidebar` components, allowing users to dynamically adjust individual color variables of the current theme directly from the settings page.
* **Dynamic Theme Adjustments**: Enhanced `ThemeProviderContext` with `adjustCurrentTheme` to apply real-time color changes to the application's CSS variables and `isModifiedTheme` to track unsaved changes.
* **New Theme Creation**: Integrated a mutation to `createNewThemeFromCurrent`, enabling users to save their customized theme as a new theme.
* **Improved Theme Persistence**: The selected theme preference now stores both the theme ID and name, providing better context upon reload.
* **Categorized Color Editing**: Theme colors are now categorized by UI component (e.g., Buttons, Cards, Forms) within the `ThemeSidebar` for easier navigation and editing.
* **Logging Enhancements**: SQLite queries now truncate long parameter lists in logs for improved readability.
* **Dependency Updates**: Various packages across the monorepo, including `@dockstat/ui`, `@dockstat/theme-handler`, `elysia`, `react`, and Storybook, have been updated to their latest versions to support these new features and maintain compatibility.
* **Documentation Update**: Updated the `theme-handler` README to reflect the new client-side setup and usage patterns.
This allows for a much more flexible and user-friendly experience for tailoring DockStat's visual appearance.
* feat(theme): Implement theme editor sidebar and hotkeys
Introduces a new dedicated sidebar for theme editing, allowing users to dynamically
adjust theme colors (CSS variables) directly from the application's UI.
This feature includes:
- Integration of a new `ThemeSidebar` component, accessible via a dedicated button
in the main sidebar and configurable hotkeys.
- Addition of `toggle:themeEditor`, `open:themeEditor`, and `close:themeEditor`
hotkeys, with 't' set as the default key for toggling the editor.
- Updates to `db/defaults.ts` and `typings` to support the new hotkeys.
- Refinement of theme color adjustment logic in `layout.tsx` and `settings.tsx`
to use the `adjustCurrentTheme` function for consistent updates.
- Implementation of `reverseSlideInVariants` for the new sidebar's animation.
- Removal of unnecessary `console.log` statements.
* feat(theme): Centralize ThemeSidebar state and globalize rendering
This commit refactors the `ThemeSidebar` component to improve the theme customization experience and ensure its consistent behavior across the application.
* **Centralized State Management**: Introduced `ThemeSidebarContext` and `ThemeSidebarProvider` to centralize the management of the theme sidebar's open/close state and associated theme properties.
* **Global Rendering**: Moved the `ThemeSidebar` rendering from `packages/ui/src/components/Sidebar/Sidebar.tsx` to `apps/dockstat/src/layout.tsx`, making it a global, application-wide overlay.
* **Dynamic Data Provisioning**: `apps/dockstat/src/layout.tsx` now populates the `ThemeSidebarContext` with dynamic theme data and callback functions from the `useTheme` hook, ensuring the sidebar always displays the current theme information.
* **UI Component Integration**: Updated `packages/ui/src/components/Sidebar/Sidebar.tsx` to interact with the theme sidebar exclusively through the new context, removing its internal state management for the sidebar.
* **Theme Sidebar Enhancements**: Enhanced `packages/ui/src/components/ThemeSidebar/ThemeSidebar.tsx` with functionality to track theme modifications and include a placeholder for saving new theme configurations.
* **Modal Transparency**: Applied `transparent` prop to `Modal` components in `packages/ui/src/components/Sidebar/Sidebar.tsx` for improved visual integration.
* **Code Cleanliness**: Performed minor import reordering across several files.
* feat(theme): Implement comprehensive theme management and editor redesign
This commit introduces a complete overhaul of theme management capabilities, including full CRUD operations, a redesigned theme editor UI, and significant improvements to data fetching and state management.
- **Theme Management:**
- Enabled creation of new themes based on the currently active theme's variables.
- Added functionality to delete custom themes directly from the theme browser.
- Refined theme selection to ensure immediate application and persistence.
- **Theme Editor Redesign:**
- Introduced a new, more organized color editing interface with a scrollable list, providing better visibility and detailed information for each color variable.
- Improved layout and integration of individual color pickers.
- **React Query Integration & Enhancements:**
- Introduced `QueryClientContext` for centralized React Query client management.
- Added `edenQuery` as a specialized hook for programmatic Eden API data fetching, complementing `useEdenQuery`.
- Refactored `ThemeProvider` to utilize `edenQuery` for efficient theme list fetching and robust refetching mechanisms.
- Added detailed JSDoc comments to `useBaseEdenMutation`, `useEdenRouteMutation`, and `extractEdenError` for enhanced developer clarity and usage guidance.
- **API & Context Updates:**
- Modified the theme deletion endpoint from using a path parameter (`DELETE /themes/:id`) to accepting the `id` in the request body (`DELETE /themes`).
- Extended `ThemeSidebarContext` to include `addNewTheme` and updated `toastSuccess` to accept theme names, providing more contextual feedback.
- **UI/UX Refinements:**
- Updated text colors in `LinkLookup` to align with the active theme.
- Adjusted `ThemeSidebar` width and integrated a dedicated modal for saving new themes.
- **Hotkeys:**
- Changed the hotkey for `toggle:themeEditor` from `t` to `p` to prevent conflicts.
* refactor(dockstat): Refactor layout into modular hooks and improve context initialization
The monolithic `layout.tsx` component has been refactored into a dedicated `src/layout` directory, organizing related logic into smaller, reusable custom hooks. This significantly improves code organization, readability, and maintainability by separating concerns.
Key changes include:
* **Layout Component Decomposition**: The main `Layout` component is now located in `src/layout/components/Layout.tsx`.
* **Modular Hooks**:
* `useLayout`: Consolidates state and effects for the primary layout.
* `useThemeManager`: Encapsulates theme-related logic, including application, adjustment, and creation.
* `useLogs`, `useRamUsage`, `usePinMutations`, `usePluginRoutes`, `useDeleteTheme`: Extract specific functionalities into dedicated hooks.
* **QueryClient Context Initialization**: The `QueryClientContext` now initializes with a proper `new QueryClient()` instance, ensuring a fully functional client is always provided. The `QueryClientProvider` also now wraps its children with `QueryClientContext.Provider`.
* **Theme Provider Simplification**:
* The `getAllThemes` function has been removed from `ThemeProviderData` and the `ThemeProvider` context, as theme list updates are now handled more directly via `useEdenQuery`.
* Toast notifications related to theme cache updates from theme creation mutations have been removed, aligning with the simplified theme list refresh.
* chore(ci): Lint [skip ci]
* refactor(core): Standardize Eden API query functions and streamline React Query setup
- **feat(eden-query)**: Introduced `createEdenQueryFn` helper to standardize query function creation for Eden API calls, including signal handling and error extraction.
- Centralized Eden-related types (`EdenQueryRoute`, `EdenQueryData`, `UseEdenQueryOptions`) in a dedicated file, removing duplication from `useEdenQuery`.
- **refactor(query-client)**: Exported a singleton `QueryClient` instance from its context file and simplified `QueryClientProvider` to use this shared instance, removing redundant instantiation.
- **refactor(theme)**: Cleaned up `useThemeManager` by removing unnecessary `useRef` wrappers for theme application functions. Refactored theme application logic in `ThemeProvider` using `applyThemeEffect` for improved reusability and state management.
- **fix(layout)**: Corrected an incorrect hotkey assignment for opening the sidebar in the `Layout` component.
* chore(ci): Lint [skip ci]
* refactor(theme-management): Decouple theme sidebar contexts and streamline prop passing
Refactor theme sidebar state management to improve separation of concerns and reduce prop drilling.
- Split the monolithic `ThemeSidebarContext` into:
- `ThemeSidebarContext`: For domain logic (e.g., `addNewTheme`).
- `ThemeSidebarUIContext`: For UI state (e.g., `isThemeSidebarOpen`).
- Eliminated the `themeProps` object; individual theme-related properties are now passed explicitly to components (`Navbar`, `Sidebar`, `ThemeSidebar`).
- Introduced a new `useLayout` hook to centralize layout-related data and theme management logic.
- Restructured `ThemeSidebarProvider` to utilize the new, separate UI and domain contexts.
- Added support for `toggle:themeEditor` hotkey to control the theme sidebar visibility.
- Enhanced `ThemeEditor` component with a `multiColumn` prop for improved layout flexibility.
* chore(ci): Lint [skip ci]
* refactor(core): Streamline theme data flow and module resolution
* refactor(theme): Simplify theme sidebar provider and clean up Navbar theme props
Merged ThemeSidebarDomainProvider into ThemeSidebarProvider to streamline theme sidebar logic and state management.
Removed currentThemeName and currentThemeColors props from Navbar component, as these are now directly accessed via the useTheme context.
* fix(dockstat-thememanager): Add ref dependencies to theme manager useEffects
* refactor(theme-management): Decouple theme sidebar contexts and strea… (#90)
* refactor(theme-management): Decouple theme sidebar contexts and streamline prop passing
Refactor theme sidebar state management to improve separation of concerns and reduce prop drilling.
- Split the monolithic `ThemeSidebarContext` into:
- `ThemeSidebarContext`: For domain logic (e.g., `addNewTheme`).
- `ThemeSidebarUIContext`: For UI state (e.g., `isThemeSidebarOpen`).
- Eliminated the `themeProps` object; individual theme-related properties are now passed explicitly to components (`Navbar`, `Sidebar`, `ThemeSidebar`).
- Introduced a new `useLayout` hook to centralize layout-related data and theme management logic.
- Restructured `ThemeSidebarProvider` to utilize the new, separate UI and domain contexts.
- Added support for `toggle:themeEditor` hotkey to control the theme sidebar visibility.
- Enhanced `ThemeEditor` component with a `multiColumn` prop for improved layout flexibility.
* chore(ci): Lint [skip ci]
* refactor(core): Streamline theme data flow and module resolution
* refactor(theme): Simplify theme sidebar provider and clean up Navbar theme props
Merged ThemeSidebarDomainProvider into ThemeSidebarProvider to streamline theme sidebar logic and state management.
Removed currentThemeName and currentThemeColors props from Navbar component, as these are now directly accessed via the useTheme context.
* fix(dockstat-thememanager): Add ref dependencies to theme manager useEffects
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
* import adjustments
* style(theme-manager): Remove trailing whitespace in useThemeManager hook
* chore(deps): Remove bun.lock file
* feat(theme): Persist dynamic theme variable adjustments and add dev debug logging
* refactor(hooks): Improve Eden query functions and theme manager
- **`useEdenQuery` and `edenQuery`:**
- Simplified the `useEdenQuery` signature by consolidating options into a single object, enhancing readability and extensibility.
- Refactored `edenQuery` to directly utilize `useEdenQuery` with `enabled: false`, removing redundant logic and improving maintainability.
- Removed an unused `EdenQueryData` type import.
- **`useThemeManager`:**
- Eliminated redundant `useRef` patterns by directly using `applyThemeById` and `adjustCurrentTheme` from `useTheme`, aligning with React hook best practices.
- Decomposed theme-related operations into more focused, reusable functions (`updateColor`, `selectTheme`).
- Implemented `useCallback` for `selectTheme` to prevent unnecessary re-renders.
- Improved semantic clarity by renaming `toastSuccess` to `notifyThemeSetActive`, maintaining `toastSuccess` as an alias for backward compatibility.
- **Formatting:**
- Ensured consistent semicolon usage across all modified TypeScript files.
* refactor(eden-integration): Centralize API hooks in @dockstat/utils/react
Moved all Eden query and mutation hooks, including `useEdenQuery`, `useEdenMutation`, `useEdenRouteMutation`, and their associated types and helpers, from `apps/dockstat/src/hooks` to `packages/utils/src/react/eden`.
Key changes include:
- Consolidating the previous `useEdenMutation` and `useEdenRouteMutation` into a single, overloaded `eden.useEdenMutation` hook within the utility package, which now handles both direct routes and route builders.
- The `edenQuery` alias for `useEdenQuery` has also been moved into the utility package.
- All consuming files within `apps/dockstat` have been updated to import `eden` from `@dockstat/utils/react` and use the new namespaced API (e.g., `eden.useEdenMutation`, `eden.useEdenQuery`).
- Introduced a new `handleEdenMutation` utility function to centralize error extraction and logical response validation logic for mutations.
This refactoring aims to improve code reusability, consistency, and maintainability of the application's API integration layer.
* chore(ci): Lint [skip ci]
---------
Signed-off-by: ItsNik <info@itsnik.de>
Co-authored-by: actions-user <its4nik@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.