Skip to content

A powerful JavaScript library for parsing JSON fault tree descriptions and rendering them as interactive SVG graphics with customizable themes.

License

Notifications You must be signed in to change notification settings

squ/js-fault-tree-analyzer

Repository files navigation

JavaScript Fault Tree Analyzer

A powerful JavaScript library for parsing JSON fault tree descriptions and rendering them as interactive SVG graphics with customizable themes. Perfect for React, Vue, and vanilla JavaScript applications.

Features

  • 🌳 JSON-based fault tree definitions with hierarchical structure
  • 🎨 Multiple color themes (Light, Dark, High Contrast, Ocean)
  • 📊 SVG rendering with precise geometric calculations
  • 🚨 Status-based color coding and blinking animations for critical nodes
  • ⚛️ React components with hooks for easy integration
  • đź–– Vue 2/3 components with composables
  • 📱 Responsive design with proper scaling
  • 🎯 TypeScript support with full type definitions
  • đź”§ Configurable animations controlled by CSS classes

Ocean Theme Example

Installation

npm install js-fault-tree-analyzer

Quick Start

Vanilla JavaScript

import { FaultTreeAnalyzer } from 'js-fault-tree-analyzer';
import 'js-fault-tree-analyzer/dist/styles.css';

const faultTreeData = {
  id: "top-gate",
  label: "System Failure",
  type: "GATE",
  gateType: "OR",
  status: "CRITICAL",
  children: [
    {
      id: "event-1",
      label: "Component A Failure",
      type: "EVENT",
      eventType: "BASIC",
      status: "DEGRADED",
      probability: 0.05
    }
  ]
};

// Render fault tree
const svg = FaultTreeAnalyzer.parseAndRender(faultTreeData, 'light');
document.getElementById('container').innerHTML = svg;

React

import React from 'react';
import FaultTreeDiagram, { useFaultTreeThemes, useFaultTreeBlinking } from 'js-fault-tree-analyzer/react';
import 'js-fault-tree-analyzer/dist/styles.css';

function FaultTreeApp() {
  const { currentTheme, availableThemes, changeTheme } = useFaultTreeThemes();
  const { isBlinking, toggleBlinking } = useFaultTreeBlinking();

  const faultTreeData = {
    id: "top-gate",
    label: "System Failure",
    type: "GATE",
    gateType: "OR",
    status: "CRITICAL",
    children: [
      // ... your fault tree data
    ]
  };

  return (
    <div>
      <div style={{ marginBottom: '20px' }}>
        <select value={currentTheme} onChange={(e) => changeTheme(e.target.value)}>
          {availableThemes.map(theme => (
            <option key={theme.key} value={theme.key}>{theme.name}</option>
          ))}
        </select>
        <label>
          <input
            type="checkbox"
            checked={isBlinking}
            onChange={toggleBlinking}
          />
          Enable blinking for critical nodes
        </label>
      </div>

      <FaultTreeDiagram
        data={faultTreeData}
        theme={currentTheme}
        enableBlinking={isBlinking}
        onError={(error) => console.error('Fault tree error:', error)}
        onRender={(svg) => console.log('Fault tree rendered')}
      />
    </div>
  );
}

Vue 3

<template>
  <div>
    <div style="margin-bottom: 20px;">
      <select v-model="currentTheme">
        <option v-for="theme in availableThemes" :key="theme.key" :value="theme.key">
          {{ theme.name }}
        </option>
      </select>
      <label>
        <input type="checkbox" v-model="isBlinking" />
        Enable blinking for critical nodes
      </label>
    </div>

    <FaultTreeDiagram
      :data="faultTreeData"
      :theme="currentTheme"
      :enableBlinking="isBlinking"
      @error="handleError"
      @render="handleRender"
    />
  </div>
</template>

<script setup>
import { FaultTreeDiagram, useFaultTreeThemes, useFaultTreeBlinking } from 'js-fault-tree-analyzer/vue';
import 'js-fault-tree-analyzer/dist/styles.css';

const { currentTheme, availableThemes, changeTheme } = useFaultTreeThemes();
const { isBlinking, toggleBlinking } = useFaultTreeBlinking();

const faultTreeData = {
  id: "top-gate",
  label: "System Failure",
  type: "GATE",
  gateType: "OR",
  status: "CRITICAL",
  children: [
    // ... your fault tree data
  ]
};

const handleError = (error) => {
  console.error('Fault tree error:', error);
};

const handleRender = (svg) => {
  console.log('Fault tree rendered');
};
</script>

JSON Schema

Fault Tree Node Structure

interface FaultTreeNode {
  id: string;                    // Unique identifier
  label: string;                 // Display label
  type: "GATE" | "EVENT";       // Node type
  gateType?: "OR" | "AND" | "VOTE";  // Gate type (for gates)
  eventType?: "BASIC" | "EXTERNAL" | "UNDEVELOPED" | "HOUSE";  // Event type (for events)
  status?: "NORMAL" | "DEGRADED" | "CRITICAL";  // Status for color coding
  probability?: number;          // Failure probability (0-1)
  riskScore?: number;           // Risk assessment score
  children?: FaultTreeNode[];   // Child nodes
  metadata?: Record<string, any>; // Additional data
}

Example Fault Tree

{
  "id": "system-failure",
  "label": "Aircraft Engine Failure",
  "type": "GATE",
  "gateType": "OR",
  "status": "CRITICAL",
  "probability": 0.15,
  "riskScore": 8.5,
  "children": [
    {
      "id": "fuel-system",
      "label": "Fuel System Failure",
      "type": "GATE",
      "gateType": "AND",
      "status": "DEGRADED",
      "children": [
        {
          "id": "fuel-pump",
          "label": "Fuel Pump Failure",
          "type": "EVENT",
          "eventType": "BASIC",
          "status": "NORMAL",
          "probability": 0.02
        },
        {
          "id": "fuel-line",
          "label": "Fuel Line Blockage",
          "type": "EVENT",
          "eventType": "BASIC",
          "status": "DEGRADED",
          "probability": 0.01
        }
      ]
    },
    {
      "id": "mechanical",
      "label": "Mechanical Failure",
      "type": "EVENT",
      "eventType": "UNDEVELOPED",
      "status": "CRITICAL",
      "probability": 0.05
    }
  ]
}

Available Themes

  • light: Clean, traditional appearance with light backgrounds
  • dark: Modern dark mode with contrasting colors
  • highContrast: Maximum accessibility with bold, distinct colors
  • ocean: Professional blue-based theme

API Reference

Core Classes

FaultTreeAnalyzer

// Parse JSON data into internal structure
const parsed = FaultTreeAnalyzer.parse(jsonData);

// Render parsed data as SVG with theme
const svg = FaultTreeAnalyzer.render(parsed, 'dark');

// Parse and render in one step
const svg = FaultTreeAnalyzer.parseAndRender(jsonData, 'light');

// Get available themes
const themes = FaultTreeAnalyzer.getAvailableThemes();

React Hooks

useFaultTreeThemes()

const {
  currentTheme,      // Current theme name
  availableThemes,   // Array of {key, name} objects
  changeTheme,       // Function to change theme
  setTheme          // Direct setter for theme
} = useFaultTreeThemes();

useFaultTreeBlinking(initialState = true)

const {
  isBlinking,        // Current blinking state
  toggleBlinking,    // Toggle function
  enableBlinking,    // Enable blinking
  disableBlinking,   // Disable blinking
  setBlinking       // Direct setter
} = useFaultTreeBlinking();

Vue Composables

useFaultTreeThemes() (Vue 3)

const {
  currentTheme,      // Ref<string>
  availableThemes,   // ComputedRef<ThemeInfo[]>
  changeTheme,       // Function to change theme
  setTheme          // Direct setter
} = useFaultTreeThemes();

Styling and Customization

CSS Classes

The library uses these CSS classes for styling:

  • .fault-tree-container - Main container
  • .fault-tree-blink - Applied to enable blinking
  • .status-normal - Normal status elements
  • .status-degraded - Degraded status elements
  • .status-critical - Critical status elements
  • .label-box - Label background boxes
  • .quantity-box - Probability/risk score boxes
  • .symbol - Fault tree symbols (gates, events)

Custom Blinking Animation

.fault-tree-blink .status-critical {
  animation: blink 1.5s infinite;
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.3; }
  100% { opacity: 1; }
}

Custom Themes

You can access and modify the built-in themes:

import { COLOR_THEMES } from 'js-fault-tree-analyzer';

// Create custom theme
const customTheme = {
  ...COLOR_THEMES.light,
  name: "Custom Theme",
  background: "#f5f5f5",
  labelBox: {
    normal: "#e8f5e8",
    degraded: "#fff3cd",
    critical: "#f8d7da"
  }
  // ... other theme properties
};

Browser Support

  • Modern browsers supporting SVG and ES6 classes
  • Chrome 60+
  • Firefox 60+
  • Safari 12+
  • Edge 79+

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

Apache License 2.0 - see LICENSE file for details.

Changelog

See CHANGELOG.md for release history.

About

A powerful JavaScript library for parsing JSON fault tree descriptions and rendering them as interactive SVG graphics with customizable themes.

Resources

License

Stars

Watchers

Forks

Packages

No packages published