diff --git a/.gitignore b/.gitignore index 35873d9..d85fc1e 100644 --- a/.gitignore +++ b/.gitignore @@ -109,3 +109,6 @@ SETUP_COMPLETE.md # Archive and working directory .wrks/ + +# sync-assets manifest — local artefact written by just sync-assets +assets/.sync-manifest.json diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70e70c8..3b38a23 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -140,8 +140,9 @@ repos: exclude: ^\.woodpecker/ - id: end-of-file-fixer + exclude: ^features/.*/site/public/js/ - id: trailing-whitespace - exclude: \.md$ + exclude: (\.md$|^features/.*/site/public/js/) - id: mixed-line-ending diff --git a/.woodpecker/ci.yml b/.woodpecker/ci.yml index be8aba9..b2a519d 100644 --- a/.woodpecker/ci.yml +++ b/.woodpecker/ci.yml @@ -1,84 +1,51 @@ -# Woodpecker CI Pipeline -# Equivalent to GitHub Actions CI workflow -# Generated by dev-system/ci +# Generated by ore workflow generate — layer: ci-standard +# Source: .ontology/workflow.ncl +# Do not edit manually — regenerate with: ore workflow generate --layer ci-standard when: event: [push, pull_request, manual] - branch: - - main - - develop steps: - # === LINTING === - - lint-rust: + rust-clippy-all: image: rust:latest commands: - - curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to /usr/local/bin - - rustup component add clippy - - cargo fmt --all -- --check - - cargo clippy --all-targets -- -D warnings + - cargo clippy --all-targets --all-features -- -D warnings - lint-bash: - image: koalaman/shellcheck-alpine:stable - commands: - - apk add --no-cache curl bash - - find . -name '*.sh' -type f ! -path './target/*' -exec shellcheck {} + - - lint-nickel: + nickel-typecheck: image: rust:latest commands: - cargo install nickel-lang-cli --locked - - find . -name '*.ncl' -type f ! -path './target/*' -exec nickel typecheck {} \; + - nickel typecheck - lint-nushell: + nushell-check: image: rust:latest commands: - cargo install nu --locked - - find . -name '*.nu' -type f ! -path './target/*' -exec nu --ide-check 100 {} \; + - find . -name '*.nu' ! -path '*/target/*' -print0 | xargs -0 -I\{\} nu --ide-check 100 \{\} - lint-markdown: - image: node:alpine - commands: - - npm install -g markdownlint-cli2 - - markdownlint-cli2 '**/*.md' '#node_modules' '#target' - - # === TESTING === - - test: + nextest-ci: image: rust:latest commands: - - cargo test --workspace --all-features - depends_on: - - lint-rust - - lint-bash - - lint-nickel - - lint-nushell - - lint-markdown + - cargo install cargo-nextest --locked + - cargo nextest run --all-features --workspace --profile ci --cargo-profile ci + depends_on: ["rust-clippy-all", "nickel-typecheck", "nushell-check"] + environment: + RUST_BACKTRACE: 1 - # === BUILD === - - build: - image: rust:latest - commands: - - cargo build --release - depends_on: - - test - - # === SECURITY === - - security-audit: - image: rust:latest - commands: - - cargo install cargo-audit --locked - - cargo audit --deny warnings - depends_on: - - lint-rust - - license-check: + deny-subset: image: rust:latest commands: - cargo install cargo-deny --locked - cargo deny check licenses advisories - depends_on: - - lint-rust + + docs-check: + image: rust:latest + commands: + - RUSTDOCFLAGS="-D rustdoc::broken-intra-doc-links -D rustdoc::private-intra-doc-links" cargo doc --no-deps --workspace --profile ci -q + depends_on: ["rust-clippy-all", "nickel-typecheck", "nushell-check"] + + build-release-native: + image: rust:latest + commands: + - cargo build --release --workspace + depends_on: ["rust-clippy-all", "nickel-typecheck", "nushell-check"] diff --git a/CHANGELOG.md b/CHANGELOG.md index cd4f37b..ca45ffd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **Website templates + generator (2026-05-28)**: Two render-mode project templates and an interactive generator, modelled on the living jpl-website site. + - `templates/website-htmx-ssr/`, `templates/website-leptos/` — sanitized snapshots produced by a reproducible extractor (`scripts/generator/extract-template.nu`): rsync + prune + binary-safe sanitize + seed overlay; neutral `website-*` crate names; deploy identity defaults to `example.com` with a `TEMPLATE-SETUP.md` checklist. Both carry the full workspace (render profile is a build concern: features + cfg + Dockerfile + `rendering.ncl`). + - `scripts/generator/new-site.nu` + `templates/options.ncl` + `just site::new` — interactive (or `--config`/`--yes`) wizard: picks the template via the `templates.json` registry (now carrying `render_mode`), creates the site as a framework sibling, renames crates to the project, sets domain, and stamps ontoref onboarding. Verified: a generated site's full `cargo metadata` resolves ~700 packages via `../rustelo`. + - `scripts/generator/onto-onboard.nu` + `templates/_ontoref-skeleton/` — ontoref onboarding levels (full/minimal/none) that delegate ontology scaffolding to `ontoref setup` and write a `.rustelo.ontoref` domain pointer (reference, not embed). + - `templates/shared/public/scripts/` — htmx-ssr integration glue promoted from jpl-website (`htmx-reinit.js`, `reinit-handlers.js`, `theme-init.js`, `highlight-utils.js`, `tag-filters.js`); the htmx library + extensions already lived under `templates/shared/htmx/`. + - `just site::extract` — re-snapshot both templates from the living model. +- **ADR-006** — Rendering Profile Axis: HTMX-SSR Coexisting with Leptos Hydration. +- **ADR-007** — Website Templates as Reproducible Snapshots + a Generator that Delegates (snapshot model, neutral crate names, delegated ontoref onboarding, self-contained trees superseding init.rs assembly). +### Removed +- Obsolete Leptos-only templates (basic/cms/content-website/enterprise/minimal/website-full) removed from `templates/` and the registry; `just site::new` is the single scaffolding path. A reference copy of the old trees is kept under `.coder/archive/templates/`. +- **Legacy `cargo rustelo init` scaffolding removed** from `rustelo_cli`: deleted `commands/init.rs`, `templates.rs`, `commands/remote.rs`, `embedded.rs`, the `Commands::Init` variant + match arm, and the now-orphaned `generate` feature (+ optional deps tera/quote/syn/proc-macro2). The remaining `cargo rustelo` commands (build/dev/update/assets/pipeline/cross) are unchanged. Verified: `cargo check -p rustelo_cli` and `cargo clippy -p rustelo_cli --no-deps -- -D warnings` both clean. +- Framework landing (`assets/web/src/index.html`) updated to present both render modes (added a "Two Render Modes" card). + +- **Architecture Self-Description (on+re)**: Integrated Ontoref protocol across framework and implementation + - `.ontology/core.ncl` — knowledge graph with axioms (config-driven, language-agnostic, no-framework-forks), tensions, and practices (build-time codegen, custom routing, layered override, plugin architecture, auth framework, component library, page library, feature system, CSS theme system) + - `.ontology/state.ncl` — state dimensions tracking framework-maturity (feature-complete → api-stable), plugin-system (L5 → L8), template-system (designed → operational) + - `.ontology/gate.ncl` — four architecture membranes: routing-integrity (Closed), code-quality (Closed), configuration-driven (Low permeability), framework-boundary (Closed) + - `.ontology/manifest.ncl` — Library manifest with Developer, Downstream, and Agent consumption modes; framework-core, templates, features, and self-description layers + - `reflection/` — backlog, constraints, defaults, qa, schema, and operational modes (integrity-check, sync-ontology, validate-pap) +- **ADR System**: Four Architecture Decision Records in typed Nickel NCL with contract validation + - `adr-001` — Build-Time Code Generation Pattern (`include!(concat!(env!("OUT_DIR"), ...))`) + - `adr-002` — Custom Routing System over Leptos Router + - `adr-003` — Layered Override System (Local > Feature > Template > Framework precedence) + - `adr-004` — Compile-Time Plugin Architecture (Level 5) with documented Level 8 upgrade path + - `adr-005` — Auth Framework as Hexagonal Port over Foundation (`rustelo_auth` re-exports from `rustelo_core_lib::auth`; constraints: consumers-use-port, no-auth-impl-in-framework-crate) +- **on+re migration (2026-04)**: Ontology updated to reflect current codebase state + - `core.ncl` — artifact path `site/config/` corrected to `resources/nickel/routes/`; `auth-framework` description updated to hexagonal port; `unified-template-system` updated (CLI wired) + - `state.ncl` — `template-system` and `framework-maturity` blockers/catalysts updated + ### Fixed - **rustelo_server**: Resolved 302 compilation errors after dependency updates - Removed duplicate module declarations (`auth`, `content`) in lib.rs diff --git a/README.md b/README.md index 4aa3122..9ff51f0 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@
- RUSTELO + RUSTELO
A unified, modern, and secure **Rust** platform to build, deploy, and deliver scalable, high-performance, and reactive web applications with integrated content management, user authentication, multilingual UI, email services, CI/CD pipelines, and comprehensive tooling from development to production.
- RUSTELO + RUSTELO
>[!NOTE] @@ -281,6 +281,26 @@ A unified, modern, and secure **Rust** platform to build, deploy, and deliver sc **New to Rustelo?** Check out our **[Quick Start Guide](QUICK_START.md)** for a complete walkthrough! +### Generate a new website (recommended for new sites) + +Scaffold a fresh website from a render-mode template (snapshot of the reference site): + +```bash +# Interactive — asks project name, render mode, languages, domain, ontoref level +just site::new + +# Non-interactive +just site::new --project acme --render-mode htmx-ssr --domain acme.dev --ontoref minimal --yes +``` + +Render modes: +- `htmx-ssr` — server-rendered HTML + HTMX, no WASM. +- `leptos-hydration` — SSR + WASM hydration. + +The site is created as a sibling of this framework (so its `../rustelo` path deps +resolve), with crates renamed to your project and a `SETUP.md` listing what to complete. +`just site::extract` re-snapshots the templates from the living model. See ADR-007. + ### Option 1: One-Command Setup (Recommended) ```bash # Clone and install everything automatically @@ -563,9 +583,46 @@ rustelo_core_lib::load_resources_from_config()?; ### Documentation -- [Plugin Architecture Guide](../docs/architecture/rustelo-plugin-architecture.md) -- [Plugin Development Guide](./.coder/info/PHASE3-PLUGIN-DEVELOPMENT-GUIDE.md) -- [Example Plugin](../website/website-impl/crates/plugin-example-theme/) +- [Plugin Architecture Guide](./docs/architecture/rustelo-plugin-architecture.md) +- [ADR-004: Plugin Architecture Level 5](./adrs/adr-004-plugin-architecture-level5.ncl) +- [Example Plugin](./examples/plugin-example-theme/) + +## 🔍 Architecture Self-Description (on+re) + +Rustelo is **self-describing** via the [Ontoref](https://github.com/ontoref) `on+re` protocol. The `.ontology/` and `reflection/` directories form a machine- and agent-readable knowledge graph of the framework's architecture, current state, and invariants. + +### What's in `.ontology/` + +| File | Purpose | +|------|---------| +| `core.ncl` | Knowledge graph: axioms, tensions, practices, edges | +| `state.ncl` | State dimensions with current/desired states and transitions | +| `gate.ncl` | Architecture membranes (routing integrity, config-driven gate, framework boundary) | +| `manifest.ncl` | Consumer modes, layer definitions, operational modes | + +### ADR System (`adrs/`) + +Architecture Decision Records in typed NCL with contract validation: + +- `adr-001` — Build-Time Code Generation Pattern +- `adr-002` — Custom Routing over Leptos Router +- `adr-003` — Layered Override System +- `adr-004` — Compile-Time Plugin Architecture (Level 5) with Runtime Upgrade Path + +### How Agents Use This + +An agent reading `.ontology/core.ncl` knows before touching any code: +- Which axioms are invariant (routing integrity, config-driven, no framework forks) +- Which tensions exist and how they're resolved +- Which practices are operative and their artifact paths +- Which gates reject changes without justification + +```bash +# Browse framework architecture +nickel export .ontology/core.ncl +nickel export .ontology/state.ncl # current state vs desired state +nickel export .ontology/gate.ncl # active membranes and protocols +``` ## 🏗️ Project Structure @@ -603,13 +660,17 @@ template/ ## 🚀 Development ### Prerequisites -- Rust 1.75+ -- Node.js 18+ (for frontend tooling) -- PostgreSQL (if using database features) -- **mdBook** (for documentation) - `cargo install mdbook` -- **Just** (task runner) - `cargo install just` +- **Rust 1.75+** - Core language and toolchain +- **Node.js 18+** - Frontend tooling and asset processing +- **Nickel** (Configuration language) - **REQUIRED** for type-safe configuration + - macOS: `brew install nickel` + - Linux/Windows: `cargo install nickel-lang-cli` + - See [Nickel Installation Guide](../docs/guides/nickel-installation.md) +- **PostgreSQL** - Required if using database features (`auth` or `content-db`) +- **mdBook** - Documentation generation - `cargo install mdbook` +- **Just** - Task runner - `cargo install just` -> **Note**: All tools are automatically installed by `./scripts/install.sh`. For manual setup, see [INSTALL.md](INSTALL.md). +> **Note**: Nickel is mandatory for Rustelo projects. All configuration files (routes, themes, menus, content types) use NCL format for type-safety and DRY principles. See [Why Nickel?](../docs/adr/0002-nickel-configuration-language.md) and [Configuration Guide](../docs/guides/nickel-configuration-guide.md). ### Quick Setup ```bash diff --git a/features/content-graph/Cargo.toml b/features/content-graph/Cargo.toml new file mode 100644 index 0000000..0649544 --- /dev/null +++ b/features/content-graph/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "content-graph" +version = "0.1.0" +edition = "2021" + +[workspace] + +[lib] +path = "src/lib.rs" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +glob = "0.3" diff --git a/features/content-graph/feature.toml b/features/content-graph/feature.toml new file mode 100644 index 0000000..6f4a6e1 --- /dev/null +++ b/features/content-graph/feature.toml @@ -0,0 +1,65 @@ +[feature] +name = "content-graph" +version = "0.1.0" +source = "rustelo" +description = "Knowledge graph connecting content items with each other and with on+re ontology nodes. Generates content_graph.json at build time and provides Cytoscape-powered interactive graph views plus SSR-safe RelatedContent and OntologyContext components." +requires = [] + +[dependencies] +workspace = ["serde", "serde_json"] +external = ["glob = '0.3'"] + +[[environment.variables]] +name = "CONTENT_GRAPH_CONTENT_DIR" +default = "site/content" +required = false + +[[environment.variables]] +name = "CONTENT_GRAPH_NICKEL_SCHEMA_DIR" +default = "rustelo/nickel" +required = false + +[[environment.variables]] +name = "CONTENT_GRAPH_FRAMEWORK_ONTOLOGY" +default = "" +required = true + +[[environment.variables]] +name = "CONTENT_GRAPH_IMPL_ONTOLOGY" +default = ".ontology/core.ncl" +required = false + +[[environment.variables]] +name = "CONTENT_GRAPH_FRAMEWORK_ADRS_GLOB" +default = "" +required = true + +[[environment.variables]] +name = "CONTENT_GRAPH_IMPL_ADRS_GLOB" +default = "adrs/adr-*.ncl" +required = false + +[[environment.variables]] +name = "ONTOREF_NICKEL_IMPORT_PATH" +default = "" +required = true + +[configuration] +files = [ + { path = "site/config/assets_content_graph.ncl", template = "templates/assets_ncl_fragment.ncl" }, +] + +[resources] +public = [ + { from = "js/cytoscape-shim.js", to = "public/js/content-graph-shim.js" }, +] + +[node] +scripts = [ + { name = "cytoscape:download", command = "node scripts/download/download-cytoscape.js" }, +] +build_all_hook = "cytoscape:download" + +[[scripts]] +from = "scripts/download/download-cytoscape.js" +to = "scripts/download/download-cytoscape.js" diff --git a/features/content-graph/js/cytoscape-shim.js b/features/content-graph/js/cytoscape-shim.js new file mode 100644 index 0000000..6573c2f --- /dev/null +++ b/features/content-graph/js/cytoscape-shim.js @@ -0,0 +1,262 @@ +/** + * content-graph-shim.js + * + * Thin bridge between Leptos/WASM and Cytoscape.js. + * Exposes window.ContentGraph with a single render() entry point. + * + * Called from GraphView component after mount: + * window.ContentGraph.render(containerId, focusNodeId, theme) + * + * Reads graph data from: + * + * + * Requires (loaded before this script via assets pipeline): + * - cytoscape.min.js + * - cytoscape-cose-bilkent.min.js + */ + +(function () { + 'use strict'; + + // ── Theme tokens ──────────────────────────────────────────────────────────── + + function buildPalette(isDark) { + return { + // Content node variants + contentFill: isDark ? '#3b82f6' : '#2563eb', + // Ontology node variants by level + axiomFill: isDark ? '#8b5cf6' : '#7c3aed', + tensionFill: isDark ? '#f59e0b' : '#d97706', + practiceFill: isDark ? '#10b981' : '#059669', + projectFill: isDark ? '#06b6d4' : '#0891b2', + // ADR + adrFill: isDark ? '#f97316' : '#ea580c', + // Ego node ring + egoStroke: isDark ? '#facc15' : '#ca8a04', + // Edge colours by kind group + declaredEdge: isDark ? '#6b7280' : '#9ca3af', + autoEdge: isDark ? '#4b5563' : '#d1d5db', + implicitEdge: isDark ? '#374151' : '#e5e7eb', + // Labels + labelColor: isDark ? '#f9fafb' : '#111827', + labelBg: isDark ? 'rgba(17,24,39,0.75)' : 'rgba(255,255,255,0.75)', + // Background + bg: isDark ? '#111827' : '#ffffff', + }; + } + + // ── Cytoscape stylesheet ───────────────────────────────────────────────────── + + function buildStylesheet(palette, egoId) { + const label = { + label: 'data(title)', + color: palette.labelColor, + 'background-color':palette.labelBg, + 'background-opacity': 0.75, + 'background-padding': '3px', + 'font-size': '11px', + 'text-valign': 'bottom', + 'text-halign': 'center', + 'text-margin-y': '4px', + }; + + return [ + // Default node + { + selector: 'node', + style: { + ...label, + shape: 'ellipse', + width: '36px', + height: '36px', + 'background-color': palette.contentFill, + 'border-width': '0px', + 'cursor': 'pointer', + }, + }, + // Ego node (focused) + { + selector: `node[id="${egoId}"]`, + style: { + width: '48px', + height: '48px', + 'border-width': '3px', + 'border-color': palette.egoStroke, + 'font-size': '13px', + 'font-weight': 'bold', + }, + }, + // Ontology variants + { selector: 'node[level="Axiom"]', style: { 'background-color': palette.axiomFill, shape: 'diamond' } }, + { selector: 'node[level="Tension"]', style: { 'background-color': palette.tensionFill, shape: 'triangle' } }, + { selector: 'node[level="Practice"]', style: { 'background-color': palette.practiceFill, shape: 'rectangle' } }, + { selector: 'node[level="Project"]', style: { 'background-color': palette.projectFill, shape: 'rectangle' } }, + // ADR + { selector: 'node[type="adr"]', style: { 'background-color': palette.adrFill, shape: 'pentagon' } }, + // Hover + { + selector: 'node:selected', + style: { 'border-width': '3px', 'border-color': palette.egoStroke }, + }, + // Default edge + { + selector: 'edge', + style: { + width: '1.5px', + 'line-color': palette.declaredEdge, + 'target-arrow-color':palette.declaredEdge, + 'target-arrow-shape':'triangle', + 'curve-style': 'bezier', + opacity: 0.7, + }, + }, + // Auto-backlink edges (lighter) + { + selector: 'edge[source="auto_backlink"]', + style: { 'line-color': palette.autoEdge, 'target-arrow-color': palette.autoEdge, opacity: 0.5 }, + }, + // Implicit / SharedTag edges (dashed, very light) + { + selector: 'edge[kind="shared_tag"]', + style: { + 'line-style': 'dashed', + 'line-color': palette.implicitEdge, + 'target-arrow-color':palette.implicitEdge, + opacity: 0.35, + }, + }, + ]; + } + + // ── Element conversion ─────────────────────────────────────────────────────── + + function toCytoscapeElements(graphData) { + const nodes = (graphData.nodes || []).map(n => ({ + data: { + id: n.id, + title: n.title || n.name || n.id, + type: n.type, + level: n.level || null, + url: n.url || null, + instance: n.instance || null, + }, + })); + + const edges = (graphData.edges || []).map((e, i) => ({ + data: { + id: `e-${i}`, + source: e.from, + target: e.to, + kind: e.kind, + source_type: e.source, // "declared" | "auto_backlink" | "implicit" + }, + })); + + return [...nodes, ...edges]; + } + + // ── Layout config ──────────────────────────────────────────────────────────── + + function buildLayout(nodeCount) { + // cose-bilkent for larger graphs; grid fallback for tiny graphs + if (nodeCount <= 4) { + return { name: 'circle', animate: false, padding: 40 }; + } + return { + name: 'cose-bilkent', + animate: false, + nodeDimensionsIncludeLabels: true, + idealEdgeLength: 100, + nodeRepulsion: 8000, + padding: 30, + }; + } + + // ── Instances registry ─────────────────────────────────────────────────────── + // Keeps track of active cy instances so they can be destroyed on re-render. + + const _instances = new Map(); + + // ── Public API ─────────────────────────────────────────────────────────────── + + window.ContentGraph = { + /** + * Render the knowledge graph into `containerId`. + * + * @param {string} containerId - DOM id of the container element + * @param {string} focusNodeId - node id to highlight/center; may be empty + * @param {string} theme - "dark" | "light" + */ + render(containerId, focusNodeId, theme) { + const container = document.getElementById(containerId); + if (!container) { + console.warn('[ContentGraph] container not found:', containerId); + return; + } + + // Destroy previous instance if re-rendering + if (_instances.has(containerId)) { + _instances.get(containerId).destroy(); + _instances.delete(containerId); + } + + // Read graph data embedded by SSR + const dataEl = document.getElementById('content-graph-data'); + if (!dataEl) { + console.warn('[ContentGraph] #content-graph-data not found'); + return; + } + + let graphData; + try { + graphData = JSON.parse(dataEl.textContent); + } catch (e) { + console.error('[ContentGraph] failed to parse graph data:', e); + return; + } + + const isDark = theme === 'dark'; + const palette = buildPalette(isDark); + const egoId = focusNodeId || ''; + + const cy = window.cytoscape({ + container, + elements: toCytoscapeElements(graphData), + style: buildStylesheet(palette, egoId), + layout: buildLayout((graphData.nodes || []).length), + minZoom: 0.3, + maxZoom: 4, + }); + + _instances.set(containerId, cy); + + // Navigate to content URL on node tap + cy.on('tap', 'node', evt => { + const url = evt.target.data('url'); + if (url) window.location.href = url; + }); + + // Pointer cursor on hover + cy.on('mouseover', 'node[?url]', () => { container.style.cursor = 'pointer'; }); + cy.on('mouseout', 'node', () => { container.style.cursor = 'default'; }); + + // Focus and center on ego node + if (egoId) { + const egoNode = cy.$(`#${CSS.escape(egoId)}`); + if (egoNode.length) { + cy.animate({ fit: { eles: egoNode.neighborhood().add(egoNode), padding: 60 } }, { duration: 400 }); + } + } + }, + + /** + * Destroy the Cytoscape instance for a given container (cleanup on unmount). + */ + destroy(containerId) { + if (_instances.has(containerId)) { + _instances.get(containerId).destroy(); + _instances.delete(containerId); + } + }, + }; +})(); diff --git a/features/content-graph/scripts/download/download-cytoscape.js b/features/content-graph/scripts/download/download-cytoscape.js new file mode 100644 index 0000000..7427dcc --- /dev/null +++ b/features/content-graph/scripts/download/download-cytoscape.js @@ -0,0 +1,76 @@ +#!/usr/bin/env node +// Download Cytoscape.js + cose-bilkent layout plugin from CDN. +// Skips download if files exist and are < 30 days old. +// +// Usage: +// node scripts/download/download-cytoscape.js + +import fs from 'fs'; +import path from 'path'; +import https from 'https'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const PUBLIC_JS = path.join(__dirname, '../../site/public/js'); + +const ASSETS = [ + { + url: 'https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.29.2/cytoscape.min.js', + out: 'cytoscape.min.js', + name: 'Cytoscape.js 3.29.2', + }, + { + url: 'https://cdn.jsdelivr.net/npm/cytoscape-cose-bilkent@4.1.0/cytoscape-cose-bilkent.js', + out: 'cytoscape-cose-bilkent.js', + name: 'cose-bilkent layout 4.1.0', + }, +]; + +const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; + +function download(url, dest) { + return new Promise((resolve, reject) => { + https.get(url, (res) => { + if (res.statusCode === 301 || res.statusCode === 302) { + return download(res.headers.location, dest).then(resolve).catch(reject); + } + if (res.statusCode !== 200) { + return reject(new Error(`HTTP ${res.statusCode}: ${url}`)); + } + const chunks = []; + res.on('data', (c) => chunks.push(c)); + res.on('end', () => { + fs.mkdirSync(path.dirname(dest), { recursive: true }); + fs.writeFileSync(dest, Buffer.concat(chunks)); + resolve(); + }); + }).on('error', reject); + }); +} + +async function main() { + for (const asset of ASSETS) { + const dest = path.join(PUBLIC_JS, asset.out); + + if (fs.existsSync(dest)) { + const age = Date.now() - fs.statSync(dest).mtimeMs; + if (age < MAX_AGE_MS) { + const kb = (fs.statSync(dest).size / 1024).toFixed(1); + console.log(`skip ${asset.name} (${kb} kB, cached)`); + continue; + } + } + + process.stdout.write(`get ${asset.name} ... `); + try { + await download(asset.url, dest); + const kb = (fs.statSync(dest).size / 1024).toFixed(1); + console.log(`ok (${kb} kB)`); + } catch (err) { + console.error(`\nfail ${asset.name}: ${err.message}`); + process.exit(1); + } + } +} + +main(); diff --git a/features/content-graph/site/public/js/cytoscape-cose-bilkent.js b/features/content-graph/site/public/js/cytoscape-cose-bilkent.js new file mode 100644 index 0000000..1f138a8 --- /dev/null +++ b/features/content-graph/site/public/js/cytoscape-cose-bilkent.js @@ -0,0 +1,458 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("cose-base")); + else if(typeof define === 'function' && define.amd) + define(["cose-base"], factory); + else if(typeof exports === 'object') + exports["cytoscapeCoseBilkent"] = factory(require("cose-base")); + else + root["cytoscapeCoseBilkent"] = factory(root["coseBase"]); +})(this, function(__WEBPACK_EXTERNAL_MODULE_0__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 1); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +module.exports = __WEBPACK_EXTERNAL_MODULE_0__; + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var LayoutConstants = __webpack_require__(0).layoutBase.LayoutConstants; +var FDLayoutConstants = __webpack_require__(0).layoutBase.FDLayoutConstants; +var CoSEConstants = __webpack_require__(0).CoSEConstants; +var CoSELayout = __webpack_require__(0).CoSELayout; +var CoSENode = __webpack_require__(0).CoSENode; +var PointD = __webpack_require__(0).layoutBase.PointD; +var DimensionD = __webpack_require__(0).layoutBase.DimensionD; + +var defaults = { + // Called on `layoutready` + ready: function ready() {}, + // Called on `layoutstop` + stop: function stop() {}, + // 'draft', 'default' or 'proof" + // - 'draft' fast cooling rate + // - 'default' moderate cooling rate + // - "proof" slow cooling rate + quality: 'default', + // include labels in node dimensions + nodeDimensionsIncludeLabels: false, + // number of ticks per frame; higher is faster but more jerky + refresh: 30, + // Whether to fit the network view after when done + fit: true, + // Padding on fit + padding: 10, + // Whether to enable incremental mode + randomize: true, + // Node repulsion (non overlapping) multiplier + nodeRepulsion: 4500, + // Ideal edge (non nested) length + idealEdgeLength: 50, + // Divisor to compute edge forces + edgeElasticity: 0.45, + // Nesting factor (multiplier) to compute ideal edge length for nested edges + nestingFactor: 0.1, + // Gravity force (constant) + gravity: 0.25, + // Maximum number of iterations to perform + numIter: 2500, + // For enabling tiling + tile: true, + // Type of layout animation. The option set is {'during', 'end', false} + animate: 'end', + // Duration for animate:end + animationDuration: 500, + // Represents the amount of the vertical space to put between the zero degree members during the tiling operation(can also be a function) + tilingPaddingVertical: 10, + // Represents the amount of the horizontal space to put between the zero degree members during the tiling operation(can also be a function) + tilingPaddingHorizontal: 10, + // Gravity range (constant) for compounds + gravityRangeCompound: 1.5, + // Gravity force (constant) for compounds + gravityCompound: 1.0, + // Gravity range (constant) + gravityRange: 3.8, + // Initial cooling factor for incremental layout + initialEnergyOnIncremental: 0.5 +}; + +function extend(defaults, options) { + var obj = {}; + + for (var i in defaults) { + obj[i] = defaults[i]; + } + + for (var i in options) { + obj[i] = options[i]; + } + + return obj; +}; + +function _CoSELayout(_options) { + this.options = extend(defaults, _options); + getUserOptions(this.options); +} + +var getUserOptions = function getUserOptions(options) { + if (options.nodeRepulsion != null) CoSEConstants.DEFAULT_REPULSION_STRENGTH = FDLayoutConstants.DEFAULT_REPULSION_STRENGTH = options.nodeRepulsion; + if (options.idealEdgeLength != null) CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = options.idealEdgeLength; + if (options.edgeElasticity != null) CoSEConstants.DEFAULT_SPRING_STRENGTH = FDLayoutConstants.DEFAULT_SPRING_STRENGTH = options.edgeElasticity; + if (options.nestingFactor != null) CoSEConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = options.nestingFactor; + if (options.gravity != null) CoSEConstants.DEFAULT_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = options.gravity; + if (options.numIter != null) CoSEConstants.MAX_ITERATIONS = FDLayoutConstants.MAX_ITERATIONS = options.numIter; + if (options.gravityRange != null) CoSEConstants.DEFAULT_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = options.gravityRange; + if (options.gravityCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = options.gravityCompound; + if (options.gravityRangeCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = options.gravityRangeCompound; + if (options.initialEnergyOnIncremental != null) CoSEConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = options.initialEnergyOnIncremental; + + if (options.quality == 'draft') LayoutConstants.QUALITY = 0;else if (options.quality == 'proof') LayoutConstants.QUALITY = 2;else LayoutConstants.QUALITY = 1; + + CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS = FDLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = options.nodeDimensionsIncludeLabels; + CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = !options.randomize; + CoSEConstants.ANIMATE = FDLayoutConstants.ANIMATE = LayoutConstants.ANIMATE = options.animate; + CoSEConstants.TILE = options.tile; + CoSEConstants.TILING_PADDING_VERTICAL = typeof options.tilingPaddingVertical === 'function' ? options.tilingPaddingVertical.call() : options.tilingPaddingVertical; + CoSEConstants.TILING_PADDING_HORIZONTAL = typeof options.tilingPaddingHorizontal === 'function' ? options.tilingPaddingHorizontal.call() : options.tilingPaddingHorizontal; +}; + +_CoSELayout.prototype.run = function () { + var ready; + var frameId; + var options = this.options; + var idToLNode = this.idToLNode = {}; + var layout = this.layout = new CoSELayout(); + var self = this; + + self.stopped = false; + + this.cy = this.options.cy; + + this.cy.trigger({ type: 'layoutstart', layout: this }); + + var gm = layout.newGraphManager(); + this.gm = gm; + + var nodes = this.options.eles.nodes(); + var edges = this.options.eles.edges(); + + this.root = gm.addRoot(); + this.processChildrenList(this.root, this.getTopMostNodes(nodes), layout); + + for (var i = 0; i < edges.length; i++) { + var edge = edges[i]; + var sourceNode = this.idToLNode[edge.data("source")]; + var targetNode = this.idToLNode[edge.data("target")]; + if (sourceNode !== targetNode && sourceNode.getEdgesBetween(targetNode).length == 0) { + var e1 = gm.add(layout.newEdge(), sourceNode, targetNode); + e1.id = edge.id(); + } + } + + var getPositions = function getPositions(ele, i) { + if (typeof ele === "number") { + ele = i; + } + var theId = ele.data('id'); + var lNode = self.idToLNode[theId]; + + return { + x: lNode.getRect().getCenterX(), + y: lNode.getRect().getCenterY() + }; + }; + + /* + * Reposition nodes in iterations animatedly + */ + var iterateAnimated = function iterateAnimated() { + // Thigs to perform after nodes are repositioned on screen + var afterReposition = function afterReposition() { + if (options.fit) { + options.cy.fit(options.eles, options.padding); + } + + if (!ready) { + ready = true; + self.cy.one('layoutready', options.ready); + self.cy.trigger({ type: 'layoutready', layout: self }); + } + }; + + var ticksPerFrame = self.options.refresh; + var isDone; + + for (var i = 0; i < ticksPerFrame && !isDone; i++) { + isDone = self.stopped || self.layout.tick(); + } + + // If layout is done + if (isDone) { + // If the layout is not a sublayout and it is successful perform post layout. + if (layout.checkLayoutSuccess() && !layout.isSubLayout) { + layout.doPostLayout(); + } + + // If layout has a tilingPostLayout function property call it. + if (layout.tilingPostLayout) { + layout.tilingPostLayout(); + } + + layout.isLayoutFinished = true; + + self.options.eles.nodes().positions(getPositions); + + afterReposition(); + + // trigger layoutstop when the layout stops (e.g. finishes) + self.cy.one('layoutstop', self.options.stop); + self.cy.trigger({ type: 'layoutstop', layout: self }); + + if (frameId) { + cancelAnimationFrame(frameId); + } + + ready = false; + return; + } + + var animationData = self.layout.getPositionsData(); // Get positions of layout nodes note that all nodes may not be layout nodes because of tiling + + // Position nodes, for the nodes whose id does not included in data (because they are removed from their parents and included in dummy compounds) + // use position of their ancestors or dummy ancestors + options.eles.nodes().positions(function (ele, i) { + if (typeof ele === "number") { + ele = i; + } + // If ele is a compound node, then its position will be defined by its children + if (!ele.isParent()) { + var theId = ele.id(); + var pNode = animationData[theId]; + var temp = ele; + // If pNode is undefined search until finding position data of its first ancestor (It may be dummy as well) + while (pNode == null) { + pNode = animationData[temp.data('parent')] || animationData['DummyCompound_' + temp.data('parent')]; + animationData[theId] = pNode; + temp = temp.parent()[0]; + if (temp == undefined) { + break; + } + } + if (pNode != null) { + return { + x: pNode.x, + y: pNode.y + }; + } else { + return { + x: ele.position('x'), + y: ele.position('y') + }; + } + } + }); + + afterReposition(); + + frameId = requestAnimationFrame(iterateAnimated); + }; + + /* + * Listen 'layoutstarted' event and start animated iteration if animate option is 'during' + */ + layout.addListener('layoutstarted', function () { + if (self.options.animate === 'during') { + frameId = requestAnimationFrame(iterateAnimated); + } + }); + + layout.runLayout(); // Run cose layout + + /* + * If animate option is not 'during' ('end' or false) perform these here (If it is 'during' similar things are already performed) + */ + if (this.options.animate !== "during") { + self.options.eles.nodes().not(":parent").layoutPositions(self, self.options, getPositions); // Use layout positions to reposition the nodes it considers the options parameter + ready = false; + } + + return this; // chaining +}; + +//Get the top most ones of a list of nodes +_CoSELayout.prototype.getTopMostNodes = function (nodes) { + var nodesMap = {}; + for (var i = 0; i < nodes.length; i++) { + nodesMap[nodes[i].id()] = true; + } + var roots = nodes.filter(function (ele, i) { + if (typeof ele === "number") { + ele = i; + } + var parent = ele.parent()[0]; + while (parent != null) { + if (nodesMap[parent.id()]) { + return false; + } + parent = parent.parent()[0]; + } + return true; + }); + + return roots; +}; + +_CoSELayout.prototype.processChildrenList = function (parent, children, layout) { + var size = children.length; + for (var i = 0; i < size; i++) { + var theChild = children[i]; + var children_of_children = theChild.children(); + var theNode; + + var dimensions = theChild.layoutDimensions({ + nodeDimensionsIncludeLabels: this.options.nodeDimensionsIncludeLabels + }); + + if (theChild.outerWidth() != null && theChild.outerHeight() != null) { + theNode = parent.add(new CoSENode(layout.graphManager, new PointD(theChild.position('x') - dimensions.w / 2, theChild.position('y') - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h)))); + } else { + theNode = parent.add(new CoSENode(this.graphManager)); + } + // Attach id to the layout node + theNode.id = theChild.data("id"); + // Attach the paddings of cy node to layout node + theNode.paddingLeft = parseInt(theChild.css('padding')); + theNode.paddingTop = parseInt(theChild.css('padding')); + theNode.paddingRight = parseInt(theChild.css('padding')); + theNode.paddingBottom = parseInt(theChild.css('padding')); + + //Attach the label properties to compound if labels will be included in node dimensions + if (this.options.nodeDimensionsIncludeLabels) { + if (theChild.isParent()) { + var labelWidth = theChild.boundingBox({ includeLabels: true, includeNodes: false }).w; + var labelHeight = theChild.boundingBox({ includeLabels: true, includeNodes: false }).h; + var labelPos = theChild.css("text-halign"); + theNode.labelWidth = labelWidth; + theNode.labelHeight = labelHeight; + theNode.labelPos = labelPos; + } + } + + // Map the layout node + this.idToLNode[theChild.data("id")] = theNode; + + if (isNaN(theNode.rect.x)) { + theNode.rect.x = 0; + } + + if (isNaN(theNode.rect.y)) { + theNode.rect.y = 0; + } + + if (children_of_children != null && children_of_children.length > 0) { + var theNewGraph; + theNewGraph = layout.getGraphManager().add(layout.newGraph(), theNode); + this.processChildrenList(theNewGraph, children_of_children, layout); + } + } +}; + +/** + * @brief : called on continuous layouts to stop them before they finish + */ +_CoSELayout.prototype.stop = function () { + this.stopped = true; + + return this; // chaining +}; + +var register = function register(cytoscape) { + // var Layout = getLayout( cytoscape ); + + cytoscape('layout', 'cose-bilkent', _CoSELayout); +}; + +// auto reg for globals +if (typeof cytoscape !== 'undefined') { + register(cytoscape); +} + +module.exports = register; + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/features/content-graph/site/public/js/cytoscape.min.js b/features/content-graph/site/public/js/cytoscape.min.js new file mode 100644 index 0000000..e04654d --- /dev/null +++ b/features/content-graph/site/public/js/cytoscape.min.js @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2016-2024, The Cytoscape Consortium. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the “Software”), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).cytoscape=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);nt?1:0},A=null!=Object.assign?Object.assign.bind(Object):function(e){for(var t=arguments,n=1;n255)return;t.push(Math.floor(a))}var o=r[1]||r[2]||r[3],s=r[1]&&r[2]&&r[3];if(o&&!s)return;var l=n[4];if(void 0!==l){if((l=parseFloat(l))<0||l>1)return;t.push(l)}}return t}(e)||function(e){var t,n,r,i,a,o,s,l;function u(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}var c=new RegExp("^hsl[a]?\\(((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?)))\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])(?:\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))))?\\)$").exec(e);if(c){if((n=parseInt(c[1]))<0?n=(360- -1*n%360)%360:n>360&&(n%=360),n/=360,(r=parseFloat(c[2]))<0||r>100)return;if(r/=100,(i=parseFloat(c[3]))<0||i>100)return;if(i/=100,void 0!==(a=c[4])&&((a=parseFloat(a))<0||a>1))return;if(0===r)o=s=l=Math.round(255*i);else{var d=i<.5?i*(1+r):i+r-i*r,h=2*i-d;o=Math.round(255*u(h,d,n+1/3)),s=Math.round(255*u(h,d,n)),l=Math.round(255*u(h,d,n-1/3))}t=[o,s,l,a]}return t}(e)},O={transparent:[0,0,0,0],aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},R=function(e){for(var t=e.map,n=e.keys,r=n.length,i=0;i=t||n<0||d&&e-u>=a}function v(){var e=W();if(g(e))return y(e);s=setTimeout(v,function(e){var n=t-(e-l);return d?fe(n,a-(e-u)):n}(e))}function y(e){return s=void 0,h&&r?p(e):(r=i=void 0,o)}function m(){var e=W(),n=g(e);if(r=arguments,i=this,l=e,n){if(void 0===s)return f(l);if(d)return clearTimeout(s),s=setTimeout(v,t),p(l)}return void 0===s&&(s=setTimeout(v,t)),o}return t=he(t)||0,F(n)&&(c=!!n.leading,a=(d="maxWait"in n)?pe(he(n.maxWait)||0,t):a,h="trailing"in n?!!n.trailing:h),m.cancel=function(){void 0!==s&&clearTimeout(s),u=0,r=l=i=s=void 0},m.flush=function(){return void 0===s?o:y(W())},m},ve=l?l.performance:null,ye=ve&&ve.now?function(){return ve.now()}:function(){return Date.now()},me=function(){if(l){if(l.requestAnimationFrame)return function(e){l.requestAnimationFrame(e)};if(l.mozRequestAnimationFrame)return function(e){l.mozRequestAnimationFrame(e)};if(l.webkitRequestAnimationFrame)return function(e){l.webkitRequestAnimationFrame(e)};if(l.msRequestAnimationFrame)return function(e){l.msRequestAnimationFrame(e)}}return function(e){e&&setTimeout((function(){e(ye())}),1e3/60)}}(),be=function(e){return me(e)},xe=ye,we=65599,Ee=function(e){for(var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261,r=n;!(t=e.next()).done;)r=r*we+t.value|0;return r},ke=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261;return t*we+e|0},Ce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5381;return(t<<5)+t+e|0},Se=function(e){return 2097152*e[0]+e[1]},Pe=function(e,t){return[ke(e[0],t[0]),Ce(e[1],t[1])]},De=function(e,t){var n={value:0,done:!1},r=0,i=e.length;return Ee({next:function(){return r=0&&(e[r]!==t||(e.splice(r,1),!n));r--);},Ke=function(e){e.splice(0,e.length)},Ge=function(e,t,n){return n&&(t=B(n,t)),e[t]},Ue=function(e,t,n,r){n&&(t=B(n,t)),e[t]=r},Ze="undefined"!=typeof Map?Map:function(){function e(){t(this,e),this._obj={}}return r(e,[{key:"set",value:function(e,t){return this._obj[e]=t,this}},{key:"delete",value:function(e){return this._obj[e]=void 0,this}},{key:"clear",value:function(){this._obj={}}},{key:"has",value:function(e){return void 0!==this._obj[e]}},{key:"get",value:function(e){return this._obj[e]}}]),e}(),$e=function(){function e(n){if(t(this,e),this._obj=Object.create(null),this.size=0,null!=n){var r;r=null!=n.instanceString&&n.instanceString()===this.instanceString()?n.toArray():n;for(var i=0;i2&&void 0!==arguments[2])||arguments[2];if(void 0!==e&&void 0!==t&&C(e)){var r=t.group;if(null==r&&(r=t.data&&null!=t.data.source&&null!=t.data.target?"edges":"nodes"),"nodes"===r||"edges"===r){this.length=1,this[0]=this;var i=this._private={cy:e,single:!0,data:t.data||{},position:t.position||{x:0,y:0},autoWidth:void 0,autoHeight:void 0,autoPadding:void 0,compoundBoundsClean:!1,listeners:[],group:r,style:{},rstyle:{},styleCxts:[],styleKeys:{},removed:!0,selected:!!t.selected,selectable:void 0===t.selectable||!!t.selectable,locked:!!t.locked,grabbed:!1,grabbable:void 0===t.grabbable||!!t.grabbable,pannable:void 0===t.pannable?"edges"===r:!!t.pannable,active:!1,classes:new Qe,animation:{current:[],queue:[]},rscratch:{},scratch:t.scratch||{},edges:[],children:[],parent:t.parent&&t.parent.isNode()?t.parent:null,traversalCache:{},backgrounding:!1,bbCache:null,bbCacheShift:{x:0,y:0},bodyBounds:null,overlayBounds:null,labelBounds:{all:null,source:null,target:null,main:null},arrowBounds:{source:null,target:null,"mid-source":null,"mid-target":null}};if(null==i.position.x&&(i.position.x=0),null==i.position.y&&(i.position.y=0),t.renderedPosition){var a=t.renderedPosition,o=e.pan(),s=e.zoom();i.position={x:(a.x-o.x)/s,y:(a.y-o.y)/s}}var l=[];y(t.classes)?l=t.classes:g(t.classes)&&(l=t.classes.split(/\s+/));for(var u=0,c=l.length;ut?1:0},u=function(e,t,i,a,o){var s;if(null==i&&(i=0),null==o&&(o=n),i<0)throw new Error("lo must be non-negative");for(null==a&&(a=e.length);in;0<=n?t++:t--)u.push(t);return u}.apply(this).reverse()).length;ag;0<=g?++h:--h)v.push(a(e,r));return v},f=function(e,t,r,i){var a,o,s;for(null==i&&(i=n),a=e[r];r>t&&i(a,o=e[s=r-1>>1])<0;)e[r]=o,r=s;return e[r]=a},g=function(e,t,r){var i,a,o,s,l;for(null==r&&(r=n),a=e.length,l=t,o=e[t],i=2*t+1;i0;){var k=b.pop(),C=v(k),S=k.id();if(d[S]=C,C!==1/0)for(var P=k.neighborhood().intersect(p),D=0;D0)for(n.unshift(t);c[i];){var a=c[i];n.unshift(a.edge),n.unshift(a.node),i=(r=a.node).id()}return o.spawn(n)}}}},at={kruskal:function(e){e=e||function(e){return 1};for(var t=this.byGroup(),n=t.nodes,r=t.edges,i=n.length,a=new Array(i),o=n,s=function(e){for(var t=0;t0;){if(l=g.pop(),u=l.id(),v.delete(u),w++,u===d){for(var E=[],k=i,C=d,S=m[C];E.unshift(k),null!=S&&E.unshift(S),null!=(k=y[C]);)S=m[C=k.id()];return{found:!0,distance:h[u],path:this.spawn(E),steps:w}}f[u]=!0;for(var P=l._private.edges,D=0;DD&&(p[P]=D,m[P]=S,b[P]=w),!i){var T=S*u+C;!i&&p[T]>D&&(p[T]=D,m[T]=C,b[T]=w)}}}for(var _=0;_1&&void 0!==arguments[1]?arguments[1]:a,r=b(e),i=[],o=r;;){if(null==o)return t.spawn();var l=m(o),u=l.edge,c=l.pred;if(i.unshift(o[0]),o.same(n)&&i.length>0)break;null!=u&&i.unshift(u),o=c}return s.spawn(i)},hasNegativeWeightCycle:f,negativeWeightCycles:v}}},ht=Math.sqrt(2),pt=function(e,t,n){0===n.length&&Re("Karger-Stein must be run on a connected (sub)graph");for(var r=n[e],i=r[1],a=r[2],o=t[i],s=t[a],l=n,u=l.length-1;u>=0;u--){var c=l[u],d=c[1],h=c[2];(t[d]===o&&t[h]===s||t[d]===s&&t[h]===o)&&l.splice(u,1)}for(var p=0;pr;){var i=Math.floor(Math.random()*t.length);t=pt(i,e,t),n--}return t},gt={kargerStein:function(){var e=this,t=this.byGroup(),n=t.nodes,r=t.edges;r.unmergeBy((function(e){return e.isLoop()}));var i=n.length,a=r.length,o=Math.ceil(Math.pow(Math.log(i)/Math.LN2,2)),s=Math.floor(i/ht);if(!(i<2)){for(var l=[],u=0;u0?1:e<0?-1:0},Et=function(e,t){return Math.sqrt(kt(e,t))},kt=function(e,t){var n=t.x-e.x,r=t.y-e.y;return n*n+r*r},Ct=function(e){for(var t=e.length,n=0,r=0;r=e.x1&&e.y2>=e.y1)return{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,w:e.x2-e.x1,h:e.y2-e.y1};if(null!=e.w&&null!=e.h&&e.w>=0&&e.h>=0)return{x1:e.x1,y1:e.y1,x2:e.x1+e.w,y2:e.y1+e.h,w:e.w,h:e.h}}},_t=function(e,t){e.x1=Math.min(e.x1,t.x1),e.x2=Math.max(e.x2,t.x2),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,t.y1),e.y2=Math.max(e.y2,t.y2),e.h=e.y2-e.y1},Mt=function(e,t,n){e.x1=Math.min(e.x1,t),e.x2=Math.max(e.x2,t),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,n),e.y2=Math.max(e.y2,n),e.h=e.y2-e.y1},Bt=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e.x1-=t,e.x2+=t,e.y1-=t,e.y2+=t,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},Nt=function(e){var t,n,r,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0];if(1===o.length)t=n=r=i=o[0];else if(2===o.length)t=r=o[0],i=n=o[1];else if(4===o.length){var s=a(o,4);t=s[0],n=s[1],r=s[2],i=s[3]}return e.x1-=i,e.x2+=n,e.y1-=t,e.y2+=r,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},zt=function(e,t){e.x1=t.x1,e.y1=t.y1,e.x2=t.x2,e.y2=t.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1},It=function(e,t){return!(e.x1>t.x2)&&(!(t.x1>e.x2)&&(!(e.x2t.y2)&&!(t.y1>e.y2)))))))},At=function(e,t,n){return e.x1<=t&&t<=e.x2&&e.y1<=n&&n<=e.y2},Lt=function(e,t){return At(e,t.x1,t.y1)&&At(e,t.x2,t.y2)},Ot=function(e,t,n,r,i,a,o){var s,l,u=arguments.length>7&&void 0!==arguments[7]?arguments[7]:"auto",c="auto"===u?tn(i,a):u,d=i/2,h=a/2,p=(c=Math.min(c,d,h))!==d,f=c!==h;if(p){var g=n-d+c-o,v=r-h-o,y=n+d-c+o,m=v;if((s=Ut(e,t,n,r,g,v,y,m,!1)).length>0)return s}if(f){var b=n+d+o,x=r-h+c-o,w=b,E=r+h-c+o;if((s=Ut(e,t,n,r,b,x,w,E,!1)).length>0)return s}if(p){var k=n-d+c-o,C=r+h+o,S=n+d-c+o,P=C;if((s=Ut(e,t,n,r,k,C,S,P,!1)).length>0)return s}if(f){var D=n-d-o,T=r-h+c-o,_=D,M=r+h-c+o;if((s=Ut(e,t,n,r,D,T,_,M,!1)).length>0)return s}var B=n-d+c,N=r-h+c;if((l=Kt(e,t,n,r,B,N,c+o)).length>0&&l[0]<=B&&l[1]<=N)return[l[0],l[1]];var z=n+d-c,I=r-h+c;if((l=Kt(e,t,n,r,z,I,c+o)).length>0&&l[0]>=z&&l[1]<=I)return[l[0],l[1]];var A=n+d-c,L=r+h-c;if((l=Kt(e,t,n,r,A,L,c+o)).length>0&&l[0]>=A&&l[1]>=L)return[l[0],l[1]];var O=n-d+c,R=r+h-c;return(l=Kt(e,t,n,r,O,R,c+o)).length>0&&l[0]<=O&&l[1]>=R?[l[0],l[1]]:[]},Rt=function(e,t,n,r,i,a,o){var s=o,l=Math.min(n,i),u=Math.max(n,i),c=Math.min(r,a),d=Math.max(r,a);return l-s<=e&&e<=u+s&&c-s<=t&&t<=d+s},Vt=function(e,t,n,r,i,a,o,s,l){var u=Math.min(n,o,i)-l,c=Math.max(n,o,i)+l,d=Math.min(r,s,a)-l,h=Math.max(r,s,a)+l;return!(ec||th)},Ft=function(e,t,n,r,i,a,o,s){var l=[];!function(e,t,n,r,i){var a,o,s,l,u,c,d,h;0===e&&(e=1e-5),s=-27*(r/=e)+(t/=e)*(9*(n/=e)-t*t*2),a=(o=(3*n-t*t)/9)*o*o+(s/=54)*s,i[1]=0,d=t/3,a>0?(u=(u=s+Math.sqrt(a))<0?-Math.pow(-u,1/3):Math.pow(u,1/3),c=(c=s-Math.sqrt(a))<0?-Math.pow(-c,1/3):Math.pow(c,1/3),i[0]=-d+u+c,d+=(u+c)/2,i[4]=i[2]=-d,d=Math.sqrt(3)*(-c+u)/2,i[3]=d,i[5]=-d):(i[5]=i[3]=0,0===a?(h=s<0?-Math.pow(-s,1/3):Math.pow(s,1/3),i[0]=2*h-d,i[4]=i[2]=-(h+d)):(l=(o=-o)*o*o,l=Math.acos(s/Math.sqrt(l)),h=2*Math.sqrt(o),i[0]=-d+h*Math.cos(l/3),i[2]=-d+h*Math.cos((l+2*Math.PI)/3),i[4]=-d+h*Math.cos((l+4*Math.PI)/3)))}(1*n*n-4*n*i+2*n*o+4*i*i-4*i*o+o*o+r*r-4*r*a+2*r*s+4*a*a-4*a*s+s*s,9*n*i-3*n*n-3*n*o-6*i*i+3*i*o+9*r*a-3*r*r-3*r*s-6*a*a+3*a*s,3*n*n-6*n*i+n*o-n*e+2*i*i+2*i*e-o*e+3*r*r-6*r*a+r*s-r*t+2*a*a+2*a*t-s*t,1*n*i-n*n+n*e-i*e+r*a-r*r+r*t-a*t,l);for(var u=[],c=0;c<6;c+=2)Math.abs(l[c+1])<1e-7&&l[c]>=0&&l[c]<=1&&u.push(l[c]);u.push(1),u.push(0);for(var d,h,p,f=-1,g=0;g=0?pl?(e-i)*(e-i)+(t-a)*(t-a):u-d},qt=function(e,t,n){for(var r,i,a,o,s=0,l=0;l=e&&e>=a||r<=e&&e<=a))continue;(e-r)/(a-r)*(o-i)+i>t&&s++}return s%2!=0},Yt=function(e,t,n,r,i,a,o,s,l){var u,c=new Array(n.length);null!=s[0]?(u=Math.atan(s[1]/s[0]),s[0]<0?u+=Math.PI/2:u=-u-Math.PI/2):u=s;for(var d,h=Math.cos(-u),p=Math.sin(-u),f=0;f0){var g=Wt(c,-l);d=Xt(g)}else d=c;return qt(e,t,d)},Xt=function(e){for(var t,n,r,i,a,o,s,l,u=new Array(e.length/2),c=0;c=0&&f<=1&&v.push(f),g>=0&&g<=1&&v.push(g),0===v.length)return[];var y=v[0]*s[0]+e,m=v[0]*s[1]+t;return v.length>1?v[0]==v[1]?[y,m]:[y,m,v[1]*s[0]+e,v[1]*s[1]+t]:[y,m]},Gt=function(e,t,n){return t<=e&&e<=n||n<=e&&e<=t?e:e<=t&&t<=n||n<=t&&t<=e?t:n},Ut=function(e,t,n,r,i,a,o,s,l){var u=e-i,c=n-e,d=o-i,h=t-a,p=r-t,f=s-a,g=d*h-f*u,v=c*h-p*u,y=f*c-d*p;if(0!==y){var m=g/y,b=v/y;return-.001<=m&&m<=1.001&&-.001<=b&&b<=1.001||l?[e+m*c,t+m*p]:[]}return 0===g||0===v?Gt(e,n,o)===o?[o,s]:Gt(e,n,i)===i?[i,a]:Gt(i,o,n)===n?[n,r]:[]:[]},Zt=function(e,t,n,r,i,a,o,s){var l,u,c,d,h,p,f=[],g=new Array(n.length),v=!0;if(null==a&&(v=!1),v){for(var y=0;y0){var m=Wt(g,-s);u=Xt(m)}else u=g}else u=n;for(var b=0;bu&&(u=t)},d=function(e){return l[e]},h=0;h0?b.edgesTo(m)[0]:m.edgesTo(b)[0];var w=r(x);m=m.id(),h[m]>h[v]+w&&(h[m]=h[v]+w,p.nodes.indexOf(m)<0?p.push(m):p.updateItem(m),u[m]=0,l[m]=[]),h[m]==h[v]+w&&(u[m]=u[m]+u[v],l[m].push(v))}else for(var E=0;E0;){for(var P=n.pop(),D=0;D0&&o.push(n[s]);0!==o.length&&i.push(r.collection(o))}return i}(c,l,t,r);return b=function(e){for(var t=0;t5&&void 0!==arguments[5]?arguments[5]:kn,o=r,s=0;s=2?_n(e,t,n,0,Pn,Dn):_n(e,t,n,0,Sn)},squaredEuclidean:function(e,t,n){return _n(e,t,n,0,Pn)},manhattan:function(e,t,n){return _n(e,t,n,0,Sn)},max:function(e,t,n){return _n(e,t,n,-1/0,Tn)}};function Bn(e,t,n,r,i,a){var o;return o=v(e)?e:Mn[e]||Mn.euclidean,0===t&&v(e)?o(i,a):o(t,n,r,i,a)}Mn["squared-euclidean"]=Mn.squaredEuclidean,Mn.squaredeuclidean=Mn.squaredEuclidean;var Nn=We({k:2,m:2,sensitivityThreshold:1e-4,distance:"euclidean",maxIterations:10,attributes:[],testMode:!1,testCentroids:null}),zn=function(e){return Nn(e)},In=function(e,t,n,r,i){var a="kMedoids"!==i?function(e){return n[e]}:function(e){return r[e](n)},o=n,s=t;return Bn(e,r.length,a,(function(e){return r[e](t)}),o,s)},An=function(e,t,n){for(var r=n.length,i=new Array(r),a=new Array(r),o=new Array(t),s=null,l=0;ln)return!1}return!0},Fn=function(e,t,n){for(var r=0;ri&&(i=t[l][u],a=u);o[a].push(e[l])}for(var c=0;c=i.threshold||"dendrogram"===i.mode&&1===e.length)return!1;var p,f=t[o],g=t[r[o]];p="dendrogram"===i.mode?{left:f,right:g,key:f.key}:{value:f.value.concat(g.value),key:f.key},e[f.index]=p,e.splice(g.index,1),t[f.key]=p;for(var v=0;vn[g.key][y.key]&&(a=n[g.key][y.key])):"max"===i.linkage?(a=n[f.key][y.key],n[f.key][y.key]1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5];r?e=e.slice(t,n):(n0&&e.splice(0,t));for(var o=0,s=e.length-1;s>=0;s--){var l=e[s];a?isFinite(l)||(e[s]=-1/0,o++):e.splice(s,1)}i&&e.sort((function(e,t){return e-t}));var u=e.length,c=Math.floor(u/2);return u%2!=0?e[c+1+o]:(e[c-1+o]+e[c+o])/2}(e):"mean"===t?function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=0,i=0,a=t;a1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=1/0,i=t;i1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=-1/0,i=t;io&&(a=l,o=t[i*e+l])}a>0&&r.push(a)}for(var u=0;u=D?(T=D,D=M,_=B):M>T&&(T=M);for(var N=0;N0?1:0;C[k%u.minIterations*t+R]=V,O+=V}if(O>0&&(k>=u.minIterations-1||k==u.maxIterations-1)){for(var F=0,j=0;j0&&r.push(i);return r}(t,a,o),X=function(e,t,n){for(var r=nr(e,t,n),i=0;il&&(s=u,l=c)}n[i]=a[s]}return r=nr(e,t,n)}(t,r,Y),W={},H=0;H1)}}));var l=Object.keys(t).filter((function(e){return t[e].cutVertex})).map((function(t){return e.getElementById(t)}));return{cut:e.spawn(l),components:i}},sr=function(){var e=this,t={},n=0,r=[],i=[],a=e.spawn(e);return e.forEach((function(o){if(o.isNode()){var s=o.id();s in t||function o(s){if(i.push(s),t[s]={index:n,low:n++,explored:!1},e.getElementById(s).connectedEdges().intersection(e).forEach((function(e){var n=e.target().id();n!==s&&(n in t||o(n),t[n].explored||(t[s].low=Math.min(t[s].low,t[n].low)))})),t[s].index===t[s].low){for(var l=e.spawn();;){var u=i.pop();if(l.merge(e.getElementById(u)),t[u].low=t[s].index,t[u].explored=!0,u===s)break}var c=l.edgesWith(l),d=l.merge(c);r.push(d),a=a.difference(d)}}(s)}})),{cut:a,components:r}},lr={};[tt,it,at,st,ut,dt,gt,on,ln,cn,hn,En,Hn,Qn,ir,{hierholzer:function(e){if(!m(e)){var t=arguments;e={root:t[0],directed:t[1]}}var n,r,i,a=ar(e),o=a.root,s=a.directed,l=this,u=!1;o&&(i=g(o)?this.filter(o)[0].id():o[0].id());var c={},d={};s?l.forEach((function(e){var t=e.id();if(e.isNode()){var i=e.indegree(!0),a=e.outdegree(!0),o=i-a,s=a-i;1==o?n?u=!0:n=t:1==s?r?u=!0:r=t:(s>1||o>1)&&(u=!0),c[t]=[],e.outgoers().forEach((function(e){e.isEdge()&&c[t].push(e.id())}))}else d[t]=[void 0,e.target().id()]})):l.forEach((function(e){var t=e.id();e.isNode()?(e.degree(!0)%2&&(n?r?u=!0:r=t:n=t),c[t]=[],e.connectedEdges().forEach((function(e){return c[t].push(e.id())}))):d[t]=[e.source().id(),e.target().id()]}));var h={found:!1,trail:void 0};if(u)return h;if(r&&n)if(s){if(i&&r!=i)return h;i=r}else{if(i&&r!=i&&n!=i)return h;i||(i=r)}else i||(i=l[0].id());var p=function(e){for(var t,n,r,i=e,a=[e];c[i].length;)t=c[i].shift(),n=d[t][0],i!=(r=d[t][1])?(c[r]=c[r].filter((function(e){return e!=t})),i=r):s||i==n||(c[n]=c[n].filter((function(e){return e!=t})),i=n),a.unshift(t),a.unshift(i);return a},f=[],v=[];for(v=p(i);1!=v.length;)0==c[v[0]].length?(f.unshift(l.getElementById(v.shift())),f.unshift(l.getElementById(v.shift()))):v=p(v.shift()).concat(v);for(var y in f.unshift(l.getElementById(v.shift())),c)if(c[y].length)return h;return h.found=!0,h.trail=this.spawn(f,!0),h}},{hopcroftTarjanBiconnected:or,htbc:or,htb:or,hopcroftTarjanBiconnectedComponents:or},{tarjanStronglyConnected:sr,tsc:sr,tscc:sr,tarjanStronglyConnectedComponents:sr}].forEach((function(e){A(lr,e)})); +/*! + Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable + Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com) + Licensed under The MIT License (http://opensource.org/licenses/MIT) + */ +var ur=function e(t){if(!(this instanceof e))return new e(t);this.id="Thenable/1.0.7",this.state=0,this.fulfillValue=void 0,this.rejectReason=void 0,this.onFulfilled=[],this.onRejected=[],this.proxy={then:this.then.bind(this)},"function"==typeof t&&t.call(this,this.fulfill.bind(this),this.reject.bind(this))};ur.prototype={fulfill:function(e){return cr(this,1,"fulfillValue",e)},reject:function(e){return cr(this,2,"rejectReason",e)},then:function(e,t){var n=new ur;return this.onFulfilled.push(pr(e,n,"fulfill")),this.onRejected.push(pr(t,n,"reject")),dr(this),n.proxy}};var cr=function(e,t,n,r){return 0===e.state&&(e.state=t,e[n]=r,dr(e)),e},dr=function(e){1===e.state?hr(e,"onFulfilled",e.fulfillValue):2===e.state&&hr(e,"onRejected",e.rejectReason)},hr=function(e,t,n){if(0!==e[t].length){var r=e[t];e[t]=[];var i=function(){for(var e=0;e0:void 0}},clearQueue:function(){return function(){var e=void 0!==this.length?this:[this];if(!(this._private.cy||this).styleEnabled())return this;for(var t=0;t-1};var ni=function(e,t){var n=this.__data__,r=$r(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this};function ri(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e0&&this.spawn(n).updateStyle().emit("class"),this},addClass:function(e){return this.toggleClass(e,!0)},hasClass:function(e){var t=this[0];return null!=t&&t._private.classes.has(e)},toggleClass:function(e,t){y(e)||(e=e.match(/\S+/g)||[]);for(var n=void 0===t,r=[],i=0,a=this.length;i0&&this.spawn(r).updateStyle().emit("class"),this},removeClass:function(e){return this.toggleClass(e,!1)},flashClass:function(e,t){var n=this;if(null==t)t=250;else if(0===t)return n;return n.addClass(e),setTimeout((function(){n.removeClass(e)}),t),n}};ji.className=ji.classNames=ji.classes;var qi={metaChar:"[\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]",comparatorOp:"=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=",boolOp:"\\?|\\!|\\^",string:"\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'",number:z,meta:"degree|indegree|outdegree",separator:"\\s*,\\s*",descendant:"\\s+",child:"\\s+>\\s+",subject:"\\$",group:"node|edge|\\*",directedEdge:"\\s+->\\s+",undirectedEdge:"\\s+<->\\s+"};qi.variable="(?:[\\w-.]|(?:\\\\"+qi.metaChar+"))+",qi.className="(?:[\\w-]|(?:\\\\"+qi.metaChar+"))+",qi.value=qi.string+"|"+qi.number,qi.id=qi.variable,function(){var e,t,n;for(e=qi.comparatorOp.split("|"),n=0;n=0||"="!==t&&(qi.comparatorOp+="|\\!"+t)}();var Yi=0,Xi=1,Wi=2,Hi=3,Ki=4,Gi=5,Ui=6,Zi=7,$i=8,Qi=9,Ji=10,ea=11,ta=12,na=13,ra=14,ia=15,aa=16,oa=17,sa=18,la=19,ua=20,ca=[{selector:":selected",matches:function(e){return e.selected()}},{selector:":unselected",matches:function(e){return!e.selected()}},{selector:":selectable",matches:function(e){return e.selectable()}},{selector:":unselectable",matches:function(e){return!e.selectable()}},{selector:":locked",matches:function(e){return e.locked()}},{selector:":unlocked",matches:function(e){return!e.locked()}},{selector:":visible",matches:function(e){return e.visible()}},{selector:":hidden",matches:function(e){return!e.visible()}},{selector:":transparent",matches:function(e){return e.transparent()}},{selector:":grabbed",matches:function(e){return e.grabbed()}},{selector:":free",matches:function(e){return!e.grabbed()}},{selector:":removed",matches:function(e){return e.removed()}},{selector:":inside",matches:function(e){return!e.removed()}},{selector:":grabbable",matches:function(e){return e.grabbable()}},{selector:":ungrabbable",matches:function(e){return!e.grabbable()}},{selector:":animated",matches:function(e){return e.animated()}},{selector:":unanimated",matches:function(e){return!e.animated()}},{selector:":parent",matches:function(e){return e.isParent()}},{selector:":childless",matches:function(e){return e.isChildless()}},{selector:":child",matches:function(e){return e.isChild()}},{selector:":orphan",matches:function(e){return e.isOrphan()}},{selector:":nonorphan",matches:function(e){return e.isChild()}},{selector:":compound",matches:function(e){return e.isNode()?e.isParent():e.source().isParent()||e.target().isParent()}},{selector:":loop",matches:function(e){return e.isLoop()}},{selector:":simple",matches:function(e){return e.isSimple()}},{selector:":active",matches:function(e){return e.active()}},{selector:":inactive",matches:function(e){return!e.active()}},{selector:":backgrounding",matches:function(e){return e.backgrounding()}},{selector:":nonbackgrounding",matches:function(e){return!e.backgrounding()}}].sort((function(e,t){return function(e,t){return-1*I(e,t)}(e.selector,t.selector)})),da=function(){for(var e,t={},n=0;n0&&l.edgeCount>0)return Fe("The selector `"+e+"` is invalid because it uses both a compound selector and an edge selector"),!1;if(l.edgeCount>1)return Fe("The selector `"+e+"` is invalid because it uses multiple edge selectors"),!1;1===l.edgeCount&&Fe("The selector `"+e+"` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.")}return!0},toString:function(){if(null!=this.toStringCache)return this.toStringCache;for(var e=function(e){return null==e?"":e},t=function(t){return g(t)?'"'+t+'"':e(t)},n=function(e){return" "+e+" "},r=function(r,a){var o=r.type,s=r.value;switch(o){case Yi:var l=e(s);return l.substring(0,l.length-1);case Hi:var u=r.field,c=r.operator;return"["+u+n(e(c))+t(s)+"]";case Gi:var d=r.operator,h=r.field;return"["+e(d)+h+"]";case Ki:return"["+r.field+"]";case Ui:var p=r.operator;return"[["+r.field+n(e(p))+t(s)+"]]";case Zi:return s;case $i:return"#"+s;case Qi:return"."+s;case oa:case ia:return i(r.parent,a)+n(">")+i(r.child,a);case sa:case aa:return i(r.ancestor,a)+" "+i(r.descendant,a);case la:var f=i(r.left,a),g=i(r.subject,a),v=i(r.right,a);return f+(f.length>0?" ":"")+g+v;case ua:return""}},i=function(e,t){return e.checks.reduce((function(n,i,a){return n+(t===e&&0===a?"$":"")+r(i,t)}),"")},a="",o=0;o1&&o=0&&(t=t.replace("!",""),c=!0),t.indexOf("@")>=0&&(t=t.replace("@",""),u=!0),(o||l||u)&&(i=o||s?""+e:"",a=""+n),u&&(e=i=i.toLowerCase(),n=a=a.toLowerCase()),t){case"*=":r=i.indexOf(a)>=0;break;case"$=":r=i.indexOf(a,i.length-a.length)>=0;break;case"^=":r=0===i.indexOf(a);break;case"=":r=e===n;break;case">":d=!0,r=e>n;break;case">=":d=!0,r=e>=n;break;case"<":d=!0,r=e0;){var u=i.shift();t(u),a.add(u.id()),o&&r(i,a,u)}return e}function Ma(e,t,n){if(n.isParent())for(var r=n._private.children,i=0;i1&&void 0!==arguments[1])||arguments[1];return _a(this,e,t,Ma)},Ta.forEachUp=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return _a(this,e,t,Ba)},Ta.forEachUpAndDown=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return _a(this,e,t,Na)},Ta.ancestors=Ta.parents,(Sa=Pa={data:Vi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),removeData:Vi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),scratch:Vi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Vi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),rscratch:Vi.data({field:"rscratch",allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!0}),removeRscratch:Vi.removeData({field:"rscratch",triggerEvent:!1}),id:function(){var e=this[0];if(e)return e._private.data.id}}).attr=Sa.data,Sa.removeAttr=Sa.removeData;var za,Ia,Aa=Pa,La={};function Oa(e){return function(t){if(void 0===t&&(t=!0),0!==this.length&&this.isNode()&&!this.removed()){for(var n=0,r=this[0],i=r._private.edges,a=0;at})),minIndegree:Ra("indegree",(function(e,t){return et})),minOutdegree:Ra("outdegree",(function(e,t){return et}))}),A(La,{totalDegree:function(e){for(var t=0,n=this.nodes(),r=0;r0,c=u;u&&(l=l[0]);var d=c?l.position():{x:0,y:0};return i={x:s.x-d.x,y:s.y-d.y},void 0===e?i:i[e]}for(var h=0;h0,y=v;v&&(f=f[0]);var b=y?f.position():{x:0,y:0};void 0!==t?p.position(e,t+b[e]):void 0!==i&&p.position({x:i.x+b.x,y:i.y+b.y})}}else if(!a)return;return this}}).modelPosition=za.point=za.position,za.modelPositions=za.points=za.positions,za.renderedPoint=za.renderedPosition,za.relativePoint=za.relativePosition;var ja,qa,Ya=Ia;ja=qa={},qa.renderedBoundingBox=function(e){var t=this.boundingBox(e),n=this.cy(),r=n.zoom(),i=n.pan(),a=t.x1*r+i.x,o=t.x2*r+i.x,s=t.y1*r+i.y,l=t.y2*r+i.y;return{x1:a,x2:o,y1:s,y2:l,w:o-a,h:l-s}},qa.dirtyCompoundBoundsCache=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();return t.styleEnabled()&&t.hasCompoundNodes()?(this.forEachUp((function(t){if(t.isParent()){var n=t._private;n.compoundBoundsClean=!1,n.bbCache=null,e||t.emitAndNotify("bounds")}})),this):this},qa.updateCompoundBounds=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();if(!t.styleEnabled()||!t.hasCompoundNodes())return this;if(!e&&t.batching())return this;function n(e){if(e.isParent()){var t=e._private,n=e.children(),r="include"===e.pstyle("compound-sizing-wrt-labels").value,i={width:{val:e.pstyle("min-width").pfValue,left:e.pstyle("min-width-bias-left"),right:e.pstyle("min-width-bias-right")},height:{val:e.pstyle("min-height").pfValue,top:e.pstyle("min-height-bias-top"),bottom:e.pstyle("min-height-bias-bottom")}},a=n.boundingBox({includeLabels:r,includeOverlays:!1,useCache:!1}),o=t.position;0!==a.w&&0!==a.h||((a={w:e.pstyle("width").pfValue,h:e.pstyle("height").pfValue}).x1=o.x-a.w/2,a.x2=o.x+a.w/2,a.y1=o.y-a.h/2,a.y2=o.y+a.h/2);var s=i.width.left.value;"px"===i.width.left.units&&i.width.val>0&&(s=100*s/i.width.val);var l=i.width.right.value;"px"===i.width.right.units&&i.width.val>0&&(l=100*l/i.width.val);var u=i.height.top.value;"px"===i.height.top.units&&i.height.val>0&&(u=100*u/i.height.val);var c=i.height.bottom.value;"px"===i.height.bottom.units&&i.height.val>0&&(c=100*c/i.height.val);var d=y(i.width.val-a.w,s,l),h=d.biasDiff,p=d.biasComplementDiff,f=y(i.height.val-a.h,u,c),g=f.biasDiff,v=f.biasComplementDiff;t.autoPadding=function(e,t,n,r){if("%"!==n.units)return"px"===n.units?n.pfValue:0;switch(r){case"width":return e>0?n.pfValue*e:0;case"height":return t>0?n.pfValue*t:0;case"average":return e>0&&t>0?n.pfValue*(e+t)/2:0;case"min":return e>0&&t>0?e>t?n.pfValue*t:n.pfValue*e:0;case"max":return e>0&&t>0?e>t?n.pfValue*e:n.pfValue*t:0;default:return 0}}(a.w,a.h,e.pstyle("padding"),e.pstyle("padding-relative-to").value),t.autoWidth=Math.max(a.w,i.width.val),o.x=(-h+a.x1+a.x2+p)/2,t.autoHeight=Math.max(a.h,i.height.val),o.y=(-g+a.y1+a.y2+v)/2}function y(e,t,n){var r=0,i=0,a=t+n;return e>0&&a>0&&(r=t/a*e,i=n/a*e),{biasDiff:r,biasComplementDiff:i}}}for(var r=0;re.x2?r:e.x2,e.y1=ne.y2?i:e.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1)},Ha=function(e,t){return null==t?e:Wa(e,t.x1,t.y1,t.x2,t.y2)},Ka=function(e,t,n){return Ge(e,t,n)},Ga=function(e,t,n){if(!t.cy().headless()){var r,i,a=t._private,o=a.rstyle,s=o.arrowWidth/2;if("none"!==t.pstyle(n+"-arrow-shape").value){"source"===n?(r=o.srcX,i=o.srcY):"target"===n?(r=o.tgtX,i=o.tgtY):(r=o.midX,i=o.midY);var l=a.arrowBounds=a.arrowBounds||{},u=l[n]=l[n]||{};u.x1=r-s,u.y1=i-s,u.x2=r+s,u.y2=i+s,u.w=u.x2-u.x1,u.h=u.y2-u.y1,Bt(u,1),Wa(e,u.x1,u.y1,u.x2,u.y2)}}},Ua=function(e,t,n){if(!t.cy().headless()){var r;r=n?n+"-":"";var i=t._private,a=i.rstyle;if(t.pstyle(r+"label").strValue){var o,s,l,u,c=t.pstyle("text-halign"),d=t.pstyle("text-valign"),h=Ka(a,"labelWidth",n),p=Ka(a,"labelHeight",n),f=Ka(a,"labelX",n),g=Ka(a,"labelY",n),v=t.pstyle(r+"text-margin-x").pfValue,y=t.pstyle(r+"text-margin-y").pfValue,m=t.isEdge(),b=t.pstyle(r+"text-rotation"),x=t.pstyle("text-outline-width").pfValue,w=t.pstyle("text-border-width").pfValue/2,E=t.pstyle("text-background-padding").pfValue,k=p,C=h,S=C/2,P=k/2;if(m)o=f-S,s=f+S,l=g-P,u=g+P;else{switch(c.value){case"left":o=f-C,s=f;break;case"center":o=f-S,s=f+S;break;case"right":o=f,s=f+C}switch(d.value){case"top":l=g-k,u=g;break;case"center":l=g-P,u=g+P;break;case"bottom":l=g,u=g+k}}o+=v-Math.max(x,w)-E-2,s+=v+Math.max(x,w)+E+2,l+=y-Math.max(x,w)-E-2,u+=y+Math.max(x,w)+E+2;var D=n||"main",T=i.labelBounds,_=T[D]=T[D]||{};_.x1=o,_.y1=l,_.x2=s,_.y2=u,_.w=s-o,_.h=u-l;var M=m&&"autorotate"===b.strValue,B=null!=b.pfValue&&0!==b.pfValue;if(M||B){var N=M?Ka(i.rstyle,"labelAngle",n):b.pfValue,z=Math.cos(N),I=Math.sin(N),A=(o+s)/2,L=(l+u)/2;if(!m){switch(c.value){case"left":A=s;break;case"right":A=o}switch(d.value){case"top":L=u;break;case"bottom":L=l}}var O=function(e,t){return{x:(e-=A)*z-(t-=L)*I+A,y:e*I+t*z+L}},R=O(o,l),V=O(o,u),F=O(s,l),j=O(s,u);o=Math.min(R.x,V.x,F.x,j.x),s=Math.max(R.x,V.x,F.x,j.x),l=Math.min(R.y,V.y,F.y,j.y),u=Math.max(R.y,V.y,F.y,j.y)}var q=D+"Rot",Y=T[q]=T[q]||{};Y.x1=o,Y.y1=l,Y.x2=s,Y.y2=u,Y.w=s-o,Y.h=u-l,Wa(e,o,l,s,u),Wa(i.labelBounds.all,o,l,s,u)}return e}},Za=function(e,t){var n,r,i,a,o,s,l,u=e._private.cy,c=u.styleEnabled(),d=u.headless(),h=Tt(),p=e._private,f=e.isNode(),g=e.isEdge(),v=p.rstyle,y=f&&c?e.pstyle("bounds-expansion").pfValue:[0],m=function(e){return"none"!==e.pstyle("display").value},b=!c||m(e)&&(!g||m(e.source())&&m(e.target()));if(b){var x=0;c&&t.includeOverlays&&0!==e.pstyle("overlay-opacity").value&&(x=e.pstyle("overlay-padding").value);var w=0;c&&t.includeUnderlays&&0!==e.pstyle("underlay-opacity").value&&(w=e.pstyle("underlay-padding").value);var E=Math.max(x,w),k=0;if(c&&(k=e.pstyle("width").pfValue/2),f&&t.includeNodes){var C=e.position();o=C.x,s=C.y;var S=e.outerWidth()/2,P=e.outerHeight()/2;Wa(h,n=o-S,i=s-P,r=o+S,a=s+P),c&&t.includeOutlines&&function(e,t){if(!t.cy().headless()){var n,r,i,a=t.pstyle("outline-opacity").value,o=t.pstyle("outline-width").value;if(a>0&&o>0){var s=t.pstyle("outline-offset").value,l=t.pstyle("shape").value,u=o+s,c=(e.w+2*u)/e.w,d=(e.h+2*u)/e.h,h=0;["diamond","pentagon","round-triangle"].includes(l)?(c=(e.w+2.4*u)/e.w,h=-u/3.6):["concave-hexagon","rhomboid","right-rhomboid"].includes(l)?c=(e.w+2.4*u)/e.w:"star"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.6*u)/e.h,h=-u/3.8):"triangle"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.4*u)/e.h,h=-u/1.4):"vee"===l&&(c=(e.w+4.4*u)/e.w,d=(e.h+3.8*u)/e.h,h=.5*-u);var p=e.h*d-e.h,f=e.w*c-e.w;if(Nt(e,[Math.ceil(p/2),Math.ceil(f/2)]),0!==h){var g=(r=0,i=h,{x1:(n=e).x1+r,x2:n.x2+r,y1:n.y1+i,y2:n.y2+i,w:n.w,h:n.h});_t(e,g)}}}}(h,e)}else if(g&&t.includeEdges)if(c&&!d){var D=e.pstyle("curve-style").strValue;if(n=Math.min(v.srcX,v.midX,v.tgtX),r=Math.max(v.srcX,v.midX,v.tgtX),i=Math.min(v.srcY,v.midY,v.tgtY),a=Math.max(v.srcY,v.midY,v.tgtY),Wa(h,n-=k,i-=k,r+=k,a+=k),"haystack"===D){var T=v.haystackPts;if(T&&2===T.length){if(n=T[0].x,i=T[0].y,n>(r=T[1].x)){var _=n;n=r,r=_}if(i>(a=T[1].y)){var M=i;i=a,a=M}Wa(h,n-k,i-k,r+k,a+k)}}else if("bezier"===D||"unbundled-bezier"===D||D.endsWith("segments")||D.endsWith("taxi")){var B;switch(D){case"bezier":case"unbundled-bezier":B=v.bezierPts;break;case"segments":case"taxi":case"round-segments":case"round-taxi":B=v.linePts}if(null!=B)for(var N=0;N(r=A.x)){var L=n;n=r,r=L}if((i=I.y)>(a=A.y)){var O=i;i=a,a=O}Wa(h,n-=k,i-=k,r+=k,a+=k)}if(c&&t.includeEdges&&g&&(Ga(h,e,"mid-source"),Ga(h,e,"mid-target"),Ga(h,e,"source"),Ga(h,e,"target")),c)if("yes"===e.pstyle("ghost").value){var R=e.pstyle("ghost-offset-x").pfValue,V=e.pstyle("ghost-offset-y").pfValue;Wa(h,h.x1+R,h.y1+V,h.x2+R,h.y2+V)}var F=p.bodyBounds=p.bodyBounds||{};zt(F,h),Nt(F,y),Bt(F,1),c&&(n=h.x1,r=h.x2,i=h.y1,a=h.y2,Wa(h,n-E,i-E,r+E,a+E));var j=p.overlayBounds=p.overlayBounds||{};zt(j,h),Nt(j,y),Bt(j,1);var q=p.labelBounds=p.labelBounds||{};null!=q.all?((l=q.all).x1=1/0,l.y1=1/0,l.x2=-1/0,l.y2=-1/0,l.w=0,l.h=0):q.all=Tt(),c&&t.includeLabels&&(t.includeMainLabels&&Ua(h,e,null),g&&(t.includeSourceLabels&&Ua(h,e,"source"),t.includeTargetLabels&&Ua(h,e,"target")))}return h.x1=Xa(h.x1),h.y1=Xa(h.y1),h.x2=Xa(h.x2),h.y2=Xa(h.y2),h.w=Xa(h.x2-h.x1),h.h=Xa(h.y2-h.y1),h.w>0&&h.h>0&&b&&(Nt(h,y),Bt(h,1)),h},$a=function(e){var t=0,n=function(e){return(e?1:0)<0&&void 0!==arguments[0]?arguments[0]:mo,t=arguments.length>1?arguments[1]:void 0,n=0;n=0;s--)o(s);return this},xo.removeAllListeners=function(){return this.removeListener("*")},xo.emit=xo.trigger=function(e,t,n){var r=this.listeners,i=r.length;return this.emitting++,y(t)||(t=[t]),ko(this,(function(e,a){null!=n&&(r=[{event:a.event,type:a.type,namespace:a.namespace,callback:n}],i=r.length);for(var o=function(n){var i=r[n];if(i.type===a.type&&(!i.namespace||i.namespace===a.namespace||".*"===i.namespace)&&e.eventMatches(e.context,i,a)){var o=[a];null!=t&&function(e,t){for(var n=0;n1&&!r){var i=this.length-1,a=this[i],o=a._private.data.id;this[i]=void 0,this[e]=a,n.set(o,{ele:a,index:e})}return this.length--,this},unmergeOne:function(e){e=e[0];var t=this._private,n=e._private.data.id,r=t.map.get(n);if(!r)return this;var i=r.index;return this.unmergeAt(i),this},unmerge:function(e){var t=this._private.cy;if(!e)return this;if(e&&g(e)){var n=e;e=t.mutableElements().filter(n)}for(var r=0;r=0;t--){e(this[t])&&this.unmergeAt(t)}return this},map:function(e,t){for(var n=[],r=0;rr&&(r=o,n=a)}return{value:r,ele:n}},min:function(e,t){for(var n,r=1/0,i=0;i=0&&i1&&void 0!==arguments[1])||arguments[1],n=this[0],r=n.cy();if(r.styleEnabled()&&n){this.cleanStyle();var i=n._private.style[e];return null!=i?i:t?r.style().getDefaultProperty(e):null}},numericStyle:function(e){var t=this[0];if(t.cy().styleEnabled()&&t){var n=t.pstyle(e);return void 0!==n.pfValue?n.pfValue:n.value}},numericStyleUnits:function(e){var t=this[0];if(t.cy().styleEnabled())return t?t.pstyle(e).units:void 0},renderedStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=this[0];return n?t.style().getRenderedStyle(n,e):void 0},style:function(e,t){var n=this.cy();if(!n.styleEnabled())return this;var r=n.style();if(m(e)){var i=e;r.applyBypass(this,i,!1),this.emitAndNotify("style")}else if(g(e)){if(void 0===t){var a=this[0];return a?r.getStylePropertyValue(a,e):void 0}r.applyBypass(this,e,t,!1),this.emitAndNotify("style")}else if(void 0===e){var o=this[0];return o?r.getRawStyle(o):void 0}return this},removeStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=t.style();if(void 0===e)for(var r=0;r0&&t.push(c[0]),t.push(s[0])}return this.spawn(t,!0).filter(e)}),"neighborhood"),closedNeighborhood:function(e){return this.neighborhood().add(this).filter(e)},openNeighborhood:function(e){return this.neighborhood(e)}}),Ko.neighbourhood=Ko.neighborhood,Ko.closedNeighbourhood=Ko.closedNeighborhood,Ko.openNeighbourhood=Ko.openNeighborhood,A(Ko,{source:Da((function(e){var t,n=this[0];return n&&(t=n._private.source||n.cy().collection()),t&&e?t.filter(e):t}),"source"),target:Da((function(e){var t,n=this[0];return n&&(t=n._private.target||n.cy().collection()),t&&e?t.filter(e):t}),"target"),sources:$o({attr:"source"}),targets:$o({attr:"target"})}),A(Ko,{edgesWith:Da(Qo(),"edgesWith"),edgesTo:Da(Qo({thisIsSrc:!0}),"edgesTo")}),A(Ko,{connectedEdges:Da((function(e){for(var t=[],n=0;n0);return a},component:function(){var e=this[0];return e.cy().mutableElements().components(e)[0]}}),Ko.componentsOf=Ko.components;var es=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(void 0!==e){var i=new Ze,a=!1;if(t){if(t.length>0&&m(t[0])&&!E(t[0])){a=!0;for(var o=[],s=new Qe,l=0,u=t.length;l0&&void 0!==arguments[0])||arguments[0],r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this,a=i.cy(),o=a._private,s=[],l=[],u=0,c=i.length;u0){for(var R=e.length===i.length?i:new es(a,e),V=0;V0&&void 0!==arguments[0])||arguments[0],t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this,r=[],i={},a=n._private.cy;function o(e){for(var t=e._private.edges,n=0;n0&&(e?D.emitAndNotify("remove"):t&&D.emit("remove"));for(var T=0;T1e-4&&Math.abs(s.v)>1e-4;);return a?function(e){return u[e*(u.length-1)|0]}:c}}(),is=function(e,t,n,r){var i=function(e,t,n,r){var i=4,a=.001,o=1e-7,s=10,l=11,u=1/(l-1),c="undefined"!=typeof Float32Array;if(4!==arguments.length)return!1;for(var d=0;d<4;++d)if("number"!=typeof arguments[d]||isNaN(arguments[d])||!isFinite(arguments[d]))return!1;e=Math.min(e,1),n=Math.min(n,1),e=Math.max(e,0),n=Math.max(n,0);var h=c?new Float32Array(l):new Array(l);function p(e,t){return 1-3*t+3*e}function f(e,t){return 3*t-6*e}function g(e){return 3*e}function v(e,t,n){return((p(t,n)*e+f(t,n))*e+g(t))*e}function y(e,t,n){return 3*p(t,n)*e*e+2*f(t,n)*e+g(t)}function m(t,r){for(var a=0;a0?i=l:r=l}while(Math.abs(a)>o&&++u=a?m(t,s):0===c?s:x(t,r,r+u)}var E=!1;function k(){E=!0,e===t&&n===r||b()}var C=function(i){return E||k(),e===t&&n===r?i:0===i?0:1===i?1:v(w(i),t,r)};C.getControlPoints=function(){return[{x:e,y:t},{x:n,y:r}]};var S="generateBezier("+[e,t,n,r]+")";return C.toString=function(){return S},C}(e,t,n,r);return function(e,t,n){return e+(t-e)*i(n)}},as={linear:function(e,t,n){return e+(t-e)*n},ease:is(.25,.1,.25,1),"ease-in":is(.42,0,1,1),"ease-out":is(0,0,.58,1),"ease-in-out":is(.42,0,.58,1),"ease-in-sine":is(.47,0,.745,.715),"ease-out-sine":is(.39,.575,.565,1),"ease-in-out-sine":is(.445,.05,.55,.95),"ease-in-quad":is(.55,.085,.68,.53),"ease-out-quad":is(.25,.46,.45,.94),"ease-in-out-quad":is(.455,.03,.515,.955),"ease-in-cubic":is(.55,.055,.675,.19),"ease-out-cubic":is(.215,.61,.355,1),"ease-in-out-cubic":is(.645,.045,.355,1),"ease-in-quart":is(.895,.03,.685,.22),"ease-out-quart":is(.165,.84,.44,1),"ease-in-out-quart":is(.77,0,.175,1),"ease-in-quint":is(.755,.05,.855,.06),"ease-out-quint":is(.23,1,.32,1),"ease-in-out-quint":is(.86,0,.07,1),"ease-in-expo":is(.95,.05,.795,.035),"ease-out-expo":is(.19,1,.22,1),"ease-in-out-expo":is(1,0,0,1),"ease-in-circ":is(.6,.04,.98,.335),"ease-out-circ":is(.075,.82,.165,1),"ease-in-out-circ":is(.785,.135,.15,.86),spring:function(e,t,n){if(0===n)return as.linear;var r=rs(e,t,n);return function(e,t,n){return e+(t-e)*r(n)}},"cubic-bezier":is};function os(e,t,n,r,i){if(1===r)return n;if(t===n)return n;var a=i(t,n,r);return null==e||((e.roundValue||e.color)&&(a=Math.round(a)),void 0!==e.min&&(a=Math.max(a,e.min)),void 0!==e.max&&(a=Math.min(a,e.max))),a}function ss(e,t){return null!=e.pfValue||null!=e.value?null==e.pfValue||null!=t&&"%"===t.type.units?e.value:e.pfValue:e}function ls(e,t,n,r,i){var a=null!=i?i.type:null;n<0?n=0:n>1&&(n=1);var o=ss(e,i),s=ss(t,i);if(b(o)&&b(s))return os(a,o,s,n,r);if(y(o)&&y(s)){for(var l=[],u=0;u0?("spring"===d&&h.push(o.duration),o.easingImpl=as[d].apply(null,h)):o.easingImpl=as[d]}var p,f=o.easingImpl;if(p=0===o.duration?1:(n-l)/o.duration,o.applying&&(p=o.progress),p<0?p=0:p>1&&(p=1),null==o.delay){var v=o.startPosition,y=o.position;if(y&&i&&!e.locked()){var m={};cs(v.x,y.x)&&(m.x=ls(v.x,y.x,p,f)),cs(v.y,y.y)&&(m.y=ls(v.y,y.y,p,f)),e.position(m)}var b=o.startPan,x=o.pan,w=a.pan,E=null!=x&&r;E&&(cs(b.x,x.x)&&(w.x=ls(b.x,x.x,p,f)),cs(b.y,x.y)&&(w.y=ls(b.y,x.y,p,f)),e.emit("pan"));var k=o.startZoom,C=o.zoom,S=null!=C&&r;S&&(cs(k,C)&&(a.zoom=Dt(a.minZoom,ls(k,C,p,f),a.maxZoom)),e.emit("zoom")),(E||S)&&e.emit("viewport");var P=o.style;if(P&&P.length>0&&i){for(var D=0;D=0;t--){(0,e[t])()}e.splice(0,e.length)},c=a.length-1;c>=0;c--){var d=a[c],h=d._private;h.stopped?(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.frames)):(h.playing||h.applying)&&(h.playing&&h.applying&&(h.applying=!1),h.started||ds(0,d,e),us(t,d,e,n),h.applying&&(h.applying=!1),u(h.frames),null!=h.step&&h.step(e),d.completed()&&(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.completes)),s=!0)}return n||0!==a.length||0!==o.length||r.push(t),s}for(var a=!1,o=0;o0?t.notify("draw",n):t.notify("draw")),n.unmerge(r),t.emit("step")}var ps={animate:Vi.animate(),animation:Vi.animation(),animated:Vi.animated(),clearQueue:Vi.clearQueue(),delay:Vi.delay(),delayAnimation:Vi.delayAnimation(),stop:Vi.stop(),addToAnimationPool:function(e){this.styleEnabled()&&this._private.aniEles.merge(e)},stopAnimationLoop:function(){this._private.animationsRunning=!1},startAnimationLoop:function(){var e=this;if(e._private.animationsRunning=!0,e.styleEnabled()){var t=e.renderer();t&&t.beforeRender?t.beforeRender((function(t,n){hs(n,e)}),t.beforeRenderPriorities.animations):function t(){e._private.animationsRunning&&be((function(n){hs(n,e),t()}))}()}}},fs={qualifierCompare:function(e,t){return null==e||null==t?null==e&&null==t:e.sameText(t)},eventMatches:function(e,t,n){var r=t.qualifier;return null==r||e!==n.target&&E(n.target)&&r.matches(n.target)},addEventFields:function(e,t){t.cy=e,t.target=e},callbackContext:function(e,t,n){return null!=t.qualifier?n.target:e}},gs=function(e){return g(e)?new Ea(e):e},vs={createEmitter:function(){var e=this._private;return e.emitter||(e.emitter=new bo(fs,this)),this},emitter:function(){return this._private.emitter},on:function(e,t,n){return this.emitter().on(e,gs(t),n),this},removeListener:function(e,t,n){return this.emitter().removeListener(e,gs(t),n),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},one:function(e,t,n){return this.emitter().one(e,gs(t),n),this},once:function(e,t,n){return this.emitter().one(e,gs(t),n),this},emit:function(e,t){return this.emitter().emit(e,t),this},emitAndNotify:function(e,t){return this.emit(e),this.notify(e,t),this}};Vi.eventAliasesOn(vs);var ys={png:function(e){return e=e||{},this._private.renderer.png(e)},jpg:function(e){var t=this._private.renderer;return(e=e||{}).bg=e.bg||"#fff",t.jpg(e)}};ys.jpeg=ys.jpg;var ms={layout:function(e){if(null!=e)if(null!=e.name){var t=e.name,n=this.extension("layout",t);if(null!=n){var r;r=g(e.eles)?this.$(e.eles):null!=e.eles?e.eles:this.$();var i=new n(A({},e,{cy:this,eles:r}));return i}Re("No such layout `"+t+"` found. Did you forget to import it and `cytoscape.use()` it?")}else Re("A `name` must be specified to make a layout");else Re("Layout options must be specified to make a layout")}};ms.createLayout=ms.makeLayout=ms.layout;var bs={notify:function(e,t){var n=this._private;if(this.batching()){n.batchNotifications=n.batchNotifications||{};var r=n.batchNotifications[e]=n.batchNotifications[e]||this.collection();null!=t&&r.merge(t)}else if(n.notificationsEnabled){var i=this.renderer();!this.destroyed()&&i&&i.notify(e,t)}},notifications:function(e){var t=this._private;return void 0===e?t.notificationsEnabled:(t.notificationsEnabled=!!e,this)},noNotifications:function(e){this.notifications(!1),e(),this.notifications(!0)},batching:function(){return this._private.batchCount>0},startBatch:function(){var e=this._private;return null==e.batchCount&&(e.batchCount=0),0===e.batchCount&&(e.batchStyleEles=this.collection(),e.batchNotifications={}),e.batchCount++,this},endBatch:function(){var e=this._private;if(0===e.batchCount)return this;if(e.batchCount--,0===e.batchCount){e.batchStyleEles.updateStyle();var t=this.renderer();Object.keys(e.batchNotifications).forEach((function(n){var r=e.batchNotifications[n];r.empty()?t.notify(n):t.notify(n,r)}))}return this},batch:function(e){return this.startBatch(),e(),this.endBatch(),this},batchData:function(e){var t=this;return this.batch((function(){for(var n=Object.keys(e),r=0;r0;)e.removeChild(e.childNodes[0]);this._private.renderer=null,this.mutableElements().forEach((function(e){var t=e._private;t.rscratch={},t.rstyle={},t.animation.current=[],t.animation.queue=[]}))},onRender:function(e){return this.on("render",e)},offRender:function(e){return this.off("render",e)}};ws.invalidateDimensions=ws.resize;var Es={collection:function(e,t){return g(e)?this.$(e):w(e)?e.collection():y(e)?(t||(t={}),new es(this,e,t.unique,t.removed)):new es(this)},nodes:function(e){var t=this.$((function(e){return e.isNode()}));return e?t.filter(e):t},edges:function(e){var t=this.$((function(e){return e.isEdge()}));return e?t.filter(e):t},$:function(e){var t=this._private.elements;return e?t.filter(e):t.spawnSelf()},mutableElements:function(){return this._private.elements}};Es.elements=Es.filter=Es.$;var ks={};ks.apply=function(e){for(var t=this._private.cy.collection(),n=0;n0;if(d||c&&h){var p=void 0;d&&h||d?p=l.properties:h&&(p=l.mappedProperties);for(var f=0;f1&&(g=1),s.color){var w=i.valueMin[0],E=i.valueMax[0],k=i.valueMin[1],C=i.valueMax[1],S=i.valueMin[2],P=i.valueMax[2],D=null==i.valueMin[3]?1:i.valueMin[3],T=null==i.valueMax[3]?1:i.valueMax[3],_=[Math.round(w+(E-w)*g),Math.round(k+(C-k)*g),Math.round(S+(P-S)*g),Math.round(D+(T-D)*g)];n={bypass:i.bypass,name:i.name,value:_,strValue:"rgb("+_[0]+", "+_[1]+", "+_[2]+")"}}else{if(!s.number)return!1;var M=i.valueMin+(i.valueMax-i.valueMin)*g;n=this.parse(i.name,M,i.bypass,"mapping")}if(!n)return f(),!1;n.mapping=i,i=n;break;case o.data:for(var B=i.field.split("."),N=d.data,z=0;z0&&a>0){for(var s={},l=!1,u=0;u0?e.delayAnimation(o).play().promise().then(t):t()})).then((function(){return e.animation({style:s,duration:a,easing:e.pstyle("transition-timing-function").value,queue:!1}).play().promise()})).then((function(){n.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1}))}else r.transitioning&&(this.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1)},ks.checkTrigger=function(e,t,n,r,i,a){var o=this.properties[t],s=i(o);null!=s&&s(n,r)&&a(o)},ks.checkZOrderTrigger=function(e,t,n,r){var i=this;this.checkTrigger(e,t,n,r,(function(e){return e.triggersZOrder}),(function(){i._private.cy.notify("zorder",e)}))},ks.checkBoundsTrigger=function(e,t,n,r){this.checkTrigger(e,t,n,r,(function(e){return e.triggersBounds}),(function(i){e.dirtyCompoundBoundsCache(),e.dirtyBoundingBoxCache(),!i.triggersBoundsOfParallelBeziers||"curve-style"!==t||"bezier"!==n&&"bezier"!==r||e.parallelEdges().forEach((function(e){e.isBundledBezier()&&e.dirtyBoundingBoxCache()})),!i.triggersBoundsOfConnectedEdges||"display"!==t||"none"!==n&&"none"!==r||e.connectedEdges().forEach((function(e){e.dirtyBoundingBoxCache()}))}))},ks.checkTriggers=function(e,t,n,r){e.dirtyStyleCache(),this.checkZOrderTrigger(e,t,n,r),this.checkBoundsTrigger(e,t,n,r)};var Cs={applyBypass:function(e,t,n,r){var i=[];if("*"===t||"**"===t){if(void 0!==n)for(var a=0;at.length?i.substr(t.length):""}function o(){n=n.length>r.length?n.substr(r.length):""}for(i=i.replace(/[/][*](\s|.)+?[*][/]/g,"");;){if(i.match(/^\s*$/))break;var s=i.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);if(!s){Fe("Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: "+i);break}t=s[0];var l=s[1];if("core"!==l)if(new Ea(l).invalid){Fe("Skipping parsing of block: Invalid selector found in string stylesheet: "+l),a();continue}var u=s[2],c=!1;n=u;for(var d=[];;){if(n.match(/^\s*$/))break;var h=n.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);if(!h){Fe("Skipping parsing of block: Invalid formatting of style property and value definitions found in:"+u),c=!0;break}r=h[0];var p=h[1],f=h[2];if(this.properties[p])this.parse(p,f)?(d.push({name:p,val:f}),o()):(Fe("Skipping property: Invalid property definition in: "+r),o());else Fe("Skipping property: Invalid property name in: "+r),o()}if(c){a();break}this.selector(l);for(var g=0;g=7&&"d"===t[0]&&(l=new RegExp(o.data.regex).exec(t))){if(n)return!1;var d=o.data;return{name:e,value:l,strValue:""+t,mapped:d,field:l[1],bypass:n}}if(t.length>=10&&"m"===t[0]&&(u=new RegExp(o.mapData.regex).exec(t))){if(n)return!1;if(c.multiple)return!1;var h=o.mapData;if(!c.color&&!c.number)return!1;var p=this.parse(e,u[4]);if(!p||p.mapped)return!1;var f=this.parse(e,u[5]);if(!f||f.mapped)return!1;if(p.pfValue===f.pfValue||p.strValue===f.strValue)return Fe("`"+e+": "+t+"` is not a valid mapper because the output range is zero; converting to `"+e+": "+p.strValue+"`"),this.parse(e,p.strValue);if(c.color){var m=p.value,x=f.value;if(!(m[0]!==x[0]||m[1]!==x[1]||m[2]!==x[2]||m[3]!==x[3]&&(null!=m[3]&&1!==m[3]||null!=x[3]&&1!==x[3])))return!1}return{name:e,value:u,strValue:""+t,mapped:h,field:u[1],fieldMin:parseFloat(u[2]),fieldMax:parseFloat(u[3]),valueMin:p.value,valueMax:f.value,bypass:n}}}if(c.multiple&&"multiple"!==r){var w;if(w=s?t.split(/\s+/):y(t)?t:[t],c.evenMultiple&&w.length%2!=0)return null;for(var E=[],k=[],C=[],S="",P=!1,D=0;D0?" ":"")+T.strValue}return c.validate&&!c.validate(E,k)?null:c.singleEnum&&P?1===E.length&&g(E[0])?{name:e,value:E[0],strValue:E[0],bypass:n}:null:{name:e,value:E,pfValue:C,strValue:S,bypass:n,units:k}}var M,B,N=function(){for(var r=0;rc.max||c.strictMax&&t===c.max))return null;var V={name:e,value:t,strValue:""+t+(I||""),units:I,bypass:n};return c.unitless||"px"!==I&&"em"!==I?V.pfValue=t:V.pfValue="px"!==I&&I?this.getEmSizeInPixels()*t:t,"ms"!==I&&"s"!==I||(V.pfValue="ms"===I?t:1e3*t),"deg"!==I&&"rad"!==I||(V.pfValue="rad"===I?t:(M=t,Math.PI*M/180)),"%"===I&&(V.pfValue=t/100),V}if(c.propList){var F=[],j=""+t;if("none"===j);else{for(var q=j.split(/\s*,\s*|\s+/),Y=0;Y0&&l>0&&!isNaN(n.w)&&!isNaN(n.h)&&n.w>0&&n.h>0)return{zoom:o=(o=(o=Math.min((s-2*t)/n.w,(l-2*t)/n.h))>this._private.maxZoom?this._private.maxZoom:o)=n.minZoom&&(n.maxZoom=t),this},minZoom:function(e){return void 0===e?this._private.minZoom:this.zoomRange({min:e})},maxZoom:function(e){return void 0===e?this._private.maxZoom:this.zoomRange({max:e})},getZoomedViewport:function(e){var t,n,r=this._private,i=r.pan,a=r.zoom,o=!1;if(r.zoomingEnabled||(o=!0),b(e)?n=e:m(e)&&(n=e.level,null!=e.position?t=vt(e.position,a,i):null!=e.renderedPosition&&(t=e.renderedPosition),null==t||r.panningEnabled||(o=!0)),n=(n=n>r.maxZoom?r.maxZoom:n)t.maxZoom||!t.zoomingEnabled?a=!0:(t.zoom=s,i.push("zoom"))}if(r&&(!a||!e.cancelOnFailedZoom)&&t.panningEnabled){var l=e.pan;b(l.x)&&(t.pan.x=l.x,o=!1),b(l.y)&&(t.pan.y=l.y,o=!1),o||i.push("pan")}return i.length>0&&(i.push("viewport"),this.emit(i.join(" ")),this.notify("viewport")),this},center:function(e){var t=this.getCenterPan(e);return t&&(this._private.pan=t,this.emit("pan viewport"),this.notify("viewport")),this},getCenterPan:function(e,t){if(this._private.panningEnabled){if(g(e)){var n=e;e=this.mutableElements().filter(n)}else w(e)||(e=this.mutableElements());if(0!==e.length){var r=e.boundingBox(),i=this.width(),a=this.height();return{x:(i-(t=void 0===t?this._private.zoom:t)*(r.x1+r.x2))/2,y:(a-t*(r.y1+r.y2))/2}}}},reset:function(){return this._private.panningEnabled&&this._private.zoomingEnabled?(this.viewport({pan:{x:0,y:0},zoom:1}),this):this},invalidateSize:function(){this._private.sizeCache=null},size:function(){var e,t,n=this._private,r=n.container,i=this;return n.sizeCache=n.sizeCache||(r?(e=i.window().getComputedStyle(r),t=function(t){return parseFloat(e.getPropertyValue(t))},{width:r.clientWidth-t("padding-left")-t("padding-right"),height:r.clientHeight-t("padding-top")-t("padding-bottom")}):{width:1,height:1})},width:function(){return this.size().width},height:function(){return this.size().height},extent:function(){var e=this._private.pan,t=this._private.zoom,n=this.renderedExtent(),r={x1:(n.x1-e.x)/t,x2:(n.x2-e.x)/t,y1:(n.y1-e.y)/t,y2:(n.y2-e.y)/t};return r.w=r.x2-r.x1,r.h=r.y2-r.y1,r},renderedExtent:function(){var e=this.width(),t=this.height();return{x1:0,y1:0,x2:e,y2:t,w:e,h:t}},multiClickDebounceTime:function(e){return e?(this._private.multiClickDebounceTime=e,this):this._private.multiClickDebounceTime}};Is.centre=Is.center,Is.autolockNodes=Is.autolock,Is.autoungrabifyNodes=Is.autoungrabify;var As={data:Vi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeData:Vi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),scratch:Vi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Vi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0})};As.attr=As.data,As.removeAttr=As.removeData;var Ls=function(e){var t=this,n=(e=A({},e)).container;n&&!x(n)&&x(n[0])&&(n=n[0]);var r=n?n._cyreg:null;(r=r||{})&&r.cy&&(r.cy.destroy(),r={});var i=r.readies=r.readies||[];n&&(n._cyreg=r),r.cy=t;var a=void 0!==l&&void 0!==n&&!e.headless,o=e;o.layout=A({name:a?"grid":"null"},o.layout),o.renderer=A({name:a?"canvas":"null"},o.renderer);var s=function(e,t,n){return void 0!==t?t:void 0!==n?n:e},u=this._private={container:n,ready:!1,options:o,elements:new es(this),listeners:[],aniEles:new es(this),data:o.data||{},scratch:{},layout:null,renderer:null,destroyed:!1,notificationsEnabled:!0,minZoom:1e-50,maxZoom:1e50,zoomingEnabled:s(!0,o.zoomingEnabled),userZoomingEnabled:s(!0,o.userZoomingEnabled),panningEnabled:s(!0,o.panningEnabled),userPanningEnabled:s(!0,o.userPanningEnabled),boxSelectionEnabled:s(!0,o.boxSelectionEnabled),autolock:s(!1,o.autolock,o.autolockNodes),autoungrabify:s(!1,o.autoungrabify,o.autoungrabifyNodes),autounselectify:s(!1,o.autounselectify),styleEnabled:void 0===o.styleEnabled?a:o.styleEnabled,zoom:b(o.zoom)?o.zoom:1,pan:{x:m(o.pan)&&b(o.pan.x)?o.pan.x:0,y:m(o.pan)&&b(o.pan.y)?o.pan.y:0},animation:{current:[],queue:[]},hasCompoundNodes:!1,multiClickDebounceTime:s(250,o.multiClickDebounceTime)};this.createEmitter(),this.selectionType(o.selectionType),this.zoomRange({min:o.minZoom,max:o.maxZoom});u.styleEnabled&&t.setStyle([]);var c=A({},o,o.renderer);t.initRenderer(c);!function(e,t){if(e.some(D))return gr.all(e).then(t);t(e)}([o.style,o.elements],(function(e){var n=e[0],a=e[1];u.styleEnabled&&t.style().append(n),function(e,n,r){t.notifications(!1);var i=t.mutableElements();i.length>0&&i.remove(),null!=e&&(m(e)||y(e))&&t.add(e),t.one("layoutready",(function(e){t.notifications(!0),t.emit(e),t.one("load",n),t.emitAndNotify("load")})).one("layoutstop",(function(){t.one("done",r),t.emit("done")}));var a=A({},t._private.options.layout);a.eles=t.elements(),t.layout(a).run()}(a,(function(){t.startAnimationLoop(),u.ready=!0,v(o.ready)&&t.on("ready",o.ready);for(var e=0;e0,u=Tt(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()});if(w(n.roots))e=n.roots;else if(y(n.roots)){for(var c=[],d=0;d0;){var N=_.shift(),z=T(N,M);if(z)N.outgoers().filter((function(e){return e.isNode()&&i.has(e)})).forEach(B);else if(null===z){Fe("Detected double maximal shift for node `"+N.id()+"`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.");break}}}D();var A=0;if(n.avoidOverlap)for(var L=0;L0&&b[0].length<=3?l/2:0),d=2*Math.PI/b[r].length*i;return 0===r&&1===b[0].length&&(c=1),{x:G+c*Math.cos(d),y:U+c*Math.sin(d)}}return{x:G+(i+1-(a+1)/2)*o,y:(r+1)*s}})),this};var Ys={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,radius:void 0,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Xs(e){this.options=A({},Ys,e)}Xs.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,a=r.nodes().not(":parent");t.sort&&(a=a.sort(t.sort));for(var o,s=Tt(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()}),l=s.x1+s.w/2,u=s.y1+s.h/2,c=(void 0===t.sweep?2*Math.PI-2*Math.PI/a.length:t.sweep)/Math.max(1,a.length-1),d=0,h=0;h1&&t.avoidOverlap){d*=1.75;var v=Math.cos(c)-Math.cos(0),y=Math.sin(c)-Math.sin(0),m=Math.sqrt(d*d/(v*v+y*y));o=Math.max(m,o)}return r.nodes().layoutPositions(this,t,(function(e,n){var r=t.startAngle+n*c*(i?1:-1),a=o*Math.cos(r),s=o*Math.sin(r);return{x:l+a,y:u+s}})),this};var Ws,Hs={fit:!0,padding:30,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,equidistant:!1,minNodeSpacing:10,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,height:void 0,width:void 0,spacingFactor:void 0,concentric:function(e){return e.degree()},levelWidth:function(e){return e.maxDegree()/4},animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Ks(e){this.options=A({},Hs,e)}Ks.prototype.run=function(){for(var e=this.options,t=e,n=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,r=e.cy,i=t.eles,a=i.nodes().not(":parent"),o=Tt(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()}),s=o.x1+o.w/2,l=o.y1+o.h/2,u=[],c=0,d=0;d0)Math.abs(m[0].value-x.value)>=v&&(m=[],y.push(m));m.push(x)}var w=c+t.minNodeSpacing;if(!t.avoidOverlap){var E=y.length>0&&y[0].length>1,k=(Math.min(o.w,o.h)/2-w)/(y.length+E?1:0);w=Math.min(w,k)}for(var C=0,S=0;S1&&t.avoidOverlap){var _=Math.cos(T)-Math.cos(0),M=Math.sin(T)-Math.sin(0),B=Math.sqrt(w*w/(_*_+M*M));C=Math.max(B,C)}P.r=C,C+=w}if(t.equidistant){for(var N=0,z=0,I=0;I=e.numIter)&&(nl(r,e),r.temperature=r.temperature*e.coolingFactor,!(r.temperature=e.animationThreshold&&a(),be(t)):(fl(r,e),s())}()}else{for(;u;)u=o(l),l++;fl(r,e),s()}return this},Us.prototype.stop=function(){return this.stopped=!0,this.thread&&this.thread.stop(),this.emit("layoutstop"),this},Us.prototype.destroy=function(){return this.thread&&this.thread.stop(),this};var Zs=function(e,t,n){for(var r=n.eles.edges(),i=n.eles.nodes(),a=Tt(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:e.width(),h:e.height()}),o={isCompound:e.hasCompoundNodes(),layoutNodes:[],idToIndex:{},nodeSize:i.size(),graphSet:[],indexToGraph:[],layoutEdges:[],edgeSize:r.size(),temperature:n.initialTemp,clientWidth:a.w,clientHeight:a.h,boundingBox:a},s=n.eles.components(),l={},u=0;u0){o.graphSet.push(E);for(u=0;ur.count?0:r.graph},Qs=function e(t,n,r,i){var a=i.graphSet[r];if(-10)var s=(u=r.nodeOverlap*o)*i/(g=Math.sqrt(i*i+a*a)),l=u*a/g;else{var u,c=sl(e,i,a),d=sl(t,-1*i,-1*a),h=d.x-c.x,p=d.y-c.y,f=h*h+p*p,g=Math.sqrt(f);s=(u=(e.nodeRepulsion+t.nodeRepulsion)/f)*h/g,l=u*p/g}e.isLocked||(e.offsetX-=s,e.offsetY-=l),t.isLocked||(t.offsetX+=s,t.offsetY+=l)}},ol=function(e,t,n,r){if(n>0)var i=e.maxX-t.minX;else i=t.maxX-e.minX;if(r>0)var a=e.maxY-t.minY;else a=t.maxY-e.minY;return i>=0&&a>=0?Math.sqrt(i*i+a*a):0},sl=function(e,t,n){var r=e.positionX,i=e.positionY,a=e.height||1,o=e.width||1,s=n/t,l=a/o,u={};return 0===t&&0n?(u.x=r,u.y=i+a/2,u):0t&&-1*l<=s&&s<=l?(u.x=r-o/2,u.y=i-o*n/2/t,u):0=l)?(u.x=r+a*t/2/n,u.y=i+a/2,u):0>n&&(s<=-1*l||s>=l)?(u.x=r-a*t/2/n,u.y=i-a/2,u):u},ll=function(e,t){for(var n=0;n1){var f=t.gravity*d/p,g=t.gravity*h/p;c.offsetX+=f,c.offsetY+=g}}}}},cl=function(e,t){var n=[],r=0,i=-1;for(n.push.apply(n,e.graphSet[0]),i+=e.graphSet[0].length;r<=i;){var a=n[r++],o=e.idToIndex[a],s=e.layoutNodes[o],l=s.children;if(0n)var i={x:n*e/r,y:n*t/r};else i={x:e,y:t};return i},pl=function e(t,n){var r=t.parentId;if(null!=r){var i=n.layoutNodes[n.idToIndex[r]],a=!1;return(null==i.maxX||t.maxX+i.padRight>i.maxX)&&(i.maxX=t.maxX+i.padRight,a=!0),(null==i.minX||t.minX-i.padLefti.maxY)&&(i.maxY=t.maxY+i.padBottom,a=!0),(null==i.minY||t.minY-i.padTopf&&(d+=p+t.componentSpacing,c=0,h=0,p=0)}}},gl={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,avoidOverlapPadding:10,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,condense:!1,rows:void 0,cols:void 0,position:function(e){},sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function vl(e){this.options=A({},gl,e)}vl.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=r.nodes().not(":parent");t.sort&&(i=i.sort(t.sort));var a=Tt(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()});if(0===a.h||0===a.w)r.nodes().layoutPositions(this,t,(function(e){return{x:a.x1,y:a.y1}}));else{var o=i.size(),s=Math.sqrt(o*a.h/a.w),l=Math.round(s),u=Math.round(a.w/a.h*s),c=function(e){if(null==e)return Math.min(l,u);Math.min(l,u)==l?l=e:u=e},d=function(e){if(null==e)return Math.max(l,u);Math.max(l,u)==l?l=e:u=e},h=t.rows,p=null!=t.cols?t.cols:t.columns;if(null!=h&&null!=p)l=h,u=p;else if(null!=h&&null==p)l=h,u=Math.ceil(o/l);else if(null==h&&null!=p)u=p,l=Math.ceil(o/u);else if(u*l>o){var f=c(),g=d();(f-1)*g>=o?c(f-1):(g-1)*f>=o&&d(g-1)}else for(;u*l=o?d(y+1):c(v+1)}var m=a.w/u,b=a.h/l;if(t.condense&&(m=0,b=0),t.avoidOverlap)for(var x=0;x=u&&(B=0,M++)},z={},I=0;I(r=jt(e,t,x[w],x[w+1],x[w+2],x[w+3])))return v(n,r),!0}else if("bezier"===a.edgeType||"multibezier"===a.edgeType||"self"===a.edgeType||"compound"===a.edgeType)for(x=a.allpts,w=0;w+5(r=Ft(e,t,x[w],x[w+1],x[w+2],x[w+3],x[w+4],x[w+5])))return v(n,r),!0;m=m||i.source,b=b||i.target;var E=o.getArrowWidth(l,c),k=[{name:"source",x:a.arrowStartX,y:a.arrowStartY,angle:a.srcArrowAngle},{name:"target",x:a.arrowEndX,y:a.arrowEndY,angle:a.tgtArrowAngle},{name:"mid-source",x:a.midX,y:a.midY,angle:a.midsrcArrowAngle},{name:"mid-target",x:a.midX,y:a.midY,angle:a.midtgtArrowAngle}];for(w=0;w0&&(y(m),y(b))}function b(e,t,n){return Ge(e,t,n)}function x(n,r){var i,a=n._private,o=f;i=r?r+"-":"",n.boundingBox();var s=a.labelBounds[r||"main"],l=n.pstyle(i+"label").value;if("yes"===n.pstyle("text-events").strValue&&l){var u=b(a.rscratch,"labelX",r),c=b(a.rscratch,"labelY",r),d=b(a.rscratch,"labelAngle",r),h=n.pstyle(i+"text-margin-x").pfValue,p=n.pstyle(i+"text-margin-y").pfValue,g=s.x1-o-h,y=s.x2+o-h,m=s.y1-o-p,x=s.y2+o-p;if(d){var w=Math.cos(d),E=Math.sin(d),k=function(e,t){return{x:(e-=u)*w-(t-=c)*E+u,y:e*E+t*w+c}},C=k(g,m),S=k(g,x),P=k(y,m),D=k(y,x),T=[C.x+h,C.y+p,P.x+h,P.y+p,D.x+h,D.y+p,S.x+h,S.y+p];if(qt(e,t,T))return v(n),!0}else if(At(s,e,t))return v(n),!0}}n&&(l=l.interactive);for(var w=l.length-1;w>=0;w--){var E=l[w];E.isNode()?y(E)||x(E):m(E)||x(E)||x(E,"source")||x(E,"target")}return u},getAllInBox:function(e,t,n,r){for(var i,a,o=this.getCachedZSortedEles().interactive,s=[],l=Math.min(e,n),u=Math.max(e,n),c=Math.min(t,r),d=Math.max(t,r),h=Tt({x1:e=l,y1:t=c,x2:n=u,y2:r=d}),p=0;p0?-(Math.PI-a.ang):Math.PI+a.ang),Ul(t,n,Gl),Nl=Kl.nx*Gl.ny-Kl.ny*Gl.nx,zl=Kl.nx*Gl.nx-Kl.ny*-Gl.ny,Ll=Math.asin(Math.max(-1,Math.min(1,Nl))),Math.abs(Ll)<1e-6)return Ml=t.x,Bl=t.y,void(Rl=Fl=0);Il=1,Al=!1,zl<0?Ll<0?Ll=Math.PI+Ll:(Ll=Math.PI-Ll,Il=-1,Al=!0):Ll>0&&(Il=-1,Al=!0),Fl=void 0!==t.radius?t.radius:r,Ol=Ll/2,jl=Math.min(Kl.len/2,Gl.len/2),i?(Vl=Math.abs(Math.cos(Ol)*Fl/Math.sin(Ol)))>jl?(Vl=jl,Rl=Math.abs(Vl*Math.sin(Ol)/Math.cos(Ol))):Rl=Fl:(Vl=Math.min(jl,Fl),Rl=Math.abs(Vl*Math.sin(Ol)/Math.cos(Ol))),Xl=t.x+Gl.nx*Vl,Wl=t.y+Gl.ny*Vl,Ml=Xl-Gl.ny*Rl*Il,Bl=Wl+Gl.nx*Rl*Il,ql=t.x+Kl.nx*Vl,Yl=t.y+Kl.ny*Vl,Hl=t};function $l(e,t){0===t.radius?e.lineTo(t.cx,t.cy):e.arc(t.cx,t.cy,t.radius,t.startAngle,t.endAngle,t.counterClockwise)}function Ql(e,t,n,r){var i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];return 0===r||0===t.radius?{cx:t.x,cy:t.y,radius:0,startX:t.x,startY:t.y,stopX:t.x,stopY:t.y,startAngle:void 0,endAngle:void 0,counterClockwise:void 0}:(Zl(e,t,n,r,i),{cx:Ml,cy:Bl,radius:Rl,startX:ql,startY:Yl,stopX:Xl,stopY:Wl,startAngle:Kl.ang+Math.PI/2*Il,endAngle:Gl.ang-Math.PI/2*Il,counterClockwise:Al})}var Jl={};function eu(e){var t=[];if(null!=e){for(var n=0;n0?Math.max(e-t,0):Math.min(e+t,0)},w=x(m,v),E=x(b,y),k=!1;"auto"===c?u=Math.abs(w)>Math.abs(E)?"horizontal":"vertical":"upward"===c||"downward"===c?(u="vertical",k=!0):"leftward"!==c&&"rightward"!==c||(u="horizontal",k=!0);var C,S="vertical"===u,P=S?E:w,D=S?b:m,T=wt(D),_=!1;(k&&(h||f)||!("downward"===c&&D<0||"upward"===c&&D>0||"leftward"===c&&D>0||"rightward"===c&&D<0)||(P=(T*=-1)*Math.abs(P),_=!0),h)?C=(p<0?1+p:p)*P:C=(p<0?P:0)+p*T;var M=function(e){return Math.abs(e)=Math.abs(P)},B=M(C),N=M(Math.abs(P)-Math.abs(C));if((B||N)&&!_)if(S){var z=Math.abs(D)<=a/2,I=Math.abs(m)<=o/2;if(z){var A=(r.x1+r.x2)/2,L=r.y1,O=r.y2;n.segpts=[A,L,A,O]}else if(I){var R=(r.y1+r.y2)/2,V=r.x1,F=r.x2;n.segpts=[V,R,F,R]}else n.segpts=[r.x1,r.y2]}else{var j=Math.abs(D)<=i/2,q=Math.abs(b)<=s/2;if(j){var Y=(r.y1+r.y2)/2,X=r.x1,W=r.x2;n.segpts=[X,Y,W,Y]}else if(q){var H=(r.x1+r.x2)/2,K=r.y1,G=r.y2;n.segpts=[H,K,H,G]}else n.segpts=[r.x2,r.y1]}else if(S){var U=r.y1+C+(l?a/2*T:0),Z=r.x1,$=r.x2;n.segpts=[Z,U,$,U]}else{var Q=r.x1+C+(l?i/2*T:0),J=r.y1,ee=r.y2;n.segpts=[Q,J,Q,ee]}if(n.isRound){var te=e.pstyle("taxi-radius").value,ne="arc-radius"===e.pstyle("radius-type").value[0];n.radii=new Array(n.segpts.length/2).fill(te),n.isArcRadius=new Array(n.segpts.length/2).fill(ne)}},Jl.tryToCorrectInvalidPoints=function(e,t){var n=e._private.rscratch;if("bezier"===n.edgeType){var r=t.srcPos,i=t.tgtPos,a=t.srcW,o=t.srcH,s=t.tgtW,l=t.tgtH,u=t.srcShape,c=t.tgtShape,d=t.srcCornerRadius,h=t.tgtCornerRadius,p=t.srcRs,f=t.tgtRs,g=!b(n.startX)||!b(n.startY),v=!b(n.arrowStartX)||!b(n.arrowStartY),y=!b(n.endX)||!b(n.endY),m=!b(n.arrowEndX)||!b(n.arrowEndY),x=3*(this.getArrowWidth(e.pstyle("width").pfValue,e.pstyle("arrow-scale").value)*this.arrowShapeWidth),w=Et({x:n.ctrlpts[0],y:n.ctrlpts[1]},{x:n.startX,y:n.startY}),E=wh.poolIndex()){var p=d;d=h,h=p}var f=s.srcPos=d.position(),g=s.tgtPos=h.position(),v=s.srcW=d.outerWidth(),y=s.srcH=d.outerHeight(),m=s.tgtW=h.outerWidth(),x=s.tgtH=h.outerHeight(),w=s.srcShape=n.nodeShapes[t.getNodeShape(d)],E=s.tgtShape=n.nodeShapes[t.getNodeShape(h)],k=s.srcCornerRadius="auto"===d.pstyle("corner-radius").value?"auto":d.pstyle("corner-radius").pfValue,C=s.tgtCornerRadius="auto"===h.pstyle("corner-radius").value?"auto":h.pstyle("corner-radius").pfValue,S=s.tgtRs=h._private.rscratch,P=s.srcRs=d._private.rscratch;s.dirCounts={north:0,west:0,south:0,east:0,northwest:0,southwest:0,northeast:0,southeast:0};for(var D=0;D0){var H=u,K=kt(H,mt(t)),G=kt(H,mt(W)),U=K;if(G2)kt(H,{x:W[2],y:W[3]})0){var le=c,ue=kt(le,mt(t)),ce=kt(le,mt(se)),de=ue;if(ce2)kt(le,{x:se[2],y:se[3]})=c||b){d={cp:v,segment:m};break}}if(d)break}var x=d.cp,w=d.segment,E=(c-p)/w.length,k=w.t1-w.t0,C=u?w.t0+k*E:w.t1-k*E;C=Dt(0,C,1),t=Pt(x.p0,x.p1,x.p2,C),l=function(e,t,n,r){var i=Dt(0,r-.001,1),a=Dt(0,r+.001,1),o=Pt(e,t,n,i),s=Pt(e,t,n,a);return ou(o,s)}(x.p0,x.p1,x.p2,C);break;case"straight":case"segments":case"haystack":for(var S,P,D,T,_=0,M=r.allpts.length,B=0;B+3=c));B+=2);var N=(c-P)/S;N=Dt(0,N,1),t=function(e,t,n,r){var i=t.x-e.x,a=t.y-e.y,o=Et(e,t),s=i/o,l=a/o;return n=null==n?0:n,r=null!=r?r:n*o,{x:e.x+s*r,y:e.y+l*r}}(D,T,N),l=ou(D,T)}o("labelX",s,t.x),o("labelY",s,t.y),o("labelAutoAngle",s,l)}};l("source"),l("target"),this.applyLabelDimensions(e)}},iu.applyLabelDimensions=function(e){this.applyPrefixedLabelDimensions(e),e.isEdge()&&(this.applyPrefixedLabelDimensions(e,"source"),this.applyPrefixedLabelDimensions(e,"target"))},iu.applyPrefixedLabelDimensions=function(e,t){var n=e._private,r=this.getLabelText(e,t),i=this.calculateLabelDimensions(e,r),a=e.pstyle("line-height").pfValue,o=e.pstyle("text-wrap").strValue,s=Ge(n.rscratch,"labelWrapCachedLines",t)||[],l="wrap"!==o?1:Math.max(s.length,1),u=i.height/l,c=u*a,d=i.width,h=i.height+(l-1)*(a-1)*u;Ue(n.rstyle,"labelWidth",t,d),Ue(n.rscratch,"labelWidth",t,d),Ue(n.rstyle,"labelHeight",t,h),Ue(n.rscratch,"labelHeight",t,h),Ue(n.rscratch,"labelLineHeight",t,c)},iu.getLabelText=function(e,t){var n=e._private,r=t?t+"-":"",i=e.pstyle(r+"label").strValue,a=e.pstyle("text-transform").value,o=function(e,r){return r?(Ue(n.rscratch,e,t,r),r):Ge(n.rscratch,e,t)};if(!i)return"";"none"==a||("uppercase"==a?i=i.toUpperCase():"lowercase"==a&&(i=i.toLowerCase()));var s=e.pstyle("text-wrap").value;if("wrap"===s){var l=o("labelKey");if(null!=l&&o("labelWrapKey")===l)return o("labelWrapCachedText");for(var u=i.split("\n"),c=e.pstyle("text-max-width").pfValue,d="anywhere"===e.pstyle("text-overflow-wrap").value,h=[],p=/[\s\u200b]+/,f=d?"":" ",g=0;gc){for(var b=v.split(p),x="",w=0;wC)break;S+=i[D],D===i.length-1&&(P=!0)}return P||(S+="…"),S}return i},iu.getLabelJustification=function(e){var t=e.pstyle("text-justification").strValue,n=e.pstyle("text-halign").strValue;if("auto"!==t)return t;if(!e.isNode())return"center";switch(n){case"left":return"right";case"right":return"left";default:return"center"}},iu.calculateLabelDimensions=function(e,t){var n=De(t,e._private.labelDimsKey),r=this.labelDimCache||(this.labelDimCache=[]),i=r[n];if(null!=i)return i;var a=e.pstyle("font-style").strValue,o=e.pstyle("font-size").pfValue,s=e.pstyle("font-family").strValue,l=e.pstyle("font-weight").strValue,u=this.labelCalcCanvas,c=this.labelCalcCanvasContext;if(!u){u=this.labelCalcCanvas=document.createElement("canvas"),c=this.labelCalcCanvasContext=u.getContext("2d");var d=u.style;d.position="absolute",d.left="-9999px",d.top="-9999px",d.zIndex="-1",d.visibility="hidden",d.pointerEvents="none"}c.font="".concat(a," ").concat(l," ").concat(o,"px ").concat(s);for(var h=0,p=0,f=t.split("\n"),g=0;g1&&void 0!==arguments[1])||arguments[1];if(t.merge(e),n)for(var r=0;r=e.desktopTapThreshold2}var D=i(t);v&&(e.hoverData.tapholdCancelled=!0);n=!0,r(g,["mousemove","vmousemove","tapdrag"],t,{x:c[0],y:c[1]});var T=function(){e.data.bgActivePosistion=void 0,e.hoverData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:c[0],y:c[1]}}),f[4]=1,e.hoverData.selecting=!0,e.redrawHint("select",!0),e.redraw()};if(3===e.hoverData.which){if(v){var _={originalEvent:t,type:"cxtdrag",position:{x:c[0],y:c[1]}};m?m.emit(_):o.emit(_),e.hoverData.cxtDragged=!0,e.hoverData.cxtOver&&g===e.hoverData.cxtOver||(e.hoverData.cxtOver&&e.hoverData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:c[0],y:c[1]}}),e.hoverData.cxtOver=g,g&&g.emit({originalEvent:t,type:"cxtdragover",position:{x:c[0],y:c[1]}}))}}else if(e.hoverData.dragging){if(n=!0,o.panningEnabled()&&o.userPanningEnabled()){var M;if(e.hoverData.justStartedPan){var B=e.hoverData.mdownPos;M={x:(c[0]-B[0])*s,y:(c[1]-B[1])*s},e.hoverData.justStartedPan=!1}else M={x:x[0]*s,y:x[1]*s};o.panBy(M),o.emit("dragpan"),e.hoverData.dragged=!0}c=e.projectIntoViewport(t.clientX,t.clientY)}else if(1!=f[4]||null!=m&&!m.pannable()){if(m&&m.pannable()&&m.active()&&m.unactivate(),m&&m.grabbed()||g==y||(y&&r(y,["mouseout","tapdragout"],t,{x:c[0],y:c[1]}),g&&r(g,["mouseover","tapdragover"],t,{x:c[0],y:c[1]}),e.hoverData.last=g),m)if(v){if(o.boxSelectionEnabled()&&D)m&&m.grabbed()&&(d(w),m.emit("freeon"),w.emit("free"),e.dragData.didDrag&&(m.emit("dragfreeon"),w.emit("dragfree"))),T();else if(m&&m.grabbed()&&e.nodeIsDraggable(m)){var N=!e.dragData.didDrag;N&&e.redrawHint("eles",!0),e.dragData.didDrag=!0,e.hoverData.draggingEles||u(w,{inDragLayer:!0});var z={x:0,y:0};if(b(x[0])&&b(x[1])&&(z.x+=x[0],z.y+=x[1],N)){var I=e.hoverData.dragDelta;I&&b(I[0])&&b(I[1])&&(z.x+=I[0],z.y+=I[1])}e.hoverData.draggingEles=!0,w.silentShift(z).emit("position drag"),e.redrawHint("drag",!0),e.redraw()}}else!function(){var t=e.hoverData.dragDelta=e.hoverData.dragDelta||[];0===t.length?(t.push(x[0]),t.push(x[1])):(t[0]+=x[0],t[1]+=x[1])}();n=!0}else if(v){if(e.hoverData.dragging||!o.boxSelectionEnabled()||!D&&o.panningEnabled()&&o.userPanningEnabled()){if(!e.hoverData.selecting&&o.panningEnabled()&&o.userPanningEnabled()){a(m,e.hoverData.downs)&&(e.hoverData.dragging=!0,e.hoverData.justStartedPan=!0,f[4]=0,e.data.bgActivePosistion=mt(h),e.redrawHint("select",!0),e.redraw())}}else T();m&&m.pannable()&&m.active()&&m.unactivate()}return f[2]=c[0],f[3]=c[1],n?(t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),!1):void 0}}),!1),e.registerBinding(t,"mouseup",(function(t){if(e.hoverData.capture){e.hoverData.capture=!1;var a=e.cy,o=e.projectIntoViewport(t.clientX,t.clientY),s=e.selection,l=e.findNearestElement(o[0],o[1],!0,!1),u=e.dragData.possibleDragElements,c=e.hoverData.down,h=i(t);if(e.data.bgActivePosistion&&(e.redrawHint("select",!0),e.redraw()),e.hoverData.tapholdCancelled=!0,e.data.bgActivePosistion=void 0,c&&c.unactivate(),3===e.hoverData.which){var p={originalEvent:t,type:"cxttapend",position:{x:o[0],y:o[1]}};if(c?c.emit(p):a.emit(p),!e.hoverData.cxtDragged){var f={originalEvent:t,type:"cxttap",position:{x:o[0],y:o[1]}};c?c.emit(f):a.emit(f)}e.hoverData.cxtDragged=!1,e.hoverData.which=null}else if(1===e.hoverData.which){if(r(l,["mouseup","tapend","vmouseup"],t,{x:o[0],y:o[1]}),e.dragData.didDrag||e.hoverData.dragged||e.hoverData.selecting||e.hoverData.isOverThresholdDrag||(r(c,["click","tap","vclick"],t,{x:o[0],y:o[1]}),x=!1,t.timeStamp-w<=a.multiClickDebounceTime()?(m&&clearTimeout(m),x=!0,w=null,r(c,["dblclick","dbltap","vdblclick"],t,{x:o[0],y:o[1]})):(m=setTimeout((function(){x||r(c,["oneclick","onetap","voneclick"],t,{x:o[0],y:o[1]})}),a.multiClickDebounceTime()),w=t.timeStamp)),null!=c||e.dragData.didDrag||e.hoverData.selecting||e.hoverData.dragged||i(t)||(a.$(n).unselect(["tapunselect"]),u.length>0&&e.redrawHint("eles",!0),e.dragData.possibleDragElements=u=a.collection()),l!=c||e.dragData.didDrag||e.hoverData.selecting||null!=l&&l._private.selectable&&(e.hoverData.dragging||("additive"===a.selectionType()||h?l.selected()?l.unselect(["tapunselect"]):l.select(["tapselect"]):h||(a.$(n).unmerge(l).unselect(["tapunselect"]),l.select(["tapselect"]))),e.redrawHint("eles",!0)),e.hoverData.selecting){var g=a.collection(e.getAllInBox(s[0],s[1],s[2],s[3]));e.redrawHint("select",!0),g.length>0&&e.redrawHint("eles",!0),a.emit({type:"boxend",originalEvent:t,position:{x:o[0],y:o[1]}});var v=function(e){return e.selectable()&&!e.selected()};"additive"===a.selectionType()||h||a.$(n).unmerge(g).unselect(),g.emit("box").stdFilter(v).select().emit("boxselect"),e.redraw()}if(e.hoverData.dragging&&(e.hoverData.dragging=!1,e.redrawHint("select",!0),e.redrawHint("eles",!0),e.redraw()),!s[4]){e.redrawHint("drag",!0),e.redrawHint("eles",!0);var y=c&&c.grabbed();d(u),y&&(c.emit("freeon"),u.emit("free"),e.dragData.didDrag&&(c.emit("dragfreeon"),u.emit("dragfree")))}}s[4]=0,e.hoverData.down=null,e.hoverData.cxtStarted=!1,e.hoverData.draggingEles=!1,e.hoverData.selecting=!1,e.hoverData.isOverThresholdDrag=!1,e.dragData.didDrag=!1,e.hoverData.dragged=!1,e.hoverData.dragDelta=[],e.hoverData.mdownPos=null,e.hoverData.mdownGPos=null}}),!1);var k,C,S,P,D,T,_,M,B,N,z,I,A,L=function(t){if(!e.scrollingPage){var n=e.cy,r=n.zoom(),i=n.pan(),a=e.projectIntoViewport(t.clientX,t.clientY),o=[a[0]*r+i.x,a[1]*r+i.y];if(e.hoverData.draggingEles||e.hoverData.dragging||e.hoverData.cxtStarted||0!==e.selection[4])t.preventDefault();else if(n.panningEnabled()&&n.userPanningEnabled()&&n.zoomingEnabled()&&n.userZoomingEnabled()){var s;t.preventDefault(),e.data.wheelZooming=!0,clearTimeout(e.data.wheelTimeout),e.data.wheelTimeout=setTimeout((function(){e.data.wheelZooming=!1,e.redrawHint("eles",!0),e.redraw()}),150),s=null!=t.deltaY?t.deltaY/-250:null!=t.wheelDeltaY?t.wheelDeltaY/1e3:t.wheelDelta/1e3,s*=e.wheelSensitivity,1===t.deltaMode&&(s*=33);var l=n.zoom()*Math.pow(10,s);"gesturechange"===t.type&&(l=e.gestureStartZoom*t.scale),n.zoom({level:l,renderedPosition:{x:o[0],y:o[1]}}),n.emit("gesturechange"===t.type?"pinchzoom":"scrollzoom")}}};e.registerBinding(e.container,"wheel",L,!0),e.registerBinding(t,"scroll",(function(t){e.scrollingPage=!0,clearTimeout(e.scrollingPageTimeout),e.scrollingPageTimeout=setTimeout((function(){e.scrollingPage=!1}),250)}),!0),e.registerBinding(e.container,"gesturestart",(function(t){e.gestureStartZoom=e.cy.zoom(),e.hasTouchStarted||t.preventDefault()}),!0),e.registerBinding(e.container,"gesturechange",(function(t){e.hasTouchStarted||L(t)}),!0),e.registerBinding(e.container,"mouseout",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseout",position:{x:n[0],y:n[1]}})}),!1),e.registerBinding(e.container,"mouseover",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseover",position:{x:n[0],y:n[1]}})}),!1);var O,R,V,F,j,q,Y,X=function(e,t,n,r){return Math.sqrt((n-e)*(n-e)+(r-t)*(r-t))},W=function(e,t,n,r){return(n-e)*(n-e)+(r-t)*(r-t)};if(e.registerBinding(e.container,"touchstart",O=function(t){if(e.hasTouchStarted=!0,E(t)){p(),e.touchData.capture=!0,e.data.bgActivePosistion=void 0;var n=e.cy,i=e.touchData.now,a=e.touchData.earlier;if(t.touches[0]){var o=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);i[0]=o[0],i[1]=o[1]}if(t.touches[1]){o=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);i[2]=o[0],i[3]=o[1]}if(t.touches[2]){o=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);i[4]=o[0],i[5]=o[1]}if(t.touches[1]){e.touchData.singleTouchMoved=!0,d(e.dragData.touchDragEles);var l=e.findContainerClientCoords();B=l[0],N=l[1],z=l[2],I=l[3],k=t.touches[0].clientX-B,C=t.touches[0].clientY-N,S=t.touches[1].clientX-B,P=t.touches[1].clientY-N,A=0<=k&&k<=z&&0<=S&&S<=z&&0<=C&&C<=I&&0<=P&&P<=I;var h=n.pan(),f=n.zoom();D=X(k,C,S,P),T=W(k,C,S,P),M=[((_=[(k+S)/2,(C+P)/2])[0]-h.x)/f,(_[1]-h.y)/f];if(T<4e4&&!t.touches[2]){var g=e.findNearestElement(i[0],i[1],!0,!0),v=e.findNearestElement(i[2],i[3],!0,!0);return g&&g.isNode()?(g.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=g):v&&v.isNode()?(v.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=v):n.emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!0,e.touchData.cxtDragged=!1,e.data.bgActivePosistion=void 0,void e.redraw()}}if(t.touches[2])n.boxSelectionEnabled()&&t.preventDefault();else if(t.touches[1]);else if(t.touches[0]){var y=e.findNearestElements(i[0],i[1],!0,!0),m=y[0];if(null!=m&&(m.activate(),e.touchData.start=m,e.touchData.starts=y,e.nodeIsGrabbable(m))){var b=e.dragData.touchDragEles=n.collection(),x=null;e.redrawHint("eles",!0),e.redrawHint("drag",!0),m.selected()?(x=n.$((function(t){return t.selected()&&e.nodeIsGrabbable(t)})),u(x,{addToList:b})):c(m,{addToList:b}),s(m);var w=function(e){return{originalEvent:t,type:e,position:{x:i[0],y:i[1]}}};m.emit(w("grabon")),x?x.forEach((function(e){e.emit(w("grab"))})):m.emit(w("grab"))}r(m,["touchstart","tapstart","vmousedown"],t,{x:i[0],y:i[1]}),null==m&&(e.data.bgActivePosistion={x:o[0],y:o[1]},e.redrawHint("select",!0),e.redraw()),e.touchData.singleTouchMoved=!1,e.touchData.singleTouchStartTime=+new Date,clearTimeout(e.touchData.tapholdTimeout),e.touchData.tapholdTimeout=setTimeout((function(){!1!==e.touchData.singleTouchMoved||e.pinching||e.touchData.selecting||r(e.touchData.start,["taphold"],t,{x:i[0],y:i[1]})}),e.tapholdDuration)}if(t.touches.length>=1){for(var L=e.touchData.startPosition=[null,null,null,null,null,null],O=0;O=e.touchTapThreshold2}if(n&&e.touchData.cxt){t.preventDefault();var w=t.touches[0].clientX-B,_=t.touches[0].clientY-N,z=t.touches[1].clientX-B,I=t.touches[1].clientY-N,L=W(w,_,z,I);if(L/T>=2.25||L>=22500){e.touchData.cxt=!1,e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var O={originalEvent:t,type:"cxttapend",position:{x:s[0],y:s[1]}};e.touchData.start?(e.touchData.start.unactivate().emit(O),e.touchData.start=null):o.emit(O)}}if(n&&e.touchData.cxt){O={originalEvent:t,type:"cxtdrag",position:{x:s[0],y:s[1]}};e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.touchData.start?e.touchData.start.emit(O):o.emit(O),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxtDragged=!0;var R=e.findNearestElement(s[0],s[1],!0,!0);e.touchData.cxtOver&&R===e.touchData.cxtOver||(e.touchData.cxtOver&&e.touchData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:s[0],y:s[1]}}),e.touchData.cxtOver=R,R&&R.emit({originalEvent:t,type:"cxtdragover",position:{x:s[0],y:s[1]}}))}else if(n&&t.touches[2]&&o.boxSelectionEnabled())t.preventDefault(),e.data.bgActivePosistion=void 0,this.lastThreeTouch=+new Date,e.touchData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:s[0],y:s[1]}}),e.touchData.selecting=!0,e.touchData.didSelect=!0,i[4]=1,i&&0!==i.length&&void 0!==i[0]?(i[2]=(s[0]+s[2]+s[4])/3,i[3]=(s[1]+s[3]+s[5])/3):(i[0]=(s[0]+s[2]+s[4])/3,i[1]=(s[1]+s[3]+s[5])/3,i[2]=(s[0]+s[2]+s[4])/3+1,i[3]=(s[1]+s[3]+s[5])/3+1),e.redrawHint("select",!0),e.redraw();else if(n&&t.touches[1]&&!e.touchData.didSelect&&o.zoomingEnabled()&&o.panningEnabled()&&o.userZoomingEnabled()&&o.userPanningEnabled()){if(t.preventDefault(),e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),ee=e.dragData.touchDragEles){e.redrawHint("drag",!0);for(var V=0;V0&&!e.hoverData.draggingEles&&!e.swipePanning&&null!=e.data.bgActivePosistion&&(e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.redraw())}},!1),e.registerBinding(t,"touchcancel",V=function(t){var n=e.touchData.start;e.touchData.capture=!1,n&&n.unactivate()}),e.registerBinding(t,"touchend",F=function(t){var i=e.touchData.start;if(e.touchData.capture){0===t.touches.length&&(e.touchData.capture=!1),t.preventDefault();var a=e.selection;e.swipePanning=!1,e.hoverData.draggingEles=!1;var o,s=e.cy,l=s.zoom(),u=e.touchData.now,c=e.touchData.earlier;if(t.touches[0]){var h=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);u[0]=h[0],u[1]=h[1]}if(t.touches[1]){h=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);u[2]=h[0],u[3]=h[1]}if(t.touches[2]){h=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);u[4]=h[0],u[5]=h[1]}if(i&&i.unactivate(),e.touchData.cxt){if(o={originalEvent:t,type:"cxttapend",position:{x:u[0],y:u[1]}},i?i.emit(o):s.emit(o),!e.touchData.cxtDragged){var p={originalEvent:t,type:"cxttap",position:{x:u[0],y:u[1]}};i?i.emit(p):s.emit(p)}return e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!1,e.touchData.start=null,void e.redraw()}if(!t.touches[2]&&s.boxSelectionEnabled()&&e.touchData.selecting){e.touchData.selecting=!1;var f=s.collection(e.getAllInBox(a[0],a[1],a[2],a[3]));a[0]=void 0,a[1]=void 0,a[2]=void 0,a[3]=void 0,a[4]=0,e.redrawHint("select",!0),s.emit({type:"boxend",originalEvent:t,position:{x:u[0],y:u[1]}});f.emit("box").stdFilter((function(e){return e.selectable()&&!e.selected()})).select().emit("boxselect"),f.nonempty()&&e.redrawHint("eles",!0),e.redraw()}if(null!=i&&i.unactivate(),t.touches[2])e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);else if(t.touches[1]);else if(t.touches[0]);else if(!t.touches[0]){e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var g=e.dragData.touchDragEles;if(null!=i){var v=i._private.grabbed;d(g),e.redrawHint("drag",!0),e.redrawHint("eles",!0),v&&(i.emit("freeon"),g.emit("free"),e.dragData.didDrag&&(i.emit("dragfreeon"),g.emit("dragfree"))),r(i,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]}),i.unactivate(),e.touchData.start=null}else{var y=e.findNearestElement(u[0],u[1],!0,!0);r(y,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]})}var m=e.touchData.startPosition[0]-u[0],b=m*m,x=e.touchData.startPosition[1]-u[1],w=(b+x*x)*l*l;e.touchData.singleTouchMoved||(i||s.$(":selected").unselect(["tapunselect"]),r(i,["tap","vclick"],t,{x:u[0],y:u[1]}),j=!1,t.timeStamp-Y<=s.multiClickDebounceTime()?(q&&clearTimeout(q),j=!0,Y=null,r(i,["dbltap","vdblclick"],t,{x:u[0],y:u[1]})):(q=setTimeout((function(){j||r(i,["onetap","voneclick"],t,{x:u[0],y:u[1]})}),s.multiClickDebounceTime()),Y=t.timeStamp)),null!=i&&!e.dragData.didDrag&&i._private.selectable&&w2){for(var p=[c[0],c[1]],f=Math.pow(p[0]-e,2)+Math.pow(p[1]-t,2),g=1;g0)return g[0]}return null},p=Object.keys(d),f=0;f0?u:Ot(i,a,e,t,n,r,o,s)},checkPoint:function(e,t,n,r,i,a,o,s){var l=2*(s="auto"===s?tn(r,i):s);if(Yt(e,t,this.points,a,o,r,i-l,[0,-1],n))return!0;if(Yt(e,t,this.points,a,o,r-l,i,[0,-1],n))return!0;var u=r/2+2*n,c=i/2+2*n;return!!qt(e,t,[a-u,o-c,a-u,o,a+u,o,a+u,o-c])||(!!Ht(e,t,l,l,a+r/2-s,o+i/2-s,n)||!!Ht(e,t,l,l,a-r/2+s,o+i/2-s,n))}}},fu.registerNodeShapes=function(){var e=this.nodeShapes={},t=this;this.generateEllipse(),this.generatePolygon("triangle",Qt(3,0)),this.generateRoundPolygon("round-triangle",Qt(3,0)),this.generatePolygon("rectangle",Qt(4,0)),e.square=e.rectangle,this.generateRoundRectangle(),this.generateCutRectangle(),this.generateBarrel(),this.generateBottomRoundrectangle();var n=[0,1,1,0,0,-1,-1,0];this.generatePolygon("diamond",n),this.generateRoundPolygon("round-diamond",n),this.generatePolygon("pentagon",Qt(5,0)),this.generateRoundPolygon("round-pentagon",Qt(5,0)),this.generatePolygon("hexagon",Qt(6,0)),this.generateRoundPolygon("round-hexagon",Qt(6,0)),this.generatePolygon("heptagon",Qt(7,0)),this.generateRoundPolygon("round-heptagon",Qt(7,0)),this.generatePolygon("octagon",Qt(8,0)),this.generateRoundPolygon("round-octagon",Qt(8,0));var r=new Array(20),i=en(5,0),a=en(5,Math.PI/5),o=.5*(3-Math.sqrt(5));o*=1.57;for(var s=0;s=e.deqFastCost*g)break}else if(i){if(p>=e.deqCost*l||p>=e.deqAvgCost*s)break}else if(f>=e.deqNoDrawCost*(1e3/60))break;var v=e.deq(t,d,c);if(!(v.length>0))break;for(var y=0;y0&&(e.onDeqd(t,u),!i&&e.shouldRedraw(t,u,d,c)&&r())}),i(t))}}},xu=function(){function e(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ae;t(this,e),this.idsByKey=new Ze,this.keyForId=new Ze,this.cachesByLvl=new Ze,this.lvls=[],this.getKey=n,this.doesEleInvalidateKey=r}return r(e,[{key:"getIdsFor",value:function(e){null==e&&Re("Can not get id list for null key");var t=this.idsByKey,n=this.idsByKey.get(e);return n||(n=new Qe,t.set(e,n)),n}},{key:"addIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).add(t)}},{key:"deleteIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).delete(t)}},{key:"getNumberOfIdsForKey",value:function(e){return null==e?0:this.getIdsFor(e).size}},{key:"updateKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t),r=this.getKey(e);this.deleteIdForKey(n,t),this.addIdForKey(r,t),this.keyForId.set(t,r)}},{key:"deleteKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteIdForKey(n,t),this.keyForId.delete(t)}},{key:"keyHasChangedFor",value:function(e){var t=e.id();return this.keyForId.get(t)!==this.getKey(e)}},{key:"isInvalid",value:function(e){return this.keyHasChangedFor(e)||this.doesEleInvalidateKey(e)}},{key:"getCachesAt",value:function(e){var t=this.cachesByLvl,n=this.lvls,r=t.get(e);return r||(r=new Ze,t.set(e,r),n.push(e)),r}},{key:"getCache",value:function(e,t){return this.getCachesAt(t).get(e)}},{key:"get",value:function(e,t){var n=this.getKey(e),r=this.getCache(n,t);return null!=r&&this.updateKeyMappingFor(e),r}},{key:"getForCachedKey",value:function(e,t){var n=this.keyForId.get(e.id());return this.getCache(n,t)}},{key:"hasCache",value:function(e,t){return this.getCachesAt(t).has(e)}},{key:"has",value:function(e,t){var n=this.getKey(e);return this.hasCache(n,t)}},{key:"setCache",value:function(e,t,n){n.key=e,this.getCachesAt(t).set(e,n)}},{key:"set",value:function(e,t,n){var r=this.getKey(e);this.setCache(r,t,n),this.updateKeyMappingFor(e)}},{key:"deleteCache",value:function(e,t){this.getCachesAt(t).delete(e)}},{key:"delete",value:function(e,t){var n=this.getKey(e);this.deleteCache(n,t)}},{key:"invalidateKey",value:function(e){var t=this;this.lvls.forEach((function(n){return t.deleteCache(e,n)}))}},{key:"invalidate",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteKeyMappingFor(e);var r=this.doesEleInvalidateKey(e);return r&&this.invalidateKey(n),r||0===this.getNumberOfIdsForKey(n)}}]),e}(),wu={dequeue:"dequeue",downscale:"downscale",highQuality:"highQuality"},Eu=We({getKey:null,doesEleInvalidateKey:Ae,drawElement:null,getBoundingBox:null,getRotationPoint:null,getRotationOffset:null,isVisible:Ie,allowEdgeTxrCaching:!0,allowParentTxrCaching:!0}),ku=function(e,t){this.renderer=e,this.onDequeues=[];var n=Eu(t);A(this,n),this.lookup=new xu(n.getKey,n.doesEleInvalidateKey),this.setupDequeueing()},Cu=ku.prototype;Cu.reasons=wu,Cu.getTextureQueue=function(e){return this.eleImgCaches=this.eleImgCaches||{},this.eleImgCaches[e]=this.eleImgCaches[e]||[]},Cu.getRetiredTextureQueue=function(e){var t=this.eleImgCaches.retired=this.eleImgCaches.retired||{};return t[e]=t[e]||[]},Cu.getElementQueue=function(){return this.eleCacheQueue=this.eleCacheQueue||new nt((function(e,t){return t.reqs-e.reqs}))},Cu.getElementKeyToQueue=function(){return this.eleKeyToCacheQueue=this.eleKeyToCacheQueue||{}},Cu.getElement=function(e,t,n,r,i){var a=this,o=this.renderer,s=o.cy.zoom(),l=this.lookup;if(!t||0===t.w||0===t.h||isNaN(t.w)||isNaN(t.h)||!e.visible()||e.removed())return null;if(!a.allowEdgeTxrCaching&&e.isEdge()||!a.allowParentTxrCaching&&e.isParent())return null;if(null==r&&(r=Math.ceil(xt(s*n))),r<-4)r=-4;else if(s>=7.99||r>3)return null;var u=Math.pow(2,r),c=t.h*u,d=t.w*u,h=o.eleTextBiggerThanMin(e,u);if(!this.isVisible(e,h))return null;var p,f=l.get(e,r);if(f&&f.invalidated&&(f.invalidated=!1,f.texture.invalidatedWidth-=f.width),f)return f;if(p=c<=25?25:c<=50?50:50*Math.ceil(c/50),c>1024||d>1024)return null;var g=a.getTextureQueue(p),v=g[g.length-2],y=function(){return a.recycleTexture(p,d)||a.addTexture(p,d)};v||(v=g[g.length-1]),v||(v=y()),v.width-v.usedWidthr;D--)S=a.getElement(e,t,n,D,wu.downscale);P()}else{var T;if(!x&&!w&&!E)for(var _=r-1;_>=-4;_--){var M=l.get(e,_);if(M){T=M;break}}if(b(T))return a.queueElement(e,r),T;v.context.translate(v.usedWidth,0),v.context.scale(u,u),this.drawElement(v.context,e,t,h,!1),v.context.scale(1/u,1/u),v.context.translate(-v.usedWidth,0)}return f={x:v.usedWidth,texture:v,level:r,scale:u,width:d,height:c,scaledLabelShown:h},v.usedWidth+=Math.ceil(d+8),v.eleCaches.push(f),l.set(e,r,f),a.checkTextureFullness(v),f},Cu.invalidateElements=function(e){for(var t=0;t=.2*e.width&&this.retireTexture(e)},Cu.checkTextureFullness=function(e){var t=this.getTextureQueue(e.height);e.usedWidth/e.width>.8&&e.fullnessChecks>=10?He(t,e):e.fullnessChecks++},Cu.retireTexture=function(e){var t=e.height,n=this.getTextureQueue(t),r=this.lookup;He(n,e),e.retired=!0;for(var i=e.eleCaches,a=0;a=t)return a.retired=!1,a.usedWidth=0,a.invalidatedWidth=0,a.fullnessChecks=0,Ke(a.eleCaches),a.context.setTransform(1,0,0,1,0,0),a.context.clearRect(0,0,a.width,a.height),He(r,a),n.push(a),a}},Cu.queueElement=function(e,t){var n=this.getElementQueue(),r=this.getElementKeyToQueue(),i=this.getKey(e),a=r[i];if(a)a.level=Math.max(a.level,t),a.eles.merge(e),a.reqs++,n.updateItem(a);else{var o={eles:e.spawn().merge(e),level:t,reqs:1,key:i};n.push(o),r[i]=o}},Cu.dequeue=function(e){for(var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=[],i=this.lookup,a=0;a<1&&t.size()>0;a++){var o=t.pop(),s=o.key,l=o.eles[0],u=i.hasCache(l,o.level);if(n[s]=null,!u){r.push(o);var c=this.getBoundingBox(l);this.getElement(l,c,e,o.level,wu.dequeue)}}return r},Cu.removeFromQueue=function(e){var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=this.getKey(e),i=n[r];null!=i&&(1===i.eles.length?(i.reqs=ze,t.updateItem(i),t.pop(),n[r]=null):i.eles.unmerge(e))},Cu.onDequeue=function(e){this.onDequeues.push(e)},Cu.offDequeue=function(e){He(this.onDequeues,e)},Cu.setupDequeueing=bu({deqRedrawThreshold:100,deqCost:.15,deqAvgCost:.1,deqNoDrawCost:.9,deqFastCost:.9,deq:function(e,t,n){return e.dequeue(t,n)},onDeqd:function(e,t){for(var n=0;n=3.99||n>2)return null;r.validateLayersElesOrdering(n,e);var o,s,l=r.layersByLevel,u=Math.pow(2,n),c=l[n]=l[n]||[];if(r.levelIsComplete(n,e))return c;!function(){var t=function(t){if(r.validateLayersElesOrdering(t,e),r.levelIsComplete(t,e))return s=l[t],!0},i=function(e){if(!s)for(var r=n+e;-4<=r&&r<=2&&!t(r);r+=e);};i(1),i(-1);for(var a=c.length-1;a>=0;a--){var o=c[a];o.invalid&&He(c,o)}}();var d=function(t){var i=(t=t||{}).after;if(function(){if(!o){o=Tt();for(var t=0;t16e6)return null;var a=r.makeLayer(o,n);if(null!=i){var s=c.indexOf(i)+1;c.splice(s,0,a)}else(void 0===t.insert||t.insert)&&c.unshift(a);return a};if(r.skipping&&!a)return null;for(var h=null,p=e.length/1,f=!a,g=0;g=p||!Lt(h.bb,v.boundingBox()))&&!(h=d({insert:!0,after:h})))return null;s||f?r.queueLayer(h,v):r.drawEleInLayer(h,v,n,t),h.eles.push(v),m[n]=h}}return s||(f?null:c)},Pu.getEleLevelForLayerLevel=function(e,t){return e},Pu.drawEleInLayer=function(e,t,n,r){var i=this.renderer,a=e.context,o=t.boundingBox();0!==o.w&&0!==o.h&&t.visible()&&(n=this.getEleLevelForLayerLevel(n,r),i.setImgSmoothing(a,!1),i.drawCachedElement(a,t,null,null,n,!0),i.setImgSmoothing(a,!0))},Pu.levelIsComplete=function(e,t){var n=this.layersByLevel[e];if(!n||0===n.length)return!1;for(var r=0,i=0;i0)return!1;if(a.invalid)return!1;r+=a.eles.length}return r===t.length},Pu.validateLayersElesOrdering=function(e,t){var n=this.layersByLevel[e];if(n)for(var r=0;r0){e=!0;break}}return e},Pu.invalidateElements=function(e){var t=this;0!==e.length&&(t.lastInvalidationTime=xe(),0!==e.length&&t.haveLayers()&&t.updateElementsInLayers(e,(function(e,n,r){t.invalidateLayer(e)})))},Pu.invalidateLayer=function(e){if(this.lastInvalidationTime=xe(),!e.invalid){var t=e.level,n=e.eles,r=this.layersByLevel[t];He(r,e),e.elesQueue=[],e.invalid=!0,e.replacement&&(e.replacement.invalid=!0);for(var i=0;i3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=this,s=t._private.rscratch;if((!a||t.visible())&&!s.badLine&&null!=s.allpts&&!isNaN(s.allpts[0])){var l;n&&(l=n,e.translate(-l.x1,-l.y1));var u=a?t.pstyle("opacity").value:1,c=a?t.pstyle("line-opacity").value:1,d=t.pstyle("curve-style").value,h=t.pstyle("line-style").value,p=t.pstyle("width").pfValue,f=t.pstyle("line-cap").value,g=u*c,v=u*c,y=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:g;"straight-triangle"===d?(o.eleStrokeStyle(e,t,n),o.drawEdgeTrianglePath(t,e,s.allpts)):(e.lineWidth=p,e.lineCap=f,o.eleStrokeStyle(e,t,n),o.drawEdgePath(t,e,s.allpts,h),e.lineCap="butt")},m=function(){i&&o.drawEdgeOverlay(e,t)},b=function(){i&&o.drawEdgeUnderlay(e,t)},x=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:v;o.drawArrowheads(e,t,n)},w=function(){o.drawElementText(e,t,null,r)};e.lineJoin="round";var E="yes"===t.pstyle("ghost").value;if(E){var k=t.pstyle("ghost-offset-x").pfValue,C=t.pstyle("ghost-offset-y").pfValue,S=t.pstyle("ghost-opacity").value,P=g*S;e.translate(k,C),y(P),x(P),e.translate(-k,-C)}b(),y(),x(),m(),w(),n&&e.translate(l.x1,l.y1)}}},Xu=function(e){if(!["overlay","underlay"].includes(e))throw new Error("Invalid state");return function(t,n){if(n.visible()){var r=n.pstyle("".concat(e,"-opacity")).value;if(0!==r){var i=this,a=i.usePaths(),o=n._private.rscratch,s=2*n.pstyle("".concat(e,"-padding")).pfValue,l=n.pstyle("".concat(e,"-color")).value;t.lineWidth=s,"self"!==o.edgeType||a?t.lineCap="round":t.lineCap="butt",i.colorStrokeStyle(t,l[0],l[1],l[2],r),i.drawEdgePath(n,t,o.allpts,"solid")}}}};Yu.drawEdgeOverlay=Xu("overlay"),Yu.drawEdgeUnderlay=Xu("underlay"),Yu.drawEdgePath=function(e,t,n,r){var i,a=e._private.rscratch,s=t,l=!1,u=this.usePaths(),c=e.pstyle("line-dash-pattern").pfValue,d=e.pstyle("line-dash-offset").pfValue;if(u){var h=n.join("$");a.pathCacheKey&&a.pathCacheKey===h?(i=t=a.pathCache,l=!0):(i=t=new Path2D,a.pathCacheKey=h,a.pathCache=i)}if(s.setLineDash)switch(r){case"dotted":s.setLineDash([1,1]);break;case"dashed":s.setLineDash(c),s.lineDashOffset=d;break;case"solid":s.setLineDash([])}if(!l&&!a.badLine)switch(t.beginPath&&t.beginPath(),t.moveTo(n[0],n[1]),a.edgeType){case"bezier":case"self":case"compound":case"multibezier":for(var p=2;p+3=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,l=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){l=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(l)throw a}}}}(a.roundCorners);try{for(v.s();!(g=v.n()).done;){$l(t,g.value)}}catch(e){v.e(e)}finally{v.f()}t.lineTo(n[n.length-2],n[n.length-1])}else for(var y=2;y+15&&void 0!==arguments[5]?arguments[5]:5,o=arguments.length>6?arguments[6]:void 0;e.beginPath(),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n),e.closePath(),o?e.stroke():e.fill()}Hu.eleTextBiggerThanMin=function(e,t){if(!t){var n=e.cy().zoom(),r=this.getPixelRatio(),i=Math.ceil(xt(n*r));t=Math.pow(2,i)}return!(e.pstyle("font-size").pfValue*t5&&void 0!==arguments[5])||arguments[5],o=this;if(null==r){if(a&&!o.eleTextBiggerThanMin(t))return}else if(!1===r)return;if(t.isNode()){var s=t.pstyle("label");if(!s||!s.value)return;var l=o.getLabelJustification(t);e.textAlign=l,e.textBaseline="bottom"}else{var u=t.element()._private.rscratch.badLine,c=t.pstyle("label"),d=t.pstyle("source-label"),h=t.pstyle("target-label");if(u||(!c||!c.value)&&(!d||!d.value)&&(!h||!h.value))return;e.textAlign="center",e.textBaseline="bottom"}var p,f=!n;n&&(p=n,e.translate(-p.x1,-p.y1)),null==i?(o.drawText(e,t,null,f,a),t.isEdge()&&(o.drawText(e,t,"source",f,a),o.drawText(e,t,"target",f,a))):o.drawText(e,t,i,f,a),n&&e.translate(p.x1,p.y1)},Hu.getFontCache=function(e){var t;this.fontCaches=this.fontCaches||[];for(var n=0;n2&&void 0!==arguments[2])||arguments[2],r=t.pstyle("font-style").strValue,i=t.pstyle("font-size").pfValue+"px",a=t.pstyle("font-family").strValue,o=t.pstyle("font-weight").strValue,s=n?t.effectiveOpacity()*t.pstyle("text-opacity").value:1,l=t.pstyle("text-outline-opacity").value*s,u=t.pstyle("color").value,c=t.pstyle("text-outline-color").value;e.font=r+" "+o+" "+i+" "+a,e.lineJoin="round",this.colorFillStyle(e,u[0],u[1],u[2],s),this.colorStrokeStyle(e,c[0],c[1],c[2],l)},Hu.getTextAngle=function(e,t){var n=e._private.rscratch,r=t?t+"-":"",i=e.pstyle(r+"text-rotation"),a=Ge(n,"labelAngle",t);return"autorotate"===i.strValue?e.isEdge()?a:0:"none"===i.strValue?0:i.pfValue},Hu.drawText=function(e,t,n){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=t._private,o=a.rscratch,s=i?t.effectiveOpacity():1;if(!i||0!==s&&0!==t.pstyle("text-opacity").value){"main"===n&&(n=null);var l,u,c=Ge(o,"labelX",n),d=Ge(o,"labelY",n),h=this.getLabelText(t,n);if(null!=h&&""!==h&&!isNaN(c)&&!isNaN(d)){this.setupTextStyle(e,t,i);var p,f=n?n+"-":"",g=Ge(o,"labelWidth",n),v=Ge(o,"labelHeight",n),y=t.pstyle(f+"text-margin-x").pfValue,m=t.pstyle(f+"text-margin-y").pfValue,b=t.isEdge(),x=t.pstyle("text-halign").value,w=t.pstyle("text-valign").value;switch(b&&(x="center",w="center"),c+=y,d+=m,0!==(p=r?this.getTextAngle(t,n):0)&&(l=c,u=d,e.translate(l,u),e.rotate(p),c=0,d=0),w){case"top":break;case"center":d+=v/2;break;case"bottom":d+=v}var E=t.pstyle("text-background-opacity").value,k=t.pstyle("text-border-opacity").value,C=t.pstyle("text-border-width").pfValue,S=t.pstyle("text-background-padding").pfValue,P=t.pstyle("text-background-shape").strValue,D=0===P.indexOf("round"),T=2;if(E>0||C>0&&k>0){var _=c-S;switch(x){case"left":_-=g;break;case"center":_-=g/2}var M=d-v-S,B=g+2*S,N=v+2*S;if(E>0){var z=e.fillStyle,I=t.pstyle("text-background-color").value;e.fillStyle="rgba("+I[0]+","+I[1]+","+I[2]+","+E*s+")",D?Ku(e,_,M,B,N,T):e.fillRect(_,M,B,N),e.fillStyle=z}if(C>0&&k>0){var A=e.strokeStyle,L=e.lineWidth,O=t.pstyle("text-border-color").value,R=t.pstyle("text-border-style").value;if(e.strokeStyle="rgba("+O[0]+","+O[1]+","+O[2]+","+k*s+")",e.lineWidth=C,e.setLineDash)switch(R){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"double":e.lineWidth=C/4,e.setLineDash([]);break;case"solid":e.setLineDash([])}if(D?Ku(e,_,M,B,N,T,"stroke"):e.strokeRect(_,M,B,N),"double"===R){var V=C/2;D?Ku(e,_+V,M+V,B-2*V,N-2*V,T,"stroke"):e.strokeRect(_+V,M+V,B-2*V,N-2*V)}e.setLineDash&&e.setLineDash([]),e.lineWidth=L,e.strokeStyle=A}}var F=2*t.pstyle("text-outline-width").pfValue;if(F>0&&(e.lineWidth=F),"wrap"===t.pstyle("text-wrap").value){var j=Ge(o,"labelWrapCachedLines",n),q=Ge(o,"labelLineHeight",n),Y=g/2,X=this.getLabelJustification(t);switch("auto"===X||("left"===x?"left"===X?c+=-g:"center"===X&&(c+=-Y):"center"===x?"left"===X?c+=-Y:"right"===X&&(c+=Y):"right"===x&&("center"===X?c+=Y:"right"===X&&(c+=g))),w){case"top":d-=(j.length-1)*q;break;case"center":case"bottom":d-=(j.length-1)*q}for(var W=0;W0&&e.strokeText(j[W],c,d),e.fillText(j[W],c,d),d+=q}else F>0&&e.strokeText(h,c,d),e.fillText(h,c,d);0!==p&&(e.rotate(-p),e.translate(-l,-u))}}};var Gu={drawNode:function(e,t,n){var r,i,a=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],l=this,u=t._private,c=u.rscratch,d=t.position();if(b(d.x)&&b(d.y)&&(!s||t.visible())){var h,p,f=s?t.effectiveOpacity():1,g=l.usePaths(),v=!1,y=t.padding();r=t.width()+2*y,i=t.height()+2*y,n&&(p=n,e.translate(-p.x1,-p.y1));for(var m=t.pstyle("background-image"),x=m.value,w=new Array(x.length),E=new Array(x.length),k=0,C=0;C0&&void 0!==arguments[0]?arguments[0]:M;l.eleFillStyle(e,t,n)},H=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:R;l.colorStrokeStyle(e,B[0],B[1],B[2],t)},K=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q;l.colorStrokeStyle(e,F[0],F[1],F[2],t)},G=function(e,t,n,r){var i,a=l.nodePathCache=l.nodePathCache||[],o=Te("polygon"===n?n+","+r.join(","):n,""+t,""+e,""+X),s=a[o],u=!1;return null!=s?(i=s,u=!0,c.pathCache=i):(i=new Path2D,a[o]=c.pathCache=i),{path:i,cacheHit:u}},U=t.pstyle("shape").strValue,Z=t.pstyle("shape-polygon-points").pfValue;if(g){e.translate(d.x,d.y);var $=G(r,i,U,Z);h=$.path,v=$.cacheHit}var Q=function(){if(!v){var n=d;g&&(n={x:0,y:0}),l.nodeShapes[l.getNodeShape(t)].draw(h||e,n.x,n.y,r,i,X,c)}g?e.fill(h):e.fill()},J=function(){for(var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=u.backgrounding,a=0,o=0;o0&&void 0!==arguments[0]&&arguments[0],a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:f;l.hasPie(t)&&(l.drawPie(e,t,a),n&&(g||l.nodeShapes[l.getNodeShape(t)].draw(e,d.x,d.y,r,i,X,c)))},te=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,n=(T>0?T:-T)*t,r=T>0?0:255;0!==T&&(l.colorFillStyle(e,r,r,r,n),g?e.fill(h):e.fill())},ne=function(){if(_>0){if(e.lineWidth=_,e.lineCap=I,e.lineJoin=z,e.setLineDash)switch(N){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash(L),e.lineDashOffset=O;break;case"solid":case"double":e.setLineDash([])}if("center"!==A){if(e.save(),e.lineWidth*=2,"inside"===A)g?e.clip(h):e.clip();else{var t=new Path2D;t.rect(-r/2-_,-i/2-_,r+2*_,i+2*_),t.addPath(h),e.clip(t,"evenodd")}g?e.stroke(h):e.stroke(),e.restore()}else g?e.stroke(h):e.stroke();if("double"===N){e.lineWidth=_/3;var n=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",g?e.stroke(h):e.stroke(),e.globalCompositeOperation=n}e.setLineDash&&e.setLineDash([])}},re=function(){if(V>0){if(e.lineWidth=V,e.lineCap="butt",e.setLineDash)switch(j){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"solid":case"double":e.setLineDash([])}var n=d;g&&(n={x:0,y:0});var a=l.getNodeShape(t),o=_;"inside"===A&&(o=0),"outside"===A&&(o*=2);var s,u=(r+o+(V+Y))/r,c=(i+o+(V+Y))/i,h=r*u,p=i*c,f=l.nodeShapes[a].points;if(g)s=G(h,p,a,f).path;if("ellipse"===a)l.drawEllipsePath(s||e,n.x,n.y,h,p);else if(["round-diamond","round-heptagon","round-hexagon","round-octagon","round-pentagon","round-polygon","round-triangle","round-tag"].includes(a)){var v=0,y=0,m=0;"round-diamond"===a?v=1.4*(o+Y+V):"round-heptagon"===a?(v=1.075*(o+Y+V),m=-(o/2+Y+V)/35):"round-hexagon"===a?v=1.12*(o+Y+V):"round-pentagon"===a?(v=1.13*(o+Y+V),m=-(o/2+Y+V)/15):"round-tag"===a?(v=1.12*(o+Y+V),y=.07*(o/2+V+Y)):"round-triangle"===a&&(v=(o+Y+V)*(Math.PI/2),m=-(o+Y/2+V)/Math.PI),0!==v&&(h=r*(u=(r+v)/r),["round-hexagon","round-tag"].includes(a)||(p=i*(c=(i+v)/i)));for(var b=h/2,x=p/2,w=(X="auto"===X?nn(h,p):X)+(o+V+Y)/2,E=new Array(f.length/2),k=new Array(f.length/2),C=0;C0){if(r=r||n.position(),null==i||null==a){var d=n.padding();i=n.width()+2*d,a=n.height()+2*d}this.colorFillStyle(t,l[0],l[1],l[2],s),this.nodeShapes[u].draw(t,r.x,r.y,i+2*o,a+2*o,c),t.fill()}}}};Gu.drawNodeOverlay=Uu("overlay"),Gu.drawNodeUnderlay=Uu("underlay"),Gu.hasPie=function(e){return(e=e[0])._private.hasPie},Gu.drawPie=function(e,t,n,r){t=t[0],r=r||t.position();var i=t.cy().style(),a=t.pstyle("pie-size"),o=r.x,s=r.y,l=t.width(),u=t.height(),c=Math.min(l,u)/2,d=0;this.usePaths()&&(o=0,s=0),"%"===a.units?c*=a.pfValue:void 0!==a.pfValue&&(c=a.pfValue/2);for(var h=1;h<=i.pieBackgroundN;h++){var p=t.pstyle("pie-"+h+"-background-size").value,f=t.pstyle("pie-"+h+"-background-color").value,g=t.pstyle("pie-"+h+"-background-opacity").value*n,v=p/100;v+d>1&&(v=1-d);var y=1.5*Math.PI+2*Math.PI*d,m=y+2*Math.PI*v;0===p||d>=1||d+v>1||(e.beginPath(),e.moveTo(o,s),e.arc(o,s,c,y,m),e.closePath(),this.colorFillStyle(e,f[0],f[1],f[2],g),e.fill(),d+=v)}};var Zu={};Zu.getPixelRatio=function(){var e=this.data.contexts[0];if(null!=this.forcedPixelRatio)return this.forcedPixelRatio;var t=e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return(window.devicePixelRatio||1)/t},Zu.paintCache=function(e){for(var t,n=this.paintCaches=this.paintCaches||[],r=!0,i=0;io.minMbLowQualFrames&&(o.motionBlurPxRatio=o.mbPxRBlurry)),o.clearingMotionBlur&&(o.motionBlurPxRatio=1),o.textureDrawLastFrame&&!d&&(c[o.NODE]=!0,c[o.SELECT_BOX]=!0);var m=l.style(),b=l.zoom(),x=void 0!==i?i:b,w=l.pan(),E={x:w.x,y:w.y},k={zoom:b,pan:{x:w.x,y:w.y}},C=o.prevViewport;void 0===C||k.zoom!==C.zoom||k.pan.x!==C.pan.x||k.pan.y!==C.pan.y||g&&!f||(o.motionBlurPxRatio=1),a&&(E=a),x*=s,E.x*=s,E.y*=s;var S=o.getCachedZSortedEles();function P(e,t,n,r,i){var a=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",o.colorFillStyle(e,255,255,255,o.motionBlurTransparency),e.fillRect(t,n,r,i),e.globalCompositeOperation=a}function D(e,r){var s,l,c,d;o.clearingMotionBlur||e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]&&e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]?(s=E,l=x,c=o.canvasWidth,d=o.canvasHeight):(s={x:w.x*p,y:w.y*p},l=b*p,c=o.canvasWidth*p,d=o.canvasHeight*p),e.setTransform(1,0,0,1,0,0),"motionBlur"===r?P(e,0,0,c,d):t||void 0!==r&&!r||e.clearRect(0,0,c,d),n||(e.translate(s.x,s.y),e.scale(l,l)),a&&e.translate(a.x,a.y),i&&e.scale(i,i)}if(d||(o.textureDrawLastFrame=!1),d){if(o.textureDrawLastFrame=!0,!o.textureCache){o.textureCache={},o.textureCache.bb=l.mutableElements().boundingBox(),o.textureCache.texture=o.data.bufferCanvases[o.TEXTURE_BUFFER];var T=o.data.bufferContexts[o.TEXTURE_BUFFER];T.setTransform(1,0,0,1,0,0),T.clearRect(0,0,o.canvasWidth*o.textureMult,o.canvasHeight*o.textureMult),o.render({forcedContext:T,drawOnlyNodeLayer:!0,forcedPxRatio:s*o.textureMult}),(k=o.textureCache.viewport={zoom:l.zoom(),pan:l.pan(),width:o.canvasWidth,height:o.canvasHeight}).mpan={x:(0-k.pan.x)/k.zoom,y:(0-k.pan.y)/k.zoom}}c[o.DRAG]=!1,c[o.NODE]=!1;var _=u.contexts[o.NODE],M=o.textureCache.texture;k=o.textureCache.viewport;_.setTransform(1,0,0,1,0,0),h?P(_,0,0,k.width,k.height):_.clearRect(0,0,k.width,k.height);var B=m.core("outside-texture-bg-color").value,N=m.core("outside-texture-bg-opacity").value;o.colorFillStyle(_,B[0],B[1],B[2],N),_.fillRect(0,0,k.width,k.height);b=l.zoom();D(_,!1),_.clearRect(k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s),_.drawImage(M,k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s)}else o.textureOnViewport&&!t&&(o.textureCache=null);var z=l.extent(),I=o.pinching||o.hoverData.dragging||o.swipePanning||o.data.wheelZooming||o.hoverData.draggingEles||o.cy.animated(),A=o.hideEdgesOnViewport&&I,L=[];if(L[o.NODE]=!c[o.NODE]&&h&&!o.clearedForMotionBlur[o.NODE]||o.clearingMotionBlur,L[o.NODE]&&(o.clearedForMotionBlur[o.NODE]=!0),L[o.DRAG]=!c[o.DRAG]&&h&&!o.clearedForMotionBlur[o.DRAG]||o.clearingMotionBlur,L[o.DRAG]&&(o.clearedForMotionBlur[o.DRAG]=!0),c[o.NODE]||n||r||L[o.NODE]){var O=h&&!L[o.NODE]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]:u.contexts[o.NODE]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.nondrag,s,z):o.drawLayeredElements(_,S.nondrag,s,z),o.debug&&o.drawDebugPoints(_,S.nondrag),n||h||(c[o.NODE]=!1)}if(!r&&(c[o.DRAG]||n||L[o.DRAG])){O=h&&!L[o.DRAG]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]:u.contexts[o.DRAG]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.drag,s,z):o.drawCachedElements(_,S.drag,s,z),o.debug&&o.drawDebugPoints(_,S.drag),n||h||(c[o.DRAG]=!1)}if(o.showFps||!r&&c[o.SELECT_BOX]&&!n){if(D(_=t||u.contexts[o.SELECT_BOX]),1==o.selection[4]&&(o.hoverData.selecting||o.touchData.selecting)){b=o.cy.zoom();var R=m.core("selection-box-border-width").value/b;_.lineWidth=R,_.fillStyle="rgba("+m.core("selection-box-color").value[0]+","+m.core("selection-box-color").value[1]+","+m.core("selection-box-color").value[2]+","+m.core("selection-box-opacity").value+")",_.fillRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]),R>0&&(_.strokeStyle="rgba("+m.core("selection-box-border-color").value[0]+","+m.core("selection-box-border-color").value[1]+","+m.core("selection-box-border-color").value[2]+","+m.core("selection-box-opacity").value+")",_.strokeRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]))}if(u.bgActivePosistion&&!o.hoverData.selecting){b=o.cy.zoom();var V=u.bgActivePosistion;_.fillStyle="rgba("+m.core("active-bg-color").value[0]+","+m.core("active-bg-color").value[1]+","+m.core("active-bg-color").value[2]+","+m.core("active-bg-opacity").value+")",_.beginPath(),_.arc(V.x,V.y,m.core("active-bg-size").pfValue/b,0,2*Math.PI),_.fill()}var F=o.lastRedrawTime;if(o.showFps&&F){F=Math.round(F);var j=Math.round(1e3/F);_.setTransform(1,0,0,1,0,0),_.fillStyle="rgba(255, 0, 0, 0.75)",_.strokeStyle="rgba(255, 0, 0, 0.75)",_.lineWidth=1,_.fillText("1 frame = "+F+" ms = "+j+" fps",0,20);_.strokeRect(0,30,250,20),_.fillRect(0,30,250*Math.min(j/60,1),20)}n||(c[o.SELECT_BOX]=!1)}if(h&&1!==p){var q=u.contexts[o.NODE],Y=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_NODE],X=u.contexts[o.DRAG],W=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_DRAG],H=function(e,t,n){e.setTransform(1,0,0,1,0,0),n||!y?e.clearRect(0,0,o.canvasWidth,o.canvasHeight):P(e,0,0,o.canvasWidth,o.canvasHeight);var r=p;e.drawImage(t,0,0,o.canvasWidth*r,o.canvasHeight*r,0,0,o.canvasWidth,o.canvasHeight)};(c[o.NODE]||L[o.NODE])&&(H(q,Y,L[o.NODE]),c[o.NODE]=!1),(c[o.DRAG]||L[o.DRAG])&&(H(X,W,L[o.DRAG]),c[o.DRAG]=!1)}o.prevViewport=k,o.clearingMotionBlur&&(o.clearingMotionBlur=!1,o.motionBlurCleared=!0,o.motionBlur=!0),h&&(o.motionBlurTimeout=setTimeout((function(){o.motionBlurTimeout=null,o.clearedForMotionBlur[o.NODE]=!1,o.clearedForMotionBlur[o.DRAG]=!1,o.motionBlur=!1,o.clearingMotionBlur=!d,o.mbFrames=0,c[o.NODE]=!0,c[o.DRAG]=!0,o.redraw()}),100)),t||l.emit("render")};for(var $u={drawPolygonPath:function(e,t,n,r,i,a){var o=r/2,s=i/2;e.beginPath&&e.beginPath(),e.moveTo(t+o*a[0],n+s*a[1]);for(var l=1;l0&&a>0){h.clearRect(0,0,i,a),h.globalCompositeOperation="source-over";var p=this.getCachedZSortedEles();if(e.full)h.translate(-n.x1*l,-n.y1*l),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(n.x1*l,n.y1*l);else{var f=t.pan(),g={x:f.x*l,y:f.y*l};l*=t.zoom(),h.translate(g.x,g.y),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(-g.x,-g.y)}e.bg&&(h.globalCompositeOperation="destination-over",h.fillStyle=e.bg,h.rect(0,0,i,a),h.fill())}return d},ic.png=function(e){return oc(e,this.bufferCanvasImage(e),"image/png")},ic.jpg=function(e){return oc(e,this.bufferCanvasImage(e),"image/jpeg")};var sc={nodeShapeImpl:function(e,t,n,r,i,a,o,s){switch(e){case"ellipse":return this.drawEllipsePath(t,n,r,i,a);case"polygon":return this.drawPolygonPath(t,n,r,i,a,o);case"round-polygon":return this.drawRoundPolygonPath(t,n,r,i,a,o,s);case"roundrectangle":case"round-rectangle":return this.drawRoundRectanglePath(t,n,r,i,a,s);case"cutrectangle":case"cut-rectangle":return this.drawCutRectanglePath(t,n,r,i,a,o,s);case"bottomroundrectangle":case"bottom-round-rectangle":return this.drawBottomRoundRectanglePath(t,n,r,i,a,s);case"barrel":return this.drawBarrelPath(t,n,r,i,a)}}},lc=cc,uc=cc.prototype;function cc(e){var t=this;t.data={canvases:new Array(uc.CANVAS_LAYERS),contexts:new Array(uc.CANVAS_LAYERS),canvasNeedsRedraw:new Array(uc.CANVAS_LAYERS),bufferCanvases:new Array(uc.BUFFER_COUNT),bufferContexts:new Array(uc.CANVAS_LAYERS)};t.data.canvasContainer=document.createElement("div");var n=t.data.canvasContainer.style;t.data.canvasContainer.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)",n.position="relative",n.zIndex="0",n.overflow="hidden";var r=e.cy.container();r.appendChild(t.data.canvasContainer),r.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)";var i={"-webkit-user-select":"none","-moz-user-select":"-moz-none","user-select":"none","-webkit-tap-highlight-color":"rgba(0,0,0,0)","outline-style":"none"};u&&u.userAgent.match(/msie|trident|edge/i)&&(i["-ms-touch-action"]="none",i["touch-action"]="none");for(var a=0;a Option { + let rest = path.strip_prefix("site/content/")?; + let segs: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect(); + // Require at least [content_type, lang, category] + if segs.len() < 3 { + return None; + } + if !["en", "es"].contains(&segs[1]) { + return None; + } + // Drop the language segment; join remaining with content_type prefix. + let mut parts = vec![segs[0]]; + parts.extend_from_slice(&segs[2..]); + Some(format!("/{}", parts.join("/"))) +} + +// ── Public entry point +// ──────────────────────────────────────────────────────── + +/// Write all generated artefacts to `out_dir`. +/// +/// Outputs: +/// - `content_graph.json` — full serialised graph for Cytoscape +/// - `related_map.rs` — static map node_id → related nodes +/// (RelatedContent, no JS) +/// - `ontology_context_map.rs` — static map node_id → connected ontology nodes +/// - `graph_mini_map.rs` — static map node_id → ego SVG string +/// (GraphMini, SSR-safe) +pub fn write_outputs(graph: &ContentGraph, out_dir: &Path) -> Result<(), BuildError> { + write_graph_json(graph, out_dir)?; + write_related_map(graph, out_dir)?; + write_ontology_context_map(graph, out_dir)?; + write_graph_mini_map(graph, out_dir)?; + Ok(()) +} + +// ── content_graph.json +// ──────────────────────────────────────────────────────── + +fn write_graph_json(graph: &ContentGraph, out_dir: &Path) -> Result<(), BuildError> { + let json = serde_json::to_string_pretty(graph)?; + std::fs::write(out_dir.join("content_graph.json"), json)?; + Ok(()) +} + +// ── related_map.rs +// ──────────────────────────────────────────────────────────── + +/// Generates a phf-style static map: +/// ```rust +/// pub static RELATED_NODES: &[(&str, &[RelatedNode])] = &[...]; +/// ``` +/// Used by `RelatedContent` component — no JS, fully SSR-safe. +fn write_related_map(graph: &ContentGraph, out_dir: &Path) -> Result<(), BuildError> { + // Build adjacency: node_id → [(related_id, kind_label)] + // Use a HashSet keyed by (related_id, kind_label) to prevent duplicate entries + // from forward + autobacklink edge pairs hitting the same (from, to) pair. + let mut adjacency: HashMap> = + HashMap::new(); + + for edge in &graph.edges { + // Skip SharedTag (too noisy) and RelatedFrom (autobacklink of RelatedTo — + // the symmetric clause below already mirrors it into the target's sidebar). + if matches!(edge.kind, EdgeKind::SharedTag | EdgeKind::RelatedFrom) { + continue; + } + + let kind_label = format!("{:?}", edge.kind); + + adjacency + .entry(edge.from.clone()) + .or_default() + .insert((edge.to.clone(), kind_label.clone())); + + // RelatedTo is symmetric for display — show in both nodes' sidebars. + if matches!(edge.kind, EdgeKind::RelatedTo) { + adjacency + .entry(edge.to.clone()) + .or_default() + .insert((edge.from.clone(), kind_label)); + } + } + + // Convert sets to sorted vecs for deterministic output. + let adjacency: HashMap> = adjacency + .into_iter() + .map(|(k, set)| { + let mut v: Vec<_> = set.into_iter().collect(); + v.sort(); + (k, v) + }) + .collect(); + + // Build node title lookup + let titles: HashMap<&str, &str> = graph.nodes.iter().map(|n| (n.id(), n.title())).collect(); + + // Build node URL lookup — content nodes use their stored URL; Practice-level + // ontology nodes derive their URL from the first artifact_path if it points + // to a content directory (site/content/{type}/en/{category}/). + let node_urls: HashMap<&str, String> = graph + .nodes + .iter() + .filter_map(|n| match n { + GraphNode::Content { id, url, .. } => Some((id.as_str(), url.clone())), + GraphNode::Ontology { + id, + level: OntologyLevel::Practice, + artifact_paths, + .. + } => { + let url = artifact_paths + .first() + .and_then(|p| ontology_artifact_to_url(p))?; + Some((id.as_str(), url)) + } + _ => None, + }) + .collect(); + + // Slug → id aliases: content nodes whose URL slug differs from their id. + // PostViewer passes the URL slug as node_id, so the map must also answer to it. + let slug_to_id: HashMap = graph + .nodes + .iter() + .filter_map(|n| { + let slug = n.url_slug()?; + if slug != n.id() { + Some((slug.to_owned(), n.id().to_owned())) + } else { + None + } + }) + .collect(); + + let make_entry = |node_id: &str, related: &Vec<(String, String)>| -> String { + let related_entries: Vec = related.iter().map(|(rid, kind)| { + let title = titles.get(rid.as_str()).copied().unwrap_or(rid.as_str()); + let url = node_urls.get(rid.as_str()).map(|s| s.as_str()).unwrap_or(""); + format!( + r#" RelatedNode {{ id: {id:?}, title: {title:?}, kind: {kind:?}, url: {url:?} }}"#, + id = rid, + title = title, + kind = kind, + url = url, + ) + }).collect(); + format!( + " ({node_id:?}, &[\n{entries}\n ]),", + node_id = node_id, + entries = related_entries.join(",\n"), + ) + }; + + let mut entries: Vec = adjacency + .iter() + .map(|(node_id, related)| make_entry(node_id, related)) + .collect(); + + // Emit slug-aliased entries for content nodes where URL slug != id + for (slug, id) in &slug_to_id { + if let Some(related) = adjacency.get(id) { + entries.push(make_entry(slug, related)); + } + } + + entries.sort(); // deterministic output for incremental builds + + let code = format!( + r#"// Generated by content-graph feature — do not edit. +pub struct RelatedNode {{ + pub id: &'static str, + pub title: &'static str, + pub kind: &'static str, + pub url: &'static str, +}} + +pub static RELATED_NODES: &[(&'static str, &'static [RelatedNode])] = &[ +{entries} +]; +"#, + entries = entries.join("\n"), + ); + + std::fs::write(out_dir.join("related_map.rs"), code)?; + Ok(()) +} + +// ── ontology_context_map.rs +// ─────────────────────────────────────────────────── + +/// Generates: +/// ```rust +/// pub static ONTOLOGY_CONTEXT: &[(&str, &[OntologyRef])] = &[...]; +/// ``` +/// Used by `OntologyContext` badge component. +fn write_ontology_context_map(graph: &ContentGraph, out_dir: &Path) -> Result<(), BuildError> { + // Find all ontology nodes connected to content nodes + let ontology_ids: std::collections::HashSet = graph + .nodes + .iter() + .filter_map(|n| match n { + GraphNode::Ontology { id, .. } | GraphNode::Adr { id, .. } => Some(id.clone()), + _ => None, + }) + .collect(); + + let ontology_names: HashMap<&str, &str> = graph + .nodes + .iter() + .filter_map(|n| match n { + GraphNode::Ontology { id, name, .. } => Some((id.as_str(), name.as_str())), + GraphNode::Adr { id, title, .. } => Some((id.as_str(), title.as_str())), + _ => None, + }) + .collect(); + + // content_id → [(ontology_id, ontology_name, edge_kind)] + // Only process content→ontology direction (edge.to ∈ ontology_ids). + // Processing edge.from as well would double-add entries because every + // Implements edge has an ImplementedBy autobacklink pointing the other way. + let mut ctx_map: HashMap> = + HashMap::new(); + + for edge in &graph.edges { + if ontology_ids.contains(&edge.from) { + continue; + } // skip ontology-origin edges + if ontology_ids.contains(&edge.to) { + let name = ontology_names + .get(edge.to.as_str()) + .copied() + .unwrap_or(&edge.to); + ctx_map.entry(edge.from.clone()).or_default().insert(( + edge.to.clone(), + name.to_owned(), + format!("{:?}", edge.kind), + )); + } + } + + // Convert sets to sorted vecs. + let ctx_map: HashMap> = ctx_map + .into_iter() + .map(|(k, set)| { + let mut v: Vec<_> = set.into_iter().collect(); + v.sort(); + (k, v) + }) + .collect(); + + // Slug → id aliases (same rationale as write_related_map) + let slug_to_id: HashMap = graph + .nodes + .iter() + .filter_map(|n| { + let slug = n.url_slug()?; + if slug != n.id() { + Some((slug.to_owned(), n.id().to_owned())) + } else { + None + } + }) + .collect(); + + let make_entry = |content_id: &str, refs: &Vec<(String, String, String)>| -> String { + let ref_entries: Vec = refs + .iter() + .map(|(oid, oname, kind)| { + format!( + r#" OntologyRef {{ id: {oid:?}, name: {oname:?}, kind: {kind:?} }}"#, + oid = oid, + oname = oname, + kind = kind, + ) + }) + .collect(); + format!( + " ({content_id:?}, &[\n{entries}\n ]),", + content_id = content_id, + entries = ref_entries.join(",\n"), + ) + }; + + let mut entries: Vec = ctx_map + .iter() + .map(|(content_id, refs)| make_entry(content_id, refs)) + .collect(); + + for (slug, id) in &slug_to_id { + if let Some(refs) = ctx_map.get(id) { + entries.push(make_entry(slug, refs)); + } + } + + entries.sort(); + + let code = format!( + r#"// Generated by content-graph feature — do not edit. +pub struct OntologyRef {{ + pub id: &'static str, + pub name: &'static str, + pub kind: &'static str, +}} + +pub static ONTOLOGY_CONTEXT: &[(&'static str, &'static [OntologyRef])] = &[ +{entries} +]; +"#, + entries = entries.join("\n"), + ); + + std::fs::write(out_dir.join("ontology_context_map.rs"), code)?; + Ok(()) +} + +// ── Ego-network SVGs +// ────────────────────────────────────────────────────────── + +const MINI_SVG_STYLES: &str = r#" + .graph-node { fill: var(--cg-node, #6b7280); stroke: none; } + .graph-node.ego { fill: var(--cg-ego, #3b82f6); } + .graph-node.ontology { fill: var(--cg-onto, #8b5cf6); } + .graph-node.adr { fill: var(--cg-adr, #f59e0b); } + .graph-edge { stroke: var(--cg-edge, #d1d5db); stroke-width: 1.5; } + .graph-label { font: 10px sans-serif; fill: var(--cg-label, #374151); text-anchor: middle; } + .graph-label.ego { font-weight: 600; } +"#; + +/// Generates `graph_mini_map.rs` with all ego-network SVGs inlined: +/// ```rust +/// pub static GRAPH_MINI_SVGS: &[(&str, &str)] = &[ +/// ("rustelo", r#"..."#), +/// ... +/// ]; +/// ``` +fn write_graph_mini_map(graph: &ContentGraph, out_dir: &Path) -> Result<(), BuildError> { + // HashSet per node prevents duplicate neighbors from forward + backlink edge + // pairs (e.g. Implements + ImplementedBy both connect content ↔ ontology + // node). + let adjacency: HashMap> = { + let mut m: HashMap> = HashMap::new(); + for edge in &graph.edges { + if matches!(edge.kind, EdgeKind::SharedTag) { + continue; + } + m.entry(edge.from.clone()) + .or_default() + .insert(edge.to.clone()); + m.entry(edge.to.clone()) + .or_default() + .insert(edge.from.clone()); + } + m.into_iter() + .map(|(k, set)| (k, set.into_iter().collect())) + .collect() + }; + + let node_lookup: HashMap<&str, &GraphNode> = graph.nodes.iter().map(|n| (n.id(), n)).collect(); + + let mut entries: Vec = Vec::new(); + + for node in &graph.nodes { + if !matches!(node, GraphNode::Content { .. }) { + continue; + } + + let neighbors: Vec<&GraphNode> = adjacency + .get(node.id()) + .map(|ids| { + ids.iter() + .filter_map(|id| node_lookup.get(id.as_str()).copied()) + .collect() + }) + .unwrap_or_default(); + + // Isolated nodes carry no graph information — skip them so GraphMini + // renders nothing rather than showing a single orphan circle. + if neighbors.is_empty() { + continue; + } + + let svg = render_ego_svg(node, &neighbors); + // Escape any `#` sequences that would break raw string literal + let delim = pick_raw_delim(&svg); + let hashes = "#".repeat(delim); + entries.push(format!( + " ({id:?}, r{hashes}\"{svg}\"{hashes})", + id = node.id(), + )); + + // Also emit a slug-keyed alias when the URL slug differs from the id. + // PostViewer identifies content by URL slug, not by the NCL id field. + if let Some(slug) = node.url_slug() { + if slug != node.id() { + entries.push(format!( + " ({slug:?}, r{hashes}\"{svg}\"{hashes})", + slug = slug, + )); + } + } + } + + entries.sort(); + + let code = format!( + "// Generated by content-graph feature — do not edit.\npub static GRAPH_MINI_SVGS: \ + &[(&'static str, &'static str)] = &[\n{entries}\n];\n", + entries = entries.join(",\n"), + ); + + std::fs::write(out_dir.join("graph_mini_map.rs"), code)?; + Ok(()) +} + +/// Find the minimum number of `#` needed for a raw string literal containing +/// `svg`. +fn pick_raw_delim(s: &str) -> usize { + let mut n = 0usize; + loop { + let needle = format!("\"{}", "#".repeat(n)); + if !s.contains(&needle) { + return n; + } + n += 1; + } +} + +fn render_ego_svg(ego: &GraphNode, neighbors: &[&GraphNode]) -> String { + let (cx, cy) = (180.0_f32, 180.0_f32); + let radius = 120.0_f32; + let n = neighbors.len().max(1) as f32; + + // Start angle offset so first node lands at top rather than right, + // giving a more balanced layout on landscape viewports. + let start_angle = -std::f32::consts::FRAC_PI_2; + + let lines: String = neighbors.iter().enumerate().map(|(i, _)| { + let angle = start_angle + (i as f32 / n) * std::f32::consts::TAU; + let nx = cx + radius * angle.cos(); + let ny = cy + radius * angle.sin(); + format!(r#" "#) + }).collect::>().join("\n"); + + let neighbor_circles: String = neighbors + .iter() + .enumerate() + .map(|(i, node)| { + let angle = start_angle + (i as f32 / n) * std::f32::consts::TAU; + let nx = cx + radius * angle.cos(); + let ny = cy + radius * angle.sin(); + let css = node_css_class(node); + let label = truncate(node.title(), 22); + // Place label below circle; shift up when in upper half to avoid clipping. + let label_y = if angle.sin() < -0.3 { + ny - 24.0 + } else { + ny + 28.0 + }; + format!( + r#" + {label}"#, + ) + }) + .collect::>() + .join("\n"); + + let ego_css = node_css_class(ego); + let ego_label = truncate(ego.title(), 30); + + format!( + r#" + +{lines} + + {ego_label} +{neighbor_circles} +"#, + cy + 36.0, + ) +} + +fn node_css_class(node: &GraphNode) -> &'static str { + match node { + GraphNode::Content { .. } => "content", + GraphNode::Ontology { .. } => "ontology", + GraphNode::Adr { .. } => "adr", + } +} + +fn truncate(s: &str, max: usize) -> String { + let chars: Vec = s.chars().collect(); + if chars.len() <= max { + s.to_owned() + } else { + chars[..max - 1].iter().collect::() + "…" + } +} diff --git a/features/content-graph/src/build/edge_resolver.rs b/features/content-graph/src/build/edge_resolver.rs new file mode 100644 index 0000000..15ab1c3 --- /dev/null +++ b/features/content-graph/src/build/edge_resolver.rs @@ -0,0 +1,191 @@ +use std::collections::{HashMap, HashSet}; + +use super::node_types::{ + ContentGraph, EdgeKind, EdgeSource, EdgeWeight, GraphEdge, GraphMeta, GraphNode, + OntologyEdgeRaw, OntologyInstance, +}; + +// ── Edge key for deduplication +// ──────────────────────────────────────────────── + +/// Unique key for a directed edge. +#[derive(Debug, PartialEq, Eq, Hash)] +struct EdgeKey { + from: String, + to: String, + kind: String, +} + +impl EdgeKey { + fn new(from: &str, to: &str, kind: &EdgeKind) -> Self { + Self { + from: from.to_owned(), + to: to.to_owned(), + kind: format!("{kind:?}"), + } + } +} + +/// Unordered pair key — used to detect existing coverage for SharedTag +/// suppression. +fn pair_key(a: &str, b: &str) -> (String, String) { + if a <= b { + (a.to_owned(), b.to_owned()) + } else { + (b.to_owned(), a.to_owned()) + } +} + +// ── Public API +// ──────────────────────────────────────────────────────────────── + +/// Resolve all edges for the graph applying the precedence: +/// +/// ```text +/// Declared > AutoBacklink > Implicit(SharedTag) +/// ``` +/// +/// For any `(from, to, kind)` triple, the highest-precedence source wins. +/// SharedTag edges are additionally suppressed when any Declared or +/// AutoBacklink edge already exists between the same node pair (in either +/// direction). +pub fn resolve_edges( + graph: &mut ContentGraph, + content_graph_metas: &[(String, GraphMeta)], // (node_id, graph_meta) + ontology_edges_raw: &[OntologyEdgeRaw], + _ontology_instance: OntologyInstance, +) { + let mut edge_map: HashMap = HashMap::new(); + + // 1. Ontology native edges (from core.ncl) — treated as Declared at ontology + // layer + for raw in ontology_edges_raw { + let Some(kind) = raw.to_edge_kind() else { + continue; + }; + let weight = raw.to_weight(); + let key = EdgeKey::new(&raw.from, &raw.to, &kind); + edge_map.entry(key).or_insert_with(|| GraphEdge { + from: raw.from.clone(), + to: raw.to.clone(), + kind, + weight, + source: EdgeSource::Declared, + note: raw.note.clone(), + }); + } + + // 2. Declared content edges + AutoBacklinks + let mut declared_pairs: HashSet<(String, String)> = HashSet::new(); + + for (node_id, meta) in content_graph_metas { + let declared = collect_declared_edges(node_id, meta); + + for edge in declared { + declared_pairs.insert(pair_key(&edge.from, &edge.to)); + + // AutoBacklink first (lower precedence — Declared will override below) + if let Some(bk_kind) = edge.kind.backlink() { + let bk_weight = bk_kind.default_weight(); + let bk_key = EdgeKey::new(&edge.to, &edge.from, &bk_kind); + edge_map.entry(bk_key).or_insert_with(|| GraphEdge { + from: edge.to.clone(), + to: edge.from.clone(), + kind: bk_kind, + weight: bk_weight, + source: EdgeSource::AutoBacklink, + note: None, + }); + } + + // Declared overwrites any existing entry for this key + let key = EdgeKey::new(&edge.from, &edge.to, &edge.kind); + edge_map.insert(key, edge); + } + } + + // 3. Implicit SharedTag edges — only when no Declared/Auto pair exists + for edge in compute_implicit_tag_edges(&graph.nodes) { + let p = pair_key(&edge.from, &edge.to); + if declared_pairs.contains(&p) { + continue; // suppressed — explicit relationship already covers this + // pair + } + let key = EdgeKey::new(&edge.from, &edge.to, &edge.kind); + edge_map.entry(key).or_insert(edge); + } + + graph.edges = edge_map.into_values().collect(); +} + +// ── Helpers +// ─────────────────────────────────────────────────────────────────── + +fn collect_declared_edges(node_id: &str, meta: &GraphMeta) -> Vec { + let mut edges = Vec::new(); + + let push = |edges: &mut Vec, targets: &[String], kind: EdgeKind| { + for target in targets { + let weight = kind.default_weight(); + edges.push(GraphEdge { + from: node_id.to_owned(), + to: target.clone(), + kind: kind.clone(), + weight, + source: EdgeSource::Declared, + note: None, + }); + } + }; + + push(&mut edges, &meta.implements, EdgeKind::Implements); + push(&mut edges, &meta.related_to, EdgeKind::RelatedTo); + push(&mut edges, &meta.part_of, EdgeKind::PartOf); + push(&mut edges, &meta.references, EdgeKind::References); + push(&mut edges, &meta.extends, EdgeKind::Extends); + + edges +} + +fn compute_implicit_tag_edges(nodes: &[GraphNode]) -> Vec { + // Build tag index: tag → [node_id] + let mut tag_index: HashMap> = HashMap::new(); + for node in nodes { + for tag in node.tags() { + tag_index + .entry(tag.clone()) + .or_default() + .push(node.id().to_owned()); + } + } + + let mut seen: HashSet<(String, String)> = HashSet::new(); + let mut edges = Vec::new(); + + for node_ids in tag_index.values() { + if node_ids.len() < 2 { + continue; + } + + for i in 0..node_ids.len() { + for j in (i + 1)..node_ids.len() { + let a = &node_ids[i]; + let b = &node_ids[j]; + let p = pair_key(a, b); + + if seen.insert(p) { + edges.push(GraphEdge { + from: a.clone(), + to: b.clone(), + kind: EdgeKind::SharedTag, + weight: EdgeWeight::Low, + source: EdgeSource::Implicit, + note: None, + }); + } + } + } + } + + edges +} diff --git a/features/content-graph/src/build/graph_generator.rs b/features/content-graph/src/build/graph_generator.rs new file mode 100644 index 0000000..1586c3e --- /dev/null +++ b/features/content-graph/src/build/graph_generator.rs @@ -0,0 +1,364 @@ +use std::path::{Path, PathBuf}; + +use glob::glob; + +use super::{ + edge_resolver::resolve_edges, + ncl_parser::{ + parse_adr, parse_content_ncl, parse_ontology_core, ContentParserConfig, + OntologyParserConfig, + }, + node_types::{AdrRaw, ContentGraph, GraphMeta, GraphNode, OntologyInstance}, + BuildError, +}; + +// ── Config ──────────────────────────────────────────────────────────────────── + +/// All paths needed to generate the content graph. +/// Populated from environment variables in `build.rs`. +pub struct GraphGeneratorConfig { + /// Root of the site's content directory (e.g., site/content/). + pub content_dir: PathBuf, + + /// Root of the site's nickel schema directory for `--import-path`. + /// Must contain `content/metadata/` with the schema files. + pub nickel_schema_dir: PathBuf, + + /// Path to `rustelo/.ontology/core.ncl`. + pub framework_ontology: PathBuf, + + /// Path to `{impl}/.ontology/core.ncl`. + pub impl_ontology: PathBuf, + + /// Glob pattern matching framework ADR files (e.g., `rustelo/adrs/*.ncl`). + /// Skips files starting with `_` automatically. + pub framework_adrs_glob: String, + + /// Glob pattern matching implementation ADR files. + pub impl_adrs_glob: String, + + /// Path to the ontoref ontology directory, for `--import-path` on ontology + /// files. Typically: `$ONTOREF_NICKEL_IMPORT_PATH` = + /// `/path/to/ontoref/ontology`. + pub ontoref_import_path: PathBuf, +} + +/// `/.ontoref/ontology/core.ncl` if it exists, else the pre-migration +/// `/.ontology/core.ncl`. +/// +/// Returns the LEGACY path when neither exists, so the caller's own existence +/// check reports the familiar location rather than a path the project has never +/// had. +fn first_existing_ontology(root: &Path) -> PathBuf { + // In a CONSTELLATION the spine lives at the parent of the code repo + // (`rustelo/.ontoref/`, with the crates under `rustelo/code/`). A + // framework_root that resolves to `code/` therefore has to look one level + // up — ADR-062's layout, and the reason `code/.ontoref/` does not exist. + // + // Four candidates, most-migrated first. The last is the pre-migration layout, + // so a project that never moved its spine still works untouched. + // Walk UP. A site nested inside a constellation (`ontoref/outreach/site`) has + // no spine of its own — it SHARES the constellation's, three levels above. + // So the search climbs rather than guessing a depth: a fixed number of `..` + // is a hardcoded layout wearing a disguise, and this generator has already + // been bitten once by exactly that. + let mut here = root.to_path_buf(); + for _ in 0..6 { + for c in [ + here.join(".ontoref").join("ontology").join("core.ncl"), + here.join(".ontology").join("core.ncl"), + ] { + if c.exists() { + return c; + } + } + match here.parent() { + Some(p) => here = p.to_path_buf(), + None => break, + } + } + // None found: return the modern path so the caller's existence check names the + // location the project SHOULD have, not one it never had. + root.join(".ontoref").join("ontology").join("core.ncl") +} + +impl GraphGeneratorConfig { + /// Build config from environment variables set in the implementation's + /// `build.rs`. + /// + /// Required env vars (no default): + /// CONTENT_GRAPH_FRAMEWORK_ONTOLOGY + /// CONTENT_GRAPH_FRAMEWORK_ADRS_GLOB + /// ONTOREF_NICKEL_IMPORT_PATH + /// + /// Optional env vars (override defaults derived from `workspace_root`): + /// CONTENT_GRAPH_CONTENT_DIR (default: {root}/site/content) + /// CONTENT_GRAPH_NICKEL_SCHEMA_DIR (default: {root}/rustelo/nickel) + /// CONTENT_GRAPH_IMPL_ONTOLOGY (default: {root}/.ontology/core.ncl) + /// CONTENT_GRAPH_IMPL_ADRS_GLOB (default: {root}/adrs/adr-*.ncl) + pub fn from_env() -> Result { + let var = |name: &'static str| -> Result { + std::env::var(name).map_err(|_| BuildError::MissingEnv(name)) + }; + + Ok(Self { + content_dir: PathBuf::from(var("CONTENT_GRAPH_CONTENT_DIR")?), + nickel_schema_dir: PathBuf::from(var("CONTENT_GRAPH_NICKEL_SCHEMA_DIR")?), + framework_ontology: PathBuf::from(var("CONTENT_GRAPH_FRAMEWORK_ONTOLOGY")?), + impl_ontology: PathBuf::from(var("CONTENT_GRAPH_IMPL_ONTOLOGY")?), + framework_adrs_glob: var("CONTENT_GRAPH_FRAMEWORK_ADRS_GLOB")?, + impl_adrs_glob: var("CONTENT_GRAPH_IMPL_ADRS_GLOB")?, + ontoref_import_path: PathBuf::from(var("ONTOREF_NICKEL_IMPORT_PATH")?), + }) + } + + /// Build config with paths derived from the implementation's workspace + /// root. + /// + /// `workspace_root` is the absolute path to the directory containing + /// `rustelo.manifest.toml` (the implementation workspace root). + /// `framework_root` is the absolute path to the rustelo framework root + /// (sibling of the implementation, e.g. `../../rustelo` from the + /// workspace). `ontoref_import_path` is the external ontoref ontology + /// directory. + /// + /// Env vars with the same names override any field if set. + pub fn with_root( + workspace_root: &Path, + framework_root: &Path, + ontoref_import_path: &Path, + ) -> Self { + let env_path = |name: &str, default: PathBuf| -> PathBuf { + std::env::var(name).map(PathBuf::from).unwrap_or(default) + }; + let env_str = + |name: &str, default: String| -> String { std::env::var(name).unwrap_or(default) }; + + Self { + content_dir: env_path( + "CONTENT_GRAPH_CONTENT_DIR", + workspace_root.join("site").join("content"), + ), + nickel_schema_dir: env_path( + "CONTENT_GRAPH_NICKEL_SCHEMA_DIR", + framework_root.join("resources").join("nickel"), + ), + // FOLLOW THE ONTOLOGY WHEN IT MOVES. + // + // These defaulted to `/.ontology/core.ncl` — the layout ontoref used BEFORE it + // moved its spine to `.ontoref/ontology/`. The ontology moved and this generator did + // not follow, so on any migrated project it asked nickel for a file that is not there + // and got back "IO error" with no hint of what it had been looking for. The graph came + // out with zero nodes, the page rendered, and nothing complained. + // + // It is the same failure as everything else this generator feeds: a witness that stays + // where it was while the thing it watches moves, and reports GREEN because it looked + // where it always looked and found nothing wrong there. + // + // `.ontoref/ontology/` first, `.ontology/` second — a pre-migration project still + // works. + framework_ontology: env_path( + "CONTENT_GRAPH_FRAMEWORK_ONTOLOGY", + first_existing_ontology(framework_root), + ), + impl_ontology: env_path( + "CONTENT_GRAPH_IMPL_ONTOLOGY", + first_existing_ontology(workspace_root), + ), + framework_adrs_glob: env_str( + "CONTENT_GRAPH_FRAMEWORK_ADRS_GLOB", + framework_root + .join("adrs") + .join("adr-*.ncl") + .display() + .to_string(), + ), + impl_adrs_glob: env_str( + "CONTENT_GRAPH_IMPL_ADRS_GLOB", + workspace_root + .join("adrs") + .join("adr-*.ncl") + .display() + .to_string(), + ), + ontoref_import_path: env_path( + "ONTOREF_NICKEL_IMPORT_PATH", + ontoref_import_path.to_path_buf(), + ), + } + } +} + +// ── Generator +// ───────────────────────────────────────────────────────────────── + +/// Build the full `ContentGraph` from all content and ontology sources. +pub fn generate(config: &GraphGeneratorConfig) -> Result { + let content_parser_cfg = ContentParserConfig { + nickel_schema_dir: config.nickel_schema_dir.clone(), + }; + + let framework_ontology_cfg = OntologyParserConfig { + ontoref_import_path: config.ontoref_import_path.clone(), + instance: OntologyInstance::Framework, + }; + + let impl_ontology_cfg = OntologyParserConfig { + ontoref_import_path: config.ontoref_import_path.clone(), + instance: OntologyInstance::Implementation, + }; + + let mut graph = ContentGraph::default(); + + // Ontology nodes + edges (both instances) + let (fw_nodes, fw_edges) = + parse_ontology_core(&config.framework_ontology, &framework_ontology_cfg)?; + let (im_nodes, im_edges) = parse_ontology_core(&config.impl_ontology, &impl_ontology_cfg)?; + + for raw in &fw_nodes { + graph + .nodes + .push(super::ncl_parser::ontology_node_to_graph_node( + raw, + OntologyInstance::Framework, + )); + } + for raw in &im_nodes { + graph + .nodes + .push(super::ncl_parser::ontology_node_to_graph_node( + raw, + OntologyInstance::Implementation, + )); + } + + // ADR nodes (both instances) + let fw_adrs = collect_adrs(&config.framework_adrs_glob, &config.ontoref_import_path)?; + let im_adrs = collect_adrs(&config.impl_adrs_glob, &config.ontoref_import_path)?; + + for adr in &fw_adrs { + graph.nodes.push(super::ncl_parser::adr_to_graph_node( + adr, + OntologyInstance::Framework, + )); + } + for adr in &im_adrs { + graph.nodes.push(super::ncl_parser::adr_to_graph_node( + adr, + OntologyInstance::Implementation, + )); + } + + // Content nodes + their graph metadata + let mut content_metas: Vec<(String, GraphMeta)> = Vec::new(); + + for (node, meta) in collect_content_nodes(&config.content_dir, &content_parser_cfg)? { + let id = node.id().to_owned(); + graph.nodes.push(node); + content_metas.push((id, meta)); + } + + // Deduplicate nodes by id (ontology nodes can appear in both instances if the + // same id is reused — last write wins by keeping first occurrence) + dedup_nodes(&mut graph.nodes); + + // Resolve all edges with precedence: Declared > AutoBacklink > Implicit + let all_ontology_edges: Vec<_> = fw_edges.into_iter().chain(im_edges).collect(); + resolve_edges( + &mut graph, + &content_metas, + &all_ontology_edges, + OntologyInstance::Framework, + ); + + // Remove edges whose from/to node does not exist in the graph + let node_ids: std::collections::HashSet = + graph.nodes.iter().map(|n| n.id().to_owned()).collect(); + + graph + .edges + .retain(|e| node_ids.contains(&e.from) && node_ids.contains(&e.to)); + + Ok(graph) +} + +// ── Internal helpers +// ────────────────────────────────────────────────────────── + +fn collect_content_nodes( + content_dir: &Path, + cfg: &ContentParserConfig, +) -> Result, BuildError> { + let pattern = content_dir.join("**").join("*.ncl").display().to_string(); + + let mut results = Vec::new(); + + for entry in glob(&pattern).map_err(|e| BuildError::Glob(e.to_string()))? { + let path = entry.map_err(|e| BuildError::Glob(e.to_string()))?; + + // Skip schema/config files and any file starting with underscore. + // Note: "index.ncl" is the canonical file for projects — do NOT skip it. + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + if stem.starts_with('_') { + continue; + } + + // Skip known schema/config NCL files (content-kinds, list_*) + if matches!(stem, "content-kinds" | "list_categories" | "list_tags") { + continue; + } + + if let Some(pair) = parse_content_ncl(&path, cfg)? { + results.push(pair); + } + } + + Ok(results) +} + +fn collect_adrs(glob_pattern: &str, ontoref_import_path: &Path) -> Result, BuildError> { + let mut adrs = Vec::new(); + + for entry in glob(glob_pattern).map_err(|e| BuildError::Glob(e.to_string()))? { + let path = entry.map_err(|e| BuildError::Glob(e.to_string()))?; + + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + if stem.starts_with('_') + || matches!(stem, "adr-defaults" | "adr-constraints" | "adr-schema") + { + continue; + } + + if let Some(adr) = parse_adr(&path, ontoref_import_path)? { + adrs.push(adr); + } + } + + Ok(adrs) +} + +fn dedup_nodes(nodes: &mut Vec) { + // For content nodes with the same logical id (bilingual content), keep the + // English ("en") variant as the canonical node so URLs use the primary + // language. Sort: content nodes with lang "en" come before other languages, + // so first-seen wins in the retain below. + nodes.sort_by(|a, b| { + let lang_a = if let GraphNode::Content { lang, .. } = a { + lang.as_str() + } else { + "" + }; + let lang_b = if let GraphNode::Content { lang, .. } = b { + lang.as_str() + } else { + "" + }; + // "en" < everything else → en nodes sort first + let en_a = if lang_a == "en" { 0u8 } else { 1 }; + let en_b = if lang_b == "en" { 0u8 } else { 1 }; + en_a.cmp(&en_b) + }); + + let mut seen = std::collections::HashSet::new(); + nodes.retain(|n| seen.insert(n.id().to_owned())); +} diff --git a/features/content-graph/src/build/mod.rs b/features/content-graph/src/build/mod.rs new file mode 100644 index 0000000..dfb6e9e --- /dev/null +++ b/features/content-graph/src/build/mod.rs @@ -0,0 +1,47 @@ +pub mod codegen; +pub mod edge_resolver; +pub mod graph_generator; +pub mod ncl_parser; +pub mod node_types; + +use std::fmt; + +#[derive(Debug)] +pub enum BuildError { + NiclCommand(String), + NclExport { path: String, stderr: String }, + NclParse(String), + Io(std::io::Error), + Json(serde_json::Error), + MissingEnv(&'static str), + Glob(String), +} + +impl fmt::Display for BuildError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NiclCommand(e) => write!(f, "nickel command failed: {e}"), + Self::NclExport { path, stderr } => { + write!(f, "nickel export failed for {path}: {stderr}") + } + Self::NclParse(e) => write!(f, "NCL JSON parse error: {e}"), + Self::Io(e) => write!(f, "I/O error: {e}"), + Self::Json(e) => write!(f, "JSON error: {e}"), + Self::MissingEnv(v) => write!(f, "missing env var: {v}"), + Self::Glob(e) => write!(f, "glob error: {e}"), + } + } +} + +impl std::error::Error for BuildError {} + +impl From for BuildError { + fn from(e: std::io::Error) -> Self { + Self::Io(e) + } +} +impl From for BuildError { + fn from(e: serde_json::Error) -> Self { + Self::Json(e) + } +} diff --git a/features/content-graph/src/build/ncl_parser.rs b/features/content-graph/src/build/ncl_parser.rs new file mode 100644 index 0000000..5afbe5e --- /dev/null +++ b/features/content-graph/src/build/ncl_parser.rs @@ -0,0 +1,335 @@ +use std::path::{Path, PathBuf}; +use std::process::Command; + +use serde_json::Value; + +use super::{ + node_types::{ + AdrRaw, ContentKind, GraphMeta, GraphNode, OntologyEdgeRaw, OntologyInstance, + OntologyNodeRaw, + }, + BuildError, +}; + +// ── NCL export +// ──────────────────────────────────────────────────────────────── + +/// Run `nickel export --format json` with the given import paths. +/// Returns the parsed JSON value. +fn export_ncl(file: &Path, import_paths: &[&Path]) -> Result { + let mut cmd = Command::new("nickel"); + cmd.arg("export").arg("--format").arg("json"); + + for p in import_paths { + cmd.arg("--import-path").arg(p); + } + cmd.arg(file); + + let out = cmd + .output() + .map_err(|e| BuildError::NiclCommand(e.to_string()))?; + + if !out.status.success() { + return Err(BuildError::NclExport { + path: file.display().to_string(), + stderr: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + + serde_json::from_slice(&out.stdout).map_err(|e| BuildError::NclParse(e.to_string())) +} + +// ── Content NCL parsing +// ─────────────────────────────────────────────────────── + +/// Configuration for parsing content NCL files. +pub struct ContentParserConfig { + /// Root of the site's nickel schema directory (contains content/metadata/). + /// Used as --import-path for nickel export on content files. + pub nickel_schema_dir: PathBuf, +} + +/// Parse a single content `.ncl` file and extract graph metadata + node info. +/// Returns `None` if the file is not published or is a draft. +pub fn parse_content_ncl( + file: &Path, + config: &ContentParserConfig, +) -> Result, BuildError> { + // Emit rerun directive for incremental builds + println!("cargo:rerun-if-changed={}", file.display()); + + let import_paths = [ + config.nickel_schema_dir.as_path(), + file.parent().unwrap_or(Path::new(".")), + ]; + + let value = export_ncl(file, &import_paths)?; + + // Skip unpublished and draft content + if value.get("published").and_then(Value::as_bool) == Some(false) { + return Ok(None); + } + if value.get("draft").and_then(Value::as_bool) == Some(true) { + return Ok(None); + } + + let graph_meta = extract_graph_meta(&value); + let node = build_content_node(file, &value)?; + + Ok(Some((node, graph_meta))) +} + +fn extract_graph_meta(value: &Value) -> GraphMeta { + let empty = Value::Object(Default::default()); + let graph = value.get("graph").unwrap_or(&empty); + + GraphMeta { + implements: str_array(graph, "implements"), + related_to: str_array(graph, "related_to"), + part_of: str_array(graph, "part_of"), + references: str_array(graph, "references"), + extends: str_array(graph, "extends"), + } +} + +fn build_content_node(file: &Path, value: &Value) -> Result { + let (content_kind, lang, category) = infer_content_kind_and_lang(file); + + let id = value + .get("id") + .and_then(Value::as_str) + .or_else(|| value.get("slug").and_then(Value::as_str)) + .unwrap_or_else(|| { + file.file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("unknown") + }) + .to_owned(); + + let title = value + .get("title") + .and_then(Value::as_str) + .unwrap_or("Untitled") + .to_owned(); + + let slug = value + .get("slug") + .and_then(Value::as_str) + .unwrap_or(&id) + .to_owned(); + + let page_route = value.get("page_route").and_then(Value::as_str); + + let url = if let Some(route) = page_route { + route.to_owned() + } else { + build_content_url(&content_kind, &lang, category.as_deref(), &slug) + }; + + let tags = str_array(value, "tags"); + + let excerpt = value + .get("excerpt") + .and_then(Value::as_str) + .map(str::to_owned); + + Ok(GraphNode::Content { + id, + title, + content_kind, + lang, + url, + tags, + excerpt, + }) +} + +/// Infer content kind, language, and optional category from the file path. +/// +/// Expected path segments (relative to site/content/): +/// blog/en/category/post.ncl → Blog, "en", Some("category") +/// recipes/es/category/recipe.ncl → Recipe, "es", Some("category") +/// projects/en/slug/index.ncl → Project, "en", None +/// activities/en/category/item.ncl → Activity, "en", Some("category") +fn infer_content_kind_and_lang(file: &Path) -> (ContentKind, String, Option) { + let parts: Vec<&str> = file + .components() + .filter_map(|c| c.as_os_str().to_str()) + .collect(); + + // Find "blog" | "recipes" | "projects" | "activities" in path + let kind_idx = parts + .iter() + .position(|&s| matches!(s, "blog" | "recipes" | "projects" | "activities")); + + let Some(ki) = kind_idx else { + return (ContentKind::Blog, "en".into(), None); + }; + + let kind = match parts[ki] { + "recipes" => ContentKind::Recipe, + "projects" => ContentKind::Project, + "activities" => ContentKind::Activity, + _ => ContentKind::Blog, + }; + + let lang = parts.get(ki + 1).copied().unwrap_or("en").to_owned(); + let category = if matches!( + kind, + ContentKind::Blog | ContentKind::Recipe | ContentKind::Activity + ) { + parts.get(ki + 2).map(|s| (*s).to_owned()) + } else { + None + }; + + (kind, lang, category) +} + +fn build_content_url(kind: &ContentKind, lang: &str, category: Option<&str>, slug: &str) -> String { + let segment = kind.url_segment_for_lang(lang); + match (kind, category) { + (ContentKind::Project, _) => format!("/{segment}/{slug}"), + (_, Some(cat)) => format!("/{segment}/{cat}/{slug}"), + (_, None) => format!("/{segment}/{slug}"), + } +} + +// ── Ontology NCL parsing +// ────────────────────────────────────────────────────── + +/// Configuration for parsing ontology NCL files. +pub struct OntologyParserConfig { + /// Path to the ontoref ontology directory (contains defaults/core.ncl). + /// Provided via `ONTOREF_NICKEL_IMPORT_PATH` environment variable. + pub ontoref_import_path: PathBuf, + pub instance: OntologyInstance, +} + +/// Parse a `core.ncl` file and return (nodes, edges). +pub fn parse_ontology_core( + file: &Path, + config: &OntologyParserConfig, +) -> Result<(Vec, Vec), BuildError> { + println!("cargo:rerun-if-changed={}", file.display()); + + // AN ONTOLOGY RESOLVES ITS IMPORTS AGAINST ITS OWN SPINE. + // + // `core.ncl` opens with `import "defaults/core.ncl"`, and that path is relative + // to the SPINE (`.ontoref/`), not to `ontology/`. The only import paths + // passed were a single global `ontoref_import_path` and the file's own + // directory — so when two ontologies from DIFFERENT projects are parsed in + // one run (the framework's and the implementation's, which is the whole + // point of this parser), each was handed the OTHER project's spine and neither + // could find its own defaults. One global import path cannot serve two + // projects. + // + // The file's grandparent IS its spine: `/.ontoref/ontology/core.ncl` → + // `/.ontoref`. + let own_spine = file.parent().and_then(Path::parent); + let mut import_paths: Vec<&Path> = vec![config.ontoref_import_path.as_path()]; + if let Some(sp) = own_spine { + import_paths.push(sp); + } + if let Some(dir) = file.parent() { + import_paths.push(dir); + } + + let value = export_ncl(file, &import_paths)?; + + let nodes = value + .get("nodes") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(|v| serde_json::from_value(v.clone()).ok()) + .collect() + }) + .unwrap_or_default(); + + let edges = value + .get("edges") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(|v| serde_json::from_value(v.clone()).ok()) + .collect() + }) + .unwrap_or_default(); + + Ok((nodes, edges)) +} + +// ── ADR NCL parsing +// ─────────────────────────────────────────────────────────── + +/// Parse a single ADR `.ncl` file. +pub fn parse_adr(file: &Path, ontoref_import_path: &Path) -> Result, BuildError> { + println!("cargo:rerun-if-changed={}", file.display()); + + let dir = file.parent().unwrap_or(Path::new(".")); + let import_paths = [ontoref_import_path, dir]; + + let value = export_ncl(file, &import_paths)?; + + // Skip template files (id starts with "_" or is missing) + let id = match value.get("id").and_then(Value::as_str) { + Some(id) if !id.starts_with('_') => id.to_owned(), + _ => return Ok(None), + }; + + let adr = AdrRaw { + id, + title: value + .get("title") + .and_then(Value::as_str) + .unwrap_or("Untitled ADR") + .to_owned(), + status: value + .get("status") + .and_then(Value::as_str) + .unwrap_or("Unknown") + .to_owned(), + }; + + Ok(Some(adr)) +} + +// ── Conversion helpers (used by graph_generator) +// ────────────────────────────── + +pub fn ontology_node_to_graph_node(raw: &OntologyNodeRaw, instance: OntologyInstance) -> GraphNode { + GraphNode::Ontology { + id: raw.id.clone(), + name: raw.name.clone(), + level: raw.level.clone(), + pole: raw.pole.clone(), + description: raw.description.clone(), + instance, + artifact_paths: raw.artifact_paths.clone(), + } +} + +pub fn adr_to_graph_node(raw: &AdrRaw, instance: OntologyInstance) -> GraphNode { + GraphNode::Adr { + id: raw.id.clone(), + title: raw.title.clone(), + status: raw.status.clone(), + instance, + } +} + +// ── Helpers +// ─────────────────────────────────────────────────────────────────── + +fn str_array(value: &Value, key: &str) -> Vec { + value + .get(key) + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} diff --git a/features/content-graph/src/build/node_types.rs b/features/content-graph/src/build/node_types.rs new file mode 100644 index 0000000..bb4f219 --- /dev/null +++ b/features/content-graph/src/build/node_types.rs @@ -0,0 +1,286 @@ +use serde::{Deserialize, Serialize}; + +// ── Enums ───────────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum ContentKind { + Blog, + Recipe, + Project, + Activity, +} + +impl ContentKind { + /// URL path segment for this content type in the given language. + /// + /// Matches the localized route patterns in `site/config/routes.ncl`. + pub fn url_segment_for_lang(&self, lang: &str) -> &'static str { + match (self, lang) { + (Self::Recipe, "es") => "recetas", + (Self::Project, "es") => "proyectos", + (Self::Activity, "es") => "actividades", + (Self::Blog, _) => "blog", + (Self::Recipe, _) => "recipes", + (Self::Project, _) => "projects", + (Self::Activity, _) => "activities", + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "PascalCase")] +pub enum OntologyLevel { + Axiom, + Tension, + Practice, + Project, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum OntologyInstance { + Framework, + Implementation, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "PascalCase")] +pub enum Pole { + Yang, + Yin, + Spiral, +} + +/// Edge kinds that can appear between any two graph nodes. +/// +/// Declared* variants come from explicit `.ncl` `graph` fields. +/// Auto* variants are generated as backlinks. +/// Ontology* variants are read directly from `core.ncl` edges. +/// SharedTag is computed from shared tag arrays. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum EdgeKind { + // Content → Ontology/Content (declared) + Implements, + RelatedTo, + PartOf, + References, + Extends, + // Auto-generated backlinks + ImplementedBy, + RelatedFrom, + ParentOf, + ReferencedBy, + ExtendedBy, + // Ontology native (from core.ncl edges) + ManifestsIn, + Resolves, + Complements, + DependsOn, + DocumentedIn, + // Implicit — suppressed when a Declared/Auto edge exists for the same pair + SharedTag, +} + +impl EdgeKind { + /// Returns the inverse kind used for auto-backlinks. + /// Ontology and SharedTag edges have no automatic backlink. + pub fn backlink(&self) -> Option { + match self { + Self::Implements => Some(Self::ImplementedBy), + Self::RelatedTo => Some(Self::RelatedFrom), + Self::PartOf => Some(Self::ParentOf), + Self::References => Some(Self::ReferencedBy), + Self::Extends => Some(Self::ExtendedBy), + _ => None, + } + } + + pub fn default_weight(&self) -> EdgeWeight { + match self { + Self::Implements | Self::ManifestsIn | Self::Resolves => EdgeWeight::High, + Self::RelatedTo | Self::Complements | Self::DependsOn | Self::DocumentedIn => { + EdgeWeight::Medium + } + Self::PartOf | Self::References | Self::Extends => EdgeWeight::Medium, + _ => EdgeWeight::Low, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EdgeWeight { + High, + Medium, + Low, +} + +/// Determines merge precedence when two edges share the same (from, to, kind) +/// key. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EdgeSource { + Declared, // explicit in content .ncl graph field — highest + AutoBacklink, // generated from a Declared edge + Implicit, // SharedTag — lowest, suppressed by any Declared/Auto on same pair +} + +// ── Nodes ───────────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum GraphNode { + Content { + id: String, + title: String, + content_kind: ContentKind, + lang: String, + url: String, + tags: Vec, + excerpt: Option, + }, + Ontology { + id: String, + name: String, + level: OntologyLevel, + pole: Option, + description: String, + instance: OntologyInstance, + artifact_paths: Vec, + }, + Adr { + id: String, + title: String, + status: String, + instance: OntologyInstance, + }, +} + +impl GraphNode { + pub fn id(&self) -> &str { + match self { + Self::Content { id, .. } => id, + Self::Ontology { id, .. } => id, + Self::Adr { id, .. } => id, + } + } + + pub fn title(&self) -> &str { + match self { + Self::Content { title, .. } => title, + Self::Ontology { name, .. } => name, + Self::Adr { title, .. } => title, + } + } + + pub fn tags(&self) -> &[String] { + match self { + Self::Content { tags, .. } => tags, + _ => &[], + } + } + + /// The URL slug (last path segment) for content nodes, `None` for others. + /// When the slug differs from `id` (e.g. `id = "post-2024"`, url ends in + /// `"modern-post-title"`), this is what the PostViewer passes as `node_id`. + pub fn url_slug(&self) -> Option<&str> { + if let Self::Content { url, .. } = self { + url.rsplit('/').next() + } else { + None + } + } +} + +// ── Edges ───────────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GraphEdge { + pub from: String, + pub to: String, + pub kind: EdgeKind, + pub weight: EdgeWeight, + pub source: EdgeSource, + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +// ── Graph ───────────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct ContentGraph { + pub nodes: Vec, + pub edges: Vec, +} + +// ── Raw NCL deserialization types +// ───────────────────────────────────────────── + +/// Parsed from the `graph` field of a content .ncl file. +#[derive(Debug, Deserialize, Default)] +pub struct GraphMeta { + #[serde(default)] + pub implements: Vec, + #[serde(default)] + pub related_to: Vec, + #[serde(default)] + pub part_of: Vec, + #[serde(default)] + pub references: Vec, + #[serde(default)] + pub extends: Vec, +} + +/// Raw ontology node as exported from `core.ncl`. +#[derive(Debug, Deserialize)] +pub struct OntologyNodeRaw { + pub id: String, + pub name: String, + pub level: OntologyLevel, + pub pole: Option, + pub description: String, + #[serde(default)] + pub artifact_paths: Vec, +} + +/// Raw ontology edge as exported from `core.ncl`. +#[derive(Debug, Deserialize)] +pub struct OntologyEdgeRaw { + pub from: String, + pub to: String, + pub kind: String, + pub weight: String, + #[serde(default)] + pub note: Option, +} + +impl OntologyEdgeRaw { + pub fn to_edge_kind(&self) -> Option { + match self.kind.as_str() { + "ManifestsIn" => Some(EdgeKind::ManifestsIn), + "Resolves" => Some(EdgeKind::Resolves), + "Complements" => Some(EdgeKind::Complements), + "DependsOn" => Some(EdgeKind::DependsOn), + "DocumentedIn" => Some(EdgeKind::DocumentedIn), + _ => None, + } + } + + pub fn to_weight(&self) -> EdgeWeight { + match self.weight.as_str() { + "High" => EdgeWeight::High, + "Medium" => EdgeWeight::Medium, + _ => EdgeWeight::Low, + } + } +} + +/// Raw ADR as exported from `adrs/*.ncl`. +#[derive(Debug, Deserialize)] +pub struct AdrRaw { + pub id: String, + pub title: String, + pub status: String, +} diff --git a/features/content-graph/src/lib.rs b/features/content-graph/src/lib.rs new file mode 100644 index 0000000..76f610c --- /dev/null +++ b/features/content-graph/src/lib.rs @@ -0,0 +1 @@ +pub mod build; diff --git a/features/content-graph/templates/assets_ncl_fragment.ncl b/features/content-graph/templates/assets_ncl_fragment.ncl new file mode 100644 index 0000000..3846596 --- /dev/null +++ b/features/content-graph/templates/assets_ncl_fragment.ncl @@ -0,0 +1,22 @@ +# content-graph asset additions — merge this into site/config/assets.ncl. +# +# The `rustelo add content-graph` command writes this file to +# site/config/assets_content_graph.ncl and server/build.rs must merge it +# with the base assets.ncl before generating shell_asset_paths.rs. +# +# Alternatively, copy the relevant paths directly into assets.ncl. + +{ + assets = { + source_js = [ + "/js/cytoscape.min.js", + "/js/cytoscape-cose-bilkent.js", + "/js/content-graph-shim.js", + ], + bundled_js = [ + "/js/cytoscape.min.js", + "/js/cytoscape-cose-bilkent.js", + "/js/content-graph-shim.js", + ], + }, +} diff --git a/features/content-graph/templates/build_rs_snippet.rs b/features/content-graph/templates/build_rs_snippet.rs new file mode 100644 index 0000000..1f1fb62 --- /dev/null +++ b/features/content-graph/templates/build_rs_snippet.rs @@ -0,0 +1,35 @@ +// content-graph feature — build.rs integration snippet. +// +// Add this block to the implementation's server/build.rs (or as a separate +// build step) after sourcing the required environment variables. +// +// Required .env entries (add to foundation/.env): +// +// CONTENT_GRAPH_CONTENT_DIR=site/content +// CONTENT_GRAPH_NICKEL_SCHEMA_DIR=rustelo/nickel +// CONTENT_GRAPH_FRAMEWORK_ONTOLOGY=/abs/path/to/rustelo/.ontology/core.ncl +// CONTENT_GRAPH_IMPL_ONTOLOGY=.ontology/core.ncl +// CONTENT_GRAPH_FRAMEWORK_ADRS_GLOB=/abs/path/to/rustelo/adrs/adr-*.ncl +// CONTENT_GRAPH_IMPL_ADRS_GLOB=adrs/adr-*.ncl +// ONTOREF_NICKEL_IMPORT_PATH=/abs/path/to/ontoref/ontology + +fn generate_content_graph() { + use content_graph::build::{codegen, graph_generator::GraphGeneratorConfig}; + + let config = GraphGeneratorConfig::from_env() + .expect("content-graph: missing required environment variables — see templates/build_rs_snippet.rs"); + + let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap()); + + let graph = graph_generator::generate(&config) + .expect("content-graph: graph generation failed"); + + codegen::write_outputs(&graph, &out_dir) + .expect("content-graph: codegen write failed"); + + // Invalidate when any ontology or ADR file changes + println!("cargo:rerun-if-env-changed=CONTENT_GRAPH_CONTENT_DIR"); + println!("cargo:rerun-if-env-changed=ONTOREF_NICKEL_IMPORT_PATH"); + println!("cargo:rerun-if-changed={}", config.framework_ontology.display()); + println!("cargo:rerun-if-changed={}", config.impl_ontology.display()); +} diff --git a/features/content-graph/templates/components/graph_mini.rs b/features/content-graph/templates/components/graph_mini.rs new file mode 100644 index 0000000..6e00786 --- /dev/null +++ b/features/content-graph/templates/components/graph_mini.rs @@ -0,0 +1,43 @@ +// content_graph/graph_mini.rs +// +// Inline ego-network SVG for embedding in content pages. +// Static SVG generated at build time — no JS, no Cytoscape, no hydration risk. +// Uses inner_html so SSR and WASM produce structurally identical DOM. + +use leptos::prelude::*; + +use super::generated::mini::GRAPH_MINI_SVGS; + +/// Inline ego-network SVG for the given node. +/// +/// Renders nothing if the node has no ego SVG (e.g. orphan nodes or +/// non-content nodes that don't get SVGs generated). +#[component] +pub fn GraphMini( + node_id: String, + #[prop(optional)] class: Option, +) -> impl IntoView { + let svg: Option<&'static str> = GRAPH_MINI_SVGS + .iter() + .find(|(id, _)| *id == node_id.as_str()) + .map(|(_, svg)| *svg); + + let Some(svg) = svg else { + return view! { <> }.into_any(); + }; + + let wrapper_class = format!( + "content-graph-mini-wrapper {}", + class.unwrap_or_default() + ); + + // inner_html with a static &str guarantees SSR == WASM DOM structure. + // No reactive signals, no placeholders, no hydration mismatch possible. + view! { +