### SDK Initialization Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Demonstrates how to initialize the Netdata Charts SDK. This is a common starting point for using the SDK. ```javascript import { makeSDK } from "@netdata/charts"; const sdk = makeSDK({ // SDK initialization options }); ``` -------------------------------- ### Chart Rendering Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Demonstrates how to render a chart node. This typically involves getting the chart's UI configuration and then rendering it. ```javascript const chart = sdk.getChart("my-chart"); const uiConfig = chart.getUI(); // Assuming a rendering context or library is available renderChart(uiConfig, document.getElementById("chart-container")); ``` -------------------------------- ### SDK Initialization and Usage Example Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/SDK.md This example demonstrates how to initialize the Netdata Charts SDK, create a chart, add it to the root, and interact with it using SDK methods. ```APIDOC ## Example Usage ```javascript import makeSDK from "@netdata/charts/sdk" import dygraph from "@netdata/charts/chartLibraries/dygraph" import hover from "@netdata/charts/sdk/plugins/hover" import pan from "@netdata/charts/sdk/plugins/pan" const sdk = makeSDK({ ui: { dygraph }, plugins: { hover, pan }, attributes: { chartLibrary: "dygraph", theme: "default", after: -15 * 60, // last 15 minutes }, on: { nodeAdded: (node) => console.log("Node created:", node.getId()), }, }) // Create a chart const chart = sdk.makeChart({ attributes: { id: "system.cpu", title: "CPU Usage", chartLibrary: "dygraph", }, }) // Add to root sdk.appendChild(chart) // Find and interact const found = sdk.getNode({ id: "system.cpu" }) found.focus() ``` ``` -------------------------------- ### Plugin Example Implementation Source: https://github.com/netdata/charts/blob/main/_autodocs/types.md An example of how to implement a plugin. It registers an event listener and provides a cleanup function to remove it. ```javascript const myPlugin = (sdk) => { const remove = sdk.on("nodeAdded", (node) => { console.log("Node added:", node.getId()) }) return () => { remove() // cleanup } } ``` -------------------------------- ### Navigation Guide for Netdata Charts SDK Source: https://github.com/netdata/charts/blob/main/_autodocs/00_START_HERE.md This snippet outlines the recommended navigation path through the Netdata Charts SDK documentation, starting from the README and progressing to specific API modules and configuration files. ```markdown README.md ← Start here (overview) INDEX.md ← Complete navigation index REFERENCE.md ← Quick start and common operations api-reference/ ├── SDK.md ← Main entry point: makeSDK() ├── Chart.md ← Charts: create, fetch, navigate ├── Container.md ← Containers: organize charts ├── Node.md ← Base: attributes, events, tree ├── Dimension.md ← Data series properties ├── Plugins.md ← Extend behavior (8 built-in) ├── DataFetching.md ← Fetch from API └── Helpers.md ← Utility functions configuration.md ← 120+ attributes reference types.md ← Type definitions ``` -------------------------------- ### Start Storybook Development Server Source: https://github.com/netdata/charts/blob/main/AGENTS.md Run this command to start the Storybook development server for interactive component development and documentation. ```bash yarn storybook ``` -------------------------------- ### Custom Plugin Creation Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Provides a conceptual example of how to create a custom plugin for the SDK. Custom plugins extend the SDK's capabilities. ```javascript class MyCustomPlugin { constructor(sdk) { this.sdk = sdk; } init() { console.log("MyCustomPlugin initialized"); // Register event listeners or add custom methods } destroy() { console.log("MyCustomPlugin destroyed"); // Clean up resources } } // Register the plugin sdk.registerPlugin(MyCustomPlugin); ``` -------------------------------- ### Install Netdata Charts with npm Source: https://github.com/netdata/charts/blob/main/README.md Installs the @netdata/charts package using npm. Ensure you have npm installed and configured. ```shell $ npm install @netdata/charts ``` -------------------------------- ### Container Example Usage Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Container.md This example demonstrates how to create root and sub-containers, add charts to them, listen for events, and manage children using the Netdata Charts SDK. ```APIDOC ## Example ```javascript import makeSDK from "@netdata/charts" const sdk = makeSDK({ /* config */ }) // Create root container const root = sdk.getRoot() // Create sub-container for system metrics const systemContainer = sdk.makeContainer({ attributes: { id: "system", title: "System", theme: "default", }, }) root.appendChild(systemContainer) // Create charts in container for (const metric of ["cpu", "memory", "disk"]) { const chart = sdk.makeChart({ attributes: { id: metric, title: metric.toUpperCase(), }, }) systemContainer.appendChild(chart) } // Find charts const cpuChart = systemContainer.getNode({ id: "cpu" }) const allCharts = systemContainer.getNodes({ type: "chart" }) // Listen for additions systemContainer.on("chartAdded", (chart) => { console.log("Chart added:", chart.getId()) }) // Get children const children = systemContainer.getChildren() children.forEach(chart => chart.activate()) // Color consistency const getColor = () => ["#FF6B6B", "#4ECDC4", "#45B7D1"][Math.random() * 3 | 0] const color = systemContainer.getNextColor( getColor, "dimensions", "cpu_user" ) // same color on all charts with "cpu_user" dimension // Cleanup systemContainer.destroy() ``` ``` -------------------------------- ### Start Development Server Source: https://github.com/netdata/charts/blob/main/README.md Starts the development server for the Netdata charts project. This command is typically used during development to preview changes. ```shell $ yarn start ``` -------------------------------- ### Install Netdata Charts with yarn Source: https://github.com/netdata/charts/blob/main/README.md Installs the @netdata/charts package using yarn. Ensure you have yarn installed and configured. ```shell $ yarn add @netdata/charts ``` -------------------------------- ### Registering a Plugin Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Demonstrates how to register a custom plugin with the SDK. Plugins extend the SDK's functionality. ```javascript sdk.registerPlugin({ name: "my-custom-plugin", // ... plugin implementation }); ``` -------------------------------- ### Attribute Management Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Demonstrates how to get and set attributes on a node. Attributes control various aspects of a node's behavior and appearance. ```javascript const node = sdk.getNode("some-node-id"); const currentValue = node.getAttribute("someAttribute"); node.setAttribute("someAttribute", "newValue"); // Listen for attribute changes node.onAttributeChange("someAttribute", (newValue) => { console.log("Attribute changed to:", newValue); }); ``` -------------------------------- ### Plugin Factory Example Source: https://github.com/netdata/charts/blob/main/_autodocs/types.md An example of a plugin factory function that sets up and tears down plugin logic. ```javascript const plugin = (sdk) => { // setup return () => { // cleanup } } ``` -------------------------------- ### ChartLibraryFactory Example Implementation Source: https://github.com/netdata/charts/blob/main/_autodocs/types.md An example implementation of a chart library factory using dygraphs. It includes methods for mounting, rendering, unmounting, and handling UI events. ```javascript const dygraphLibrary = (sdk, chart) => { const element = document.createElement("div") return { mount: (container) => { container.appendChild(element) // init dygraph... }, render: () => { // redraw dygraph... }, unmount: () => { // cleanup dygraph... }, trigger: (event, ...args) => { // handle UI events... }, on: (event, handler) => { // return unregister function }, } } ``` -------------------------------- ### Agent API GET Request Example Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/DataFetching.md Example of a GET request to the Netdata Agent API to fetch chart data. ```http GET http://localhost:19999/api/v1/data?chart=system.cpu&after=-3600&before=0&format=json ``` -------------------------------- ### Start Keyboard Listener with initKeyboardListener() Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Helpers.md Call initKeyboardListener() to begin tracking keyboard events. ```javascript initKeyboardListener() ``` -------------------------------- ### Chart Data Fetching Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Illustrates how to fetch data for a chart using the SDK's data fetching functions. This example shows the main entry point for data retrieval. ```javascript async function loadChartData(chartId) { try { const data = await sdk.fetchChartData(chartId, { // fetch options }); console.log("Fetched data:", data); } catch (error) { console.error("Failed to fetch data:", error); } } ``` -------------------------------- ### Node Tree Operations Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Illustrates common operations for navigating and managing the node tree, such as getting parents, ancestors, or matching nodes. ```javascript const node = sdk.getNode("some-node-id"); const parent = node.getParent(); const root = node.getAncestor(0); const matchingNodes = sdk.getNodes({ type: "chart" }); ``` -------------------------------- ### Event Handling Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Shows how to subscribe to and trigger events within the SDK. This is crucial for reactive updates and inter-component communication. ```javascript const chart = sdk.createChart({...}); chart.on("data-updated", (payload) => { console.log("Chart data updated:", payload); }); sdk.trigger("custom-event", { data: "some value" }); ``` -------------------------------- ### Full Event Bus Example Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Helpers.md Demonstrates the creation and usage of an event bus, including registering listeners with `on` and `once`, triggering events, and observing the behavior of one-time listeners. ```javascript const bus = makeListeners() bus.on("save", (data) => console.log("Saved:", data)) bus.once("ready", () => console.log("Ready!")) bus.trigger("ready") // prints "Ready!" bus.trigger("ready") // no output (once only) bus.trigger("save", {}) // prints "Saved: {}" ``` -------------------------------- ### Quick Start: Initialize SDK and Create a Chart Source: https://github.com/netdata/charts/blob/main/_autodocs/REFERENCE.md Demonstrates how to initialize the Netdata Charts SDK with plugins and attributes, create a new chart, append it to the DOM, and enable data fetching and interaction. ```javascript import makeSDK from "@netdata/charts" import dygraph from "@netdata/charts/chartLibraries/dygraph" import hover from "@netdata/charts/sdk/plugins/hover" import pan from "@netdata/charts/sdk/plugins/pan" // Create SDK with plugins const sdk = makeSDK({ ui: { dygraph }, plugins: { hover, pan }, attributes: { chartLibrary: "dygraph", after: -900, // last 15 minutes }, }) // Create a chart const chart = sdk.makeChart({ attributes: { id: "system.cpu", title: "CPU Usage", }, }) // Add to root sdk.appendChild(chart) // Enable data fetching chart.updateAttribute("autofetch", true) chart.activate() chart.startAutofetch() // Interact chart.focus() chart.moveX(-3600) // show last hour ``` -------------------------------- ### Event Handler Example Source: https://github.com/netdata/charts/blob/main/_autodocs/types.md Example of using an event handler to log when a node is added. It receives node information and the event name. ```javascript sdk.on("nodeAdded", (container, node, "nodeAdded") => { console.log("Node added:", node.getId()) }) ``` -------------------------------- ### Chart Creation Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Shows how to create a new chart node using the SDK. This involves using the SDK's chart creation methods. ```javascript const chart = sdk.createChart({ id: "my-chart", title: "My Awesome Chart", type: "line", // ... other chart options }); ``` -------------------------------- ### Fetching Agent Data Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Demonstrates how to fetch data directly from a Netdata agent. This is typically used for real-time monitoring data. ```javascript async function loadAgentData(agentUrl, chartId) { try { const data = await sdk.fetchAgentData(agentUrl, chartId, { // fetch options }); console.log("Agent data:", data); } catch (error) { console.error("Failed to fetch agent data:", error); } } ``` -------------------------------- ### Initialize Netdata Charts SDK and Create a Chart Source: https://github.com/netdata/charts/blob/main/_autodocs/README.md This example demonstrates how to initialize the Netdata Charts SDK with specified UI, plugins, and attributes, then create and activate a new chart. Ensure necessary plugins like hover, pan, and move are imported. ```javascript import makeSDK from "@netdata/charts" import dygraph from "@netdata/charts/chartLibraries/dygraph" const sdk = makeSDK({ ui: { dygraph }, plugins: { hover, pan, move }, attributes: { chartLibrary: "dygraph", after: -900 }, }) const chart = sdk.makeChart({ attributes: { id: "system.cpu", title: "CPU Usage" }, }) sdk.appendChild(chart) chart.activate() chart.startAutofetch() ``` -------------------------------- ### Cloud API POST Request Example Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/DataFetching.md Example of a POST request to the Netdata Cloud API for querying data. ```http POST https://api.netdata.cloud/api/v2/query Authorization: Bearer eyJhbGc... Content-Type: application/json { "queries": [ { "query": "average(rate(system_cpu_usage[1m]))", "labels": ["timestamp", "cpu"], "after": 1687123000, "before": 1687126456 } ] } ``` -------------------------------- ### Attribute Flow Example Source: https://github.com/netdata/charts/blob/main/_autodocs/REFERENCE.md Demonstrates how attribute changes propagate through the system, from updating an attribute to triggering listeners and plugins. ```mermaid graph TD chart.updateAttribute("after", -3600) call chart.updateAttribute chart.updateAttribute --> Trigger listeners Trigger listeners --> SDK pristine tracking SDK pristine tracking --> chart.onAttributeChange("after", handler) chart.onAttributeChange("after", handler) --> Plugin reacts (moveX) Plugin reacts (moveX) --> New data fetch ``` -------------------------------- ### Node API Usage Example Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Node.md Demonstrates the creation of a node, listening for attribute changes, updating attributes, batch updates, time navigation, pause reason management, hierarchy traversal, and node destruction. ```javascript // Create a node const node = makeNode({ sdk, attributes: { id: "my-chart", title: "CPU Usage", theme: "default", }, }) // Listen for title changes node.onAttributeChange("title", (newTitle) => { console.log("Title:", newTitle) }) // Update attribute (fires listener) node.updateAttribute("title", "Memory Usage") // Batch updates node.updateAttributes({ theme: "dark", focused: true, }) // Navigate time node.moveX(-3600) // last hour node.zoomIn() // Pause for sync operations node.addPauseReason("compare-mode") node.removePauseReason("compare-mode") // Find in hierarchy const root = node.getAncestor({ type: "root" }) // Cleanup node.destroy() ``` -------------------------------- ### Time Formatting Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Shows how to format timestamps according to locale-specific conventions. This is useful for displaying time data in a user-friendly way. ```javascript const node = sdk.getNode("some-node-id"); const timestamp = Date.now(); const formattedDate = node.formatDate(timestamp); const formattedTime = node.formatTime(timestamp); const formattedXAxis = node.formatXAxis(timestamp); ``` -------------------------------- ### Create and Display a Basic Chart with Netdata Charts SDK Source: https://github.com/netdata/charts/blob/main/_autodocs/00_START_HERE.md This snippet demonstrates the essential steps to initialize the SDK, create a chart, and make it visible on the page. It includes activating data fetching and starting automatic data updates. ```javascript import makeSDK from "@netdata/charts" import dygraph from "@netdata/charts/chartLibraries/dygraph" // Create SDK const sdk = makeSDK({ ui: { dygraph }, plugins: { hover, pan, move }, attributes: { chartLibrary: "dygraph", after: -900 }, }) // Create chart const chart = sdk.makeChart({ attributes: { id: "system.cpu", title: "CPU Usage" }, }) // Add to page sdk.appendChild(chart) // Fetch data chart.activate() chart.startAutofetch() ``` -------------------------------- ### Fetching Cloud Data Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Illustrates how to fetch data from Netdata Cloud. This is used for accessing historical or aggregated data from the cloud platform. ```javascript async function loadCloudData(cloudChartId) { try { const data = await sdk.fetchCloudData(cloudChartId, { // fetch options }); console.log("Cloud data:", data); } catch (error) { console.error("Failed to fetch cloud data:", error); } } ``` -------------------------------- ### Configuration Attributes Reference Source: https://github.com/netdata/charts/blob/main/_autodocs/README.md A comprehensive reference to over 120 configuration attributes, organized by category with defaults, types, descriptions, and examples. ```APIDOC ## Configuration Attributes Reference ### Description Provides a complete reference for 120+ configuration attributes, categorized for clarity. Includes default values, data types, detailed descriptions, and usage examples. ### Method N/A (Reference documentation) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript // Example of using a configuration attribute const chart = new Chart({ title: 'My Chart', theme: 'dark', // ... other attributes }); ``` ### Response N/A (Reference documentation) #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### Netdata SDK Chart Creation and Data Fetching Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/DataFetching.md Example demonstrating how to use the Netdata SDK to create a chart, fetch data, and set up automatic updates. Requires @netdata/charts package and a UI like dygraphs. ```javascript import makeSDK from "@netdata/charts" import { fetchChartData } from "@netdata/charts/sdk/makeChart/api" const sdk = makeSDK({ ui: { dygraph }, }) // Create chart const chart = sdk.makeChart({ attributes: { id: "system.cpu", agent: true, autofetch: true, updateEvery: 1, after: -3600, // last hour before: 0, }, }) // Fetch once try { const data = await fetchChartData(chart) console.log("Data points:", data.data.length) console.log("Dimensions:", data.labels) } catch (error) { console.error("Fetch failed:", error) } // Autofetch setup chart.startAutofetch() // Listen for updates chart.onAttributeChange("updatedAt", () => { console.log("Data updated") }) // Listen for errors chart.onAttributeChange("error", (error) => { if (error) console.error("Error:", error) }) // Cleanup chart.stopAutofetch() chart.destroy() ``` -------------------------------- ### Plugin Pattern Best Practices Example Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Plugins.md Implement a logging plugin following best practices: saving unregister functions, cleaning up listeners, and using attribute updates instead of direct data modification. ```javascript const logPlugin = (sdk) => { const unsubscribers = [] // Log all chart creations unsubscribers.push( sdk.on("chartAdded", (container, chart) => { console.log("Chart added:", chart.getAttribute("title")) }) ) // Log all attribute changes unsubscribers.push( sdk.on("nodeAdded", (container, node) => { node.on("focused", (focused) => { console.log(`${node.getId()}: focused=${focused}`) }) }) ) // Cleanup return () => { unsubscribers.forEach(unsub => unsub()) } } sdk.register("log", logPlugin) ``` -------------------------------- ### Time Navigation Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Demonstrates how to manipulate the time window for charts, such as zooming or moving the view. This is essential for exploring time-series data. ```javascript const chart = sdk.getChart("my-chart"); // Zoom in by 10% chart.zoomIn(0.1); // Move the view forward by one hour chart.moveX(60 * 60 * 1000); // milliseconds ``` -------------------------------- ### Example Usage of Netdata Chart Helpers Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Helpers.md Demonstrates the usage of various helper functions including event management with `makeListeners`, debounced rendering with `makeExecuteLatest`, and nested attribute manipulation with `getValue` and `setValue`. ```javascript import makeListeners from "@netdata/charts/helpers/makeListeners" import makeExecuteLatest from "@netdata/charts/helpers/makeExecuteLatest" import { getValue, setValue } from "@netdata/charts/helpers/crud" // Event system const events = makeListeners() events.on("update", (value) => console.log(value)) events.trigger("update", 42) // Debounced rendering const executor = makeExecuteLatest() const render = executor.add(() => chart.render()) window.addEventListener("resize", render) // Nested attributes const config = {} setValue("ui.theme.dark", "#282C34", config) console.log(getValue("ui.theme.dark", "default", config)) // Cleanup executor.clear() events.offAll() ``` -------------------------------- ### Data Flow Example Source: https://github.com/netdata/charts/blob/main/_autodocs/REFERENCE.md Illustrates the sequence of events from a user action to chart updates, including event triggering and plugin routing. ```mermaid graph TD User_Action__click,_drag_ call User_Action User_Action --> Chart_Library Chart_Library --> UI_Event UI_Event --> chartUI.trigger("event", args) chartUI.trigger("event", args) --> Chart.on("event") listeners Chart.on("event") listeners --> SDK.trigger() for sync SDK.trigger() for sync --> Plugins route events Plugins route events --> Other charts updated ``` -------------------------------- ### Create and Interact with a Chart Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Demonstrates creating a chart, activating it, starting autofetch, listening for attribute changes, converting values, navigating time, and cleaning up. ```javascript const chart = sdk.makeChart({ attributes: { id: "cpu", title: "CPU Time", chartLibrary: "dygraph", autofetch: true, after: -900, // last 15 mins }, }) chart.activate() chart.startAutofetch() // Listen for attribute changes chart.onAttributeChange("focused", (isFocused) => { console.log("Chart focused:", isFocused) }) // Format values const val = chart.getConvertedValue(2048, { fractionDigits: 1 }) console.log(val) // "2.0 KiB" // Navigate chart.moveX(-3600) // last hour chart.zoomIn() // Cleanup chart.destroy() ``` -------------------------------- ### Build Distributions with Yarn Source: https://github.com/netdata/charts/blob/main/AGENTS.md Use these commands to build different distributions of the @netdata/charts package. Ensure you have Yarn installed and the project dependencies are set up. ```bash yarn build # Build CommonJS distribution yarn build:cjs # Build ES6 distribution yarn build:es6 ``` -------------------------------- ### Initialize Keyboard Listener with makeKeyboardListener Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Helpers.md Use makeKeyboardListener to track currently pressed keys. Initialize the listener to start capturing keyboard events. ```javascript import makeKeyboardListener from "@netdata/charts/helpers/makeKeyboardListener" const { onKeyChange, initKeyboardListener, clearKeyboardListener } = makeKeyboardListener() ``` -------------------------------- ### SDK Navigation Methods Source: https://github.com/netdata/charts/blob/main/_autodocs/INDEX.md Methods for navigating the chart hierarchy, including getting the root, nodes, and managing child nodes. ```javascript getRoot() → Container getNode(attrs, opts) → Node getNodes(attrs, opts) → Node[] appendChild(node, opts) → void removeChild(id) → void ``` -------------------------------- ### Initialize SDK with Configuration Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/SDK.md Use this snippet to create the root SDK instance. Provide configuration for UI libraries, plugins, and default attributes. ```javascript import makeSDK from "@netdata/charts/sdk" const sdk = makeSDK({ ui, plugins, attributes, on, }) ``` -------------------------------- ### Built-in Plugin Usage Example (Hover) Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Illustrates the usage of a built-in plugin, specifically the 'hover' plugin for synchronizing hover states across charts. ```javascript // The 'hover' plugin is typically enabled by default or registered via SDK options. // Its functionality is often integrated into chart interactions. ``` -------------------------------- ### Get Current X-Axis Date Window Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves the current start and end timestamps displayed on the X-axis, converted to milliseconds. ```javascript const [start, end] = chart.getDateWindow() ``` -------------------------------- ### Dimension Statistics Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Shows how to access statistical properties of a dimension, such as min, max, and average values. These are useful for data analysis. ```javascript const chart = sdk.getChart("my-chart"); const dimension = chart.getDimension("my-dimension-id"); console.log("Min:", dimension.min); console.log("Max:", dimension.max); console.log("Average:", dimension.avg); ``` -------------------------------- ### Adding a Child Node Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Illustrates how to add a child node to a parent node, typically used for building hierarchical chart structures. ```javascript const parentNode = sdk.getRoot(); const childNode = sdk.createNode({...}); parentNode.appendChild(childNode); ``` -------------------------------- ### DataFetching Module Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Documentation for the data fetching system, including functions for fetching chart and agent data, and examples of HTTP requests and error handling. ```APIDOC ## DataFetching Module ### Description Details the system responsible for fetching data for charts and agents. Documents key functions, explains the agent vs. cloud API, and provides examples for HTTP requests and error handling. ### Functions - `fetchChartData(params)`: Main function to fetch chart data. - `fetchChartWeights(params)`: Fetches weights for chart data. - `fetchAgentData(params)`: Fetches data from an agent. - `fetchAgentWeights(params)`: Fetches weights for agent data. - `fetchCloudData(params)`: Fetches data from the Netdata Cloud API. - `fetchCloudWeights(params)`: Fetches weights for cloud data. - **Helper utilities**: Various utility functions supporting data fetching. ### Agent vs. Cloud API - Explains the differences and use cases for fetching data from local agents versus the Netdata Cloud. ### HTTP Request/Response Examples - Provides examples of typical HTTP requests and their expected responses. ### Error Codes and Handling - Lists common error codes and strategies for handling data fetching errors. ### Integration with Charts - How the data fetching system integrates seamlessly with chart rendering. ### Example ```javascript // Example of fetching chart data (conceptual) async function loadChartData(chartId) { try { const data = await fetchChartData({ chartId: chartId }); // Process data... } catch (error) { console.error('Failed to fetch data:', error); } } ``` ``` -------------------------------- ### Pause Reason Management Example Source: https://github.com/netdata/charts/blob/main/_autodocs/DOCUMENTATION_MANIFEST.txt Demonstrates how to add and remove reasons for pausing chart updates. This can be used to temporarily halt data fetching or rendering. ```javascript const node = sdk.getNode("some-node-id"); node.addPauseReason("user-interaction"); // ... perform some operation ... node.removePauseReason("user-interaction"); ``` -------------------------------- ### makeResizeObserver Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Helpers.md Creates a ResizeObserver to watch for element size changes. It provides methods to start observing, stop observing a specific element, and disconnect all observations. ```APIDOC ## makeResizeObserver ### Description Watches element size changes and provides methods to manage the observation. ### Methods - `observe(element)` — Watch element - `unobserve(element)` — Stop watching element - `disconnect()` — Stop all observations ``` -------------------------------- ### Attribute Change Handler Example Source: https://github.com/netdata/charts/blob/main/_autodocs/types.md Example of using an attribute change handler to log changes to the 'focused' attribute of a chart. ```javascript chart.onAttributeChange("focused", (focused, wasFocused, "focused") => { console.log("Focused changed:", wasFocused, "→", focused) }) ``` -------------------------------- ### Agent API JSON Response Example Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/DataFetching.md Example JSON response structure from the Netdata Agent API for chart data. ```json { "labels": ["X", "user", "system", "guest"], "data": [ [1687123456, 12.5, 8.3, 0.1], [1687123457, 14.2, 9.1, 0.0], ... ], "min": 0, "max": 25, "step": 1, "first_entry": 1687123000, "last_entry": 1687126456, "view_duration": 3456000, "before": 0, "after": -3600, "points": 3456, "format": "json", "result": "200" } ``` -------------------------------- ### Initialize SDK with Plugins Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Plugins.md Register plugins during SDK creation. The order of plugins in the configuration matters as later plugins can access state changes from earlier ones. ```javascript import makeSDK from "@netdata/charts" import hover from "@netdata/charts/sdk/plugins/hover" import pan from "@netdata/charts/sdk/plugins/pan" import move from "@netdata/charts/sdk/plugins/move" const sdk = makeSDK({ ui: { /* ... */ }, plugins: { hover, pan, move, }, }) ``` -------------------------------- ### Get UI Instance Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves a specific UI instance associated with the chart. By default, it fetches the 'default' UI instance. You can specify a custom name to get other UI instances. ```javascript const ui = chart.getUI() const customUI = chart.getUI("custom") ``` -------------------------------- ### Get Chart Root Container Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Use to access the root container node of the chart. ```javascript const root = chart.getRoot() ``` -------------------------------- ### Get Update Interval Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves the configured interval in milliseconds for automatic data fetching. ```javascript const interval = chart.getUpdateEvery() // 1000 ``` -------------------------------- ### Container Color Utility Source: https://github.com/netdata/charts/blob/main/_autodocs/INDEX.md Get the next available color for a given group and ID. ```javascript getNextColor(getNext, groupId, id) → string ``` -------------------------------- ### crud (getValue, setValue) Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Helpers.md Provides utilities for getting and setting values in nested object structures. ```APIDOC ## crud (getValue, setValue) ### Description Utilities for managing nested attributes within an object. ### Functions #### getValue(path, defaultValue, obj) Retrieves a value from a nested object structure using a dot-notation path. - **path** (string) - Required - The dot-notation path to the desired value (e.g., "ui.theme.dark"). - **defaultValue** (any) - Optional - The value to return if the path does not exist. - **obj** (object) - Required - The object to retrieve the value from. #### setValue(path, value, obj) Sets a value in a nested object structure using a dot-notation path. Creates nested objects if they do not exist. - **path** (string) - Required - The dot-notation path to set the value at (e.g., "ui.theme.dark"). - **value** (any) - Required - The value to set. - **obj** (object) - Required - The object to set the value in. ### Example ```javascript import { getValue, setValue } from "@netdata/charts/helpers/crud" const config = {} setValue("ui.theme.dark", "#282C34", config) console.log(getValue("ui.theme.dark", "default", config)) // Output: "#282C34" console.log(getValue("ui.font.size", 12, config)) // Output: 12 ``` ``` -------------------------------- ### Build Static Storybook Source: https://github.com/netdata/charts/blob/main/AGENTS.md Execute this command to generate a static build of your Storybook documentation. ```bash yarn build-storybook ``` -------------------------------- ### Get Unit String Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves the unit of measurement used for the chart's values, such as 'KiB/s'. ```javascript const units = chart.getUnits() // "KiB/s" ``` -------------------------------- ### Registering a Custom Plugin Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Plugins.md Demonstrates how to create and register a custom plugin with the SDK. Plugins are factories that receive the SDK instance and return a cleanup function. ```javascript const myPlugin = (sdk) => { // Setup sdk.on("nodeAdded", (node) => { console.log("Node added:", node.getId()) }) // Return cleanup function return () => { // Teardown } } sdk.register("myPlugin", myPlugin) ``` -------------------------------- ### Get Dimension Unit Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Dimension.md Access the unit of measurement for the dimension's values, such as '%', 'KiB', or 'requests/s'. ```javascript const units = dimension.unit ``` -------------------------------- ### Get Theme-Aware Attribute Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves the value of a theme-specific attribute, such as colors or styles, based on the current theme. ```javascript const color = chart.getThemeAttribute("themeGridColor") // Returns array[themeIndex] or string ``` -------------------------------- ### Node Attribute Management Source: https://github.com/netdata/charts/blob/main/_autodocs/README.md Methods for managing node attributes, including setting, getting, and deleting attributes. ```APIDOC ## Node Attribute Management ### Description Includes 5 methods for managing node attributes, 5 methods for event listeners, and 4 methods for tree operations. ### Method Methods such as `setAttribute`, `getAttribute`, `addEventListener`, `removeEventListener`. ### Endpoint N/A (Node methods) ### Parameters Parameters are specific to the node method being used. ### Request Example ```javascript // Example: Setting an attribute node.setAttribute('color', 'blue'); // Example: Adding an event listener node.addEventListener('click', handleClick); ``` ### Response Responses are method-dependent. #### Success Response Often a success status or the updated node object. #### Response Example ```json // Example response for getAttribute { "value": "blue" } ``` ``` -------------------------------- ### Get Unit Attributes Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Dimension.md Retrieves conversion settings for a dimension's units. The default key is 'units'. ```javascript const units = dimension.getUnitAttributes("units") // { method: "auto", fractionDigits: 2, divider: 1024, ... } ``` -------------------------------- ### Get Dimension Color Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Dimension.md Retrieve the color associated with the dimension, used for visualization. The format can be hex or RGB. ```javascript const color = dimension.color // "#FF6B6B" ``` -------------------------------- ### Get Dimension Name Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Dimension.md Access the human-readable display name of the dimension. This is typically used for labels in the UI. ```javascript const name = dimension.name // "CPU User Time" ``` -------------------------------- ### Create and Manage Containers and Charts Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Container.md This snippet demonstrates how to create a root container, add sub-containers and charts, find nodes by ID or type, listen for chart addition events, manage children, and ensure consistent coloring for chart dimensions. It also shows how to clean up a container. ```javascript import makeSDK from "@netdata/charts" const sdk = makeSDK({ /* config */ }) // Create root container const root = sdk.getRoot() // Create sub-container for system metrics const systemContainer = sdk.makeContainer({ attributes: { id: "system", title: "System", theme: "default", }, }) root.appendChild(systemContainer) // Create charts in container for (const metric of ["cpu", "memory", "disk"]) { const chart = sdk.makeChart({ attributes: { id: metric, title: metric.toUpperCase(), }, }) systemContainer.appendChild(chart) } // Find charts const cpuChart = systemContainer.getNode({ id: "cpu" }) const allCharts = systemContainer.getNodes({ type: "chart" }) // Listen for additions systemContainer.on("chartAdded", (chart) => { console.log("Chart added:", chart.getId()) }) // Get children const children = systemContainer.getChildren() children.forEach(chart => chart.activate()) // Color consistency const getColor = () => ["#FF6B6B", "#4ECDC4", "#45B7D1"][Math.random() * 3 | 0] const color = systemContainer.getNextColor( getColor, "dimensions", "cpu_user" ) // same color on all charts with "cpu_user" dimension // Cleanup systemContainer.destroy() ``` -------------------------------- ### Create a Node Instance Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Node.md Use the makeNode factory function to create a new Node. Pass an SDK instance, an optional parent node, and initial attributes. ```javascript import makeNode from "@netdata/charts/sdk/makeNode" const node = makeNode({ sdk, parent: null, attributes: { id: "my-node", title: "Data" }, }) ``` -------------------------------- ### Get SDK Version Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/SDK.md Retrieve the current version of the SDK. This is typically stored within the SDK's attributes. ```javascript const version = sdk.version() // "v3" ``` -------------------------------- ### makeSDK Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/SDK.md Initializes the Netdata charts system by creating the root SDK instance. It accepts configuration for UI libraries, plugins, and default attributes, returning an instance with methods for chart and container management. ```APIDOC ## makeSDK ### Description Initializes the Netdata charts system by creating the root SDK instance. It accepts configuration for UI libraries, plugins, and default attributes, returning an instance with methods for chart and container management. ### Function Signature ```javascript import makeSDK from "@netdata/charts/sdk" const sdk = makeSDK({ ui, // object of chart library makers plugins, // object of plugin factories attributes, // default attributes for all nodes on, // object of event listeners to register }) ``` ### Parameters #### ui - **Type**: object - **Required**: true - **Description**: Map of chart library name → maker function. Factories receive `(sdk, chart)` and return UI instance #### plugins - **Type**: object - **Required**: false - **Default**: {} - **Description**: Map of plugin name → factory function. Each receives the SDK instance and returns a cleanup function #### attributes - **Type**: object - **Required**: false - **Default**: {} - **Description**: Default attributes for all nodes. Merged with `initialAttributes` #### on - **Type**: object - **Required**: false - **Default**: {} - **Description**: Map of event name → handler function. Each handler is registered on init ``` -------------------------------- ### Initialize Netdata Charts SDK Source: https://github.com/netdata/charts/blob/main/_autodocs/configuration.md Pass configuration options to the makeSDK() function when initializing the Netdata Charts SDK. This allows customization of UI components, plugins, default attributes, and event handlers. ```javascript import makeSDK from "@netdata/charts" const sdk = makeSDK({ ui: { dygraph, gauge, ... }, plugins: { hover, pan, ... }, attributes: { /* defaults */ }, on: { /* event handlers */ }, }) ``` -------------------------------- ### Enable SDK Plugins for Enhanced Functionality Source: https://github.com/netdata/charts/blob/main/_autodocs/REFERENCE.md Initializes the SDK with various plugins that add features like synchronized navigation, hover effects, and time selection across charts. ```javascript const sdk = makeSDK({ ui: { dygraph }, plugins: { move, hover, pan, highlight, select, selectVertical, play, annotationSync, }, }) ``` -------------------------------- ### Get Applicable Nodes Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves an array of nodes that would be affected by actions on this chart, often used for cross-chart synchronization. ```javascript const nodes = chart.getApplicableNodes({ syncHover: true }) ``` -------------------------------- ### makeChart(options) Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/SDK.md Creates chart UI and attaches it to an existing chart. Requires the SDK instance and the chart node to create UI for. ```APIDOC ## makeChart(options) → Chart ### Description Create chart UI and attach it to an existing chart. ### Parameters - **sdk** (SDK) — SDK instance - **chart** (Chart) — Chart node to create UI for ### Returns UI instance with `render()` and `unmount()` methods ``` -------------------------------- ### Get First Data Point Timestamp Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves the Unix timestamp (in seconds) of the earliest data point available for the chart. ```javascript const ts = chart.getFirstEntry() ``` -------------------------------- ### Get Current Theme Index Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Returns the index of the currently applied theme (e.g., 0 for default, 1 for dark). ```javascript const idx = chart.getThemeIndex() ``` -------------------------------- ### Initialize Netdata Charts SDK and Create a Chart Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/SDK.md This snippet shows how to initialize the Netdata Charts SDK with specific UI components and plugins, create a new chart, append it to the root, and interact with the created node. It includes event handling for node creation. ```javascript import makeSDK from "@netdata/charts/sdk" import dygraph from "@netdata/charts/chartLibraries/dygraph" import hover from "@netdata/charts/sdk/plugins/hover" import pan from "@netdata/charts/sdk/plugins/pan" const sdk = makeSDK({ ui: { dygraph }, plugins: { hover, pan }, attributes: { chartLibrary: "dygraph", theme: "default", after: -15 * 60, // last 15 minutes }, on: { nodeAdded: (node) => console.log("Node created:", node.getId()), }, }) // Create a chart const chart = sdk.makeChart({ attributes: { id: "system.cpu", title: "CPU Usage", chartLibrary: "dygraph", }, }) // Add to root sdk.appendChild(chart) // Find and interact const found = sdk.getNode({ id: "system.cpu" }) found.focus() ``` -------------------------------- ### Get All Node Attributes Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Node.md Retrieve all current attributes of a node as an object using getAttributes(). This provides a snapshot at the time of the call. ```javascript const all = node.getAttributes() ``` -------------------------------- ### Basic HeadlessChart Usage with Render Prop Source: https://github.com/netdata/charts/blob/main/src/components/headlessChart/README.md Demonstrates how to use HeadlessChart with a render prop to access chart data, helpers, and state. Ensure the SDK is initialized and appropriate contextScope and host are provided. ```javascript import HeadlessChart from "@/components/headlessChart" import makeDefaultSDK from "@/makeDefaultSDK" const MyCustomComponent = () => { const sdk = makeDefaultSDK() return ( {({ data, helpers, state, currentRow }) => (
{state.loading &&
Loading...
} {state.empty &&
No data available
} {data.length > 0 && (
Latest value: {currentRow.formattedTime}
{currentRow.dimensions.map(dim => ( {dim.id}: {dim.convertedValue} ))}
)}
)}
) } ``` -------------------------------- ### Listen for Chart and SDK Events Source: https://github.com/netdata/charts/blob/main/_autodocs/REFERENCE.md Demonstrates how to subscribe to various events, including chart rendering, attribute changes, and nodes being added to the SDK. ```javascript // Node events chart.on("render", () => console.log("Rendered")) // Attribute changes chart.onAttributeChange("loading", (loading) => { console.log("Loading:", loading) }) // SDK events sdk.on("nodeAdded", (node) => { console.log("Node added:", node.getId()) }) ``` -------------------------------- ### Node Tree Management Source: https://github.com/netdata/charts/blob/main/_autodocs/INDEX.md Methods for managing the node hierarchy, including setting parents, getting ancestors, and matching nodes. ```javascript setParent(node, opts) → void getParent() → Node getAncestor(attrs) → Node getId() → string match(attrs) → boolean inherit() → void ``` -------------------------------- ### Get Data Point Count Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Dimension.md Retrieve the number of data points included in the dimension's current data window. ```javascript const points = dimension.count ``` -------------------------------- ### SDK Creation Methods Source: https://github.com/netdata/charts/blob/main/_autodocs/INDEX.md Use these methods to create new chart, chart core, chart UI, and container instances. ```javascript makeChart(options) → Chart makeChartCore(options) → Chart makeChartUI(chart) → UIInstance makeContainer(options) → Container ``` -------------------------------- ### Get Dimension ID Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Dimension.md Retrieve the unique identifier for a dimension within a chart. This ID is used to reference the specific metric. ```javascript const id = dimension.id // "cpu_user" ``` -------------------------------- ### SDK Instance Methods Source: https://github.com/netdata/charts/blob/main/_autodocs/types.md The main SDK object for creating, registering, and managing charts and nodes, as well as handling events. ```APIDOC ## SDK Instance Main SDK object returned by `makeSDK()`. ```javascript { // Creation makeChart(opts) → Chart, makeChartCore(opts) → Chart, makeChartUI(chart) → UIInstance, makeContainer(opts) → Container, // Registration register(name, plugin) → void, unregister(name) → void, addUI(type, factory) → void, // Navigation getRoot() → Container, getNode(attrs, opts) → Node | undefined, getNodes(attrs, opts) → Node[], appendChild(node, opts) → void, removeChild(id) → void, // Events on(event, handler) → () => void, once(event, handler) → () => void, off(event, handler) → void, trigger(event, ...args) → void, // Info version() → string, ui: { [name: string]: ChartLibraryFactory }, } ``` ``` -------------------------------- ### UIInstance Methods Source: https://github.com/netdata/charts/blob/main/_autodocs/types.md Methods for rendering and managing the UI of a chart, returned by chart library factories. ```APIDOC ## UIInstance Returned by chart library factories. Renders and manages chart UI. ```javascript { render: () => void, unmount: () => void, // Events trigger: (event, ...args) => void, on: (event, handler) => () => void, // Optional: library-specific methods [key: string]: any, } ``` ``` -------------------------------- ### Get Applied Filters for a Grouping Level Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Use to retrieve an array of filter objects currently applied to a specified grouping level. ```javascript const filters = chart.getFilters("instance") ``` -------------------------------- ### makeChart(options) Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/SDK.md Creates and initializes a new chart with UI. It accepts options for parent container, attributes, data fetching, and analytics tracking. ```APIDOC ## makeChart(options) → Chart ### Description Create and initialize a new chart with UI. ### Parameters - **options.parent** (Node, optional) — Parent container node - **options.attributes** (object, optional) — Chart attributes - **options.getChart** (function, optional) — Data fetcher (defaults to `fetchChartData`) - **options.makeTrack** (function, optional) — Analytics tracking function ### Returns Chart node with UI instances ### Example ```javascript const chart = sdk.makeChart({ parent: containerNode, attributes: { id: "cpu", title: "CPU Usage" }, }) ``` ``` -------------------------------- ### Get Dimension Weight Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Retrieves the weight (importance) of a specific dimension, identified by its ID. This weight can be used for prioritization or display logic. ```javascript const w = chart.getWeight("cpu_user") ``` -------------------------------- ### Plugins.md - Plugin System Source: https://github.com/netdata/charts/blob/main/_autodocs/README.md Information about the plugin system, including built-in plugins, lifecycle management, and how to create custom plugins. ```APIDOC ## Plugin System ### Description Extends the functionality of the Netdata charts library. ### Built-in Plugins - hover, pan, move, highlight, select, selectVertical, play, annotationSync ### Features - Plugin lifecycle and pattern - Creating custom plugins - Event routing ``` -------------------------------- ### Get Hidden Dimensions Source: https://github.com/netdata/charts/blob/main/_autodocs/api-reference/Chart.md Returns an array of all dimensions that are currently hidden. This can be used to manage which data series are shown or hidden from the chart. ```javascript const hidden = chart.getHiddenDimensions() ```