Example of Logic Circuit Diagram in ASP.NET MVC Diagram Control
Logic Circuit Diagram: a half adder. Switch the inputs with the buttons and the outputs light up; wires carrying a 1 are green. Add gates from the palette and draw wires from a gate's output (its right port) to another's input.
@Html.UiSymbolPalette((UiSymbolPaletteOptions)ViewData["palette"])
@Html.UiDiagram((UiDiagramOptions)ViewData["diagram"])
<p>
Logic Circuit Diagram: a half adder. Switch the inputs with the buttons and the outputs light up; wires carrying a 1 are green.
Add gates from the palette and draw wires from a gate's output (its right port) to another's input.
</p>
<div class="mb-2" role="group" aria-label="Inputs" id="logicInputs"></div>
<p class="small text-muted" id="diagramStatus" role="status" aria-live="polite"></p>
<div class="row g-2">
<div class="col-lg-3">
@Html.UiSymbolPalette((UiSymbolPaletteOptions)ViewData["palette"])
</div>
<div class="col-lg-9">
@Html.UiDiagram((UiDiagramOptions)ViewData["diagram"])
</div>
</div>
<script>
window.DiagramSamples = (function () {
'use strict';
var ID = 'logicDiagram';
function status(text) {
var el = document.getElementById('diagramStatus');
if (el) { el.textContent = text; }
}
function isInput(n) { return n.shape.type === 'Logic' && (n.shape.shape === 'Input' || n.shape.shape === 'Clock'); }
/** An input's value is the last character of its text: "A = 1". */
function valueOfInput(n) { var t = n.annotations.length ? n.annotations[0].content : ''; return t.charAt(t.length - 1) === '1' ? 1 : 0; }
/** Works out every gate's output from the inputs, lights the outputs and colours the wires that carry a 1. */
function evaluate() {
var d = Lumen.get(ID);
if (!d) { return; }
var byId = {};
d.nodes.forEach(function (n) { byId[n.id] = n; });
var value = {};
var valueOf = function (id, seen) {
if (value[id] !== undefined) { return value[id]; }
var n = byId[id];
if (!n || n.shape.type !== 'Logic' || seen[id]) { return 0; }
seen[id] = true;
if (isInput(n)) { value[id] = valueOfInput(n); return value[id]; }
var ins = d.connectors.filter(function (c) { return c.targetID === id && c.sourceID; })
.sort(function (x, y) { return String(x.targetPortID).localeCompare(String(y.targetPortID)); })
.map(function (c) { return valueOf(c.sourceID, seen); });
var a = ins[0] || 0;
var b = ins[1] || 0;
var result = { AndGate: a & b, OrGate: a | b, NandGate: 1 - (a & b), NorGate: 1 - (a | b), XorGate: a ^ b, XnorGate: 1 - (a ^ b), NotGate: 1 - a, Buffer: a, Output: a }[n.shape.shape];
value[id] = result || 0;
return value[id];
};
d.nodes.forEach(function (n) { valueOf(n.id, {}); });
d.nodes.forEach(function (n) {
if (n.shape.type !== 'Logic') { return; }
if (n.shape.shape === 'Output') { n.style.fill = value[n.id] ? '#ffeb3b' : null; }
if (isInput(n)) { n.style.fill = value[n.id] ? '#c8e6c9' : null; }
});
d.connectors.forEach(function (c) { c.style.strokeColor = c.sourceID && value[c.sourceID] ? '#2e7d32' : null; });
d.dataBind();
buttons(d);
var outs = d.nodes.filter(function (n) { return n.shape.type === 'Logic' && n.shape.shape === 'Output'; });
status(outs.map(function (n) { return (n.annotations.length ? n.annotations[0].content : n.id) + ' = ' + value[n.id]; }).join(', ') + '.');
}
/** A button for each input, saying its value. */
function buttons(d) {
var bar = document.getElementById('logicInputs');
bar.innerHTML = '';
d.nodes.filter(isInput).forEach(function (n) {
var b = document.createElement('button');
b.type = 'button';
b.className = 'btn btn-sm btn-outline-primary me-1';
b.setAttribute('data-input', n.id);
b.setAttribute('aria-pressed', valueOfInput(n) ? 'true' : 'false');
b.textContent = 'Switch ' + (n.annotations.length ? n.annotations[0].content.replace(/\s*=\s*[01]$/, '') : n.id);
bar.appendChild(b);
});
}
document.addEventListener('click', function (e) {
var b = e.target.closest ? e.target.closest('[data-input]') : null;
if (!b) { return; }
var d = Lumen.get(ID);
var n = d.getNodeObject(b.getAttribute('data-input'));
if (!n) { return; }
var t = n.annotations.length ? n.annotations[0].content.replace(/\s*=\s*[01]$/, '') : n.id;
var next = valueOfInput(n) ? 0 : 1;
if (n.annotations.length) { n.annotations[0].content = t + ' = ' + next; } else { n.annotations.push({ content: t + ' = ' + next }); }
evaluate();
var again = document.querySelector('[data-input="' + n.id + '"]');
if (again) { again.focus(); }
});
/** OnCreated, and after a change of the circuit: work it out again (once the change is done). */
function created() { window.setTimeout(evaluate, 0); }
function changed() { window.setTimeout(evaluate, 0); }
function clicked() { }
return { created: created, changed: changed, clicked: clicked, evaluate: evaluate };
})();
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class DiagramController : Controller
{
// The page is Views/Diagram/LogicCircuitDiagram.cshtml; it draws what ViewData holds.
public ActionResult LogicCircuitDiagram()
{
{
var gates = new[] { "AndGate", "OrGate", "NotGate", "NandGate", "NorGate", "XorGate", "XnorGate", "Buffer" }.Select(k => Gate(k.ToLowerInvariant(), 0, 0, k)).ToList();
var io = new[] { "Input", "Output", "Clock" }.Select(k => Gate(k.ToLowerInvariant(), 0, 0, k, k == "Input" ? "In = 0" : k == "Output" ? "Out" : null)).ToList();
var wire = Wire("x", null, null, null);
ViewData["palette"] = new UiSymbolPaletteOptions
{
Id = "logicPalette", TargetId = "logicDiagram", Height = "520px", Width = "100%", AriaLabel = "Logic gates",
Palettes = new List<UiSymbolPalette>
{
new UiSymbolPalette { Id = "gates", Title = "Gates", Symbols = gates },
new UiSymbolPalette { Id = "io", Title = "Inputs and outputs", Symbols = io },
new UiSymbolPalette { Id = "wires", Title = "Wires", ConnectorSymbols = new List<UiDiagramConnector> { LinkSymbol("wire", wire) } }
}
};
}
{
ViewData["diagram"] = new UiDiagramOptions
{
Id = "logicDiagram",
AvoidConnectorOverlap = true,
Height = "520px",
AriaLabel = "Logic circuit: a half adder",
Nodes = new List<UiDiagramNode>
{
Gate("a", 80, 120, "Input", "A = 0"), Gate("b", 80, 260, "Input", "B = 0"),
Gate("xor", 300, 120, "XorGate"), Gate("and", 300, 260, "AndGate"), Gate("not", 480, 380, "NotGate"),
Gate("sum", 520, 120, "Output", "Sum"), Gate("carry", 520, 260, "Output", "Carry"), Gate("noCarry", 660, 380, "Output", "No carry")
},
Connectors = new List<UiDiagramConnector>
{
Wire("w1", "a", "xor", "in1"), Wire("w2", "b", "xor", "in2"), Wire("w3", "a", "and", "in1"), Wire("w4", "b", "and", "in2"),
Wire("w5", "xor", "sum", "in"), Wire("w6", "and", "carry", "in"), Wire("w7", "and", "not", "in"), Wire("w8", "not", "noCarry", "in")
},
OnClick = "DiagramSamples.clicked",
OnCreated = "DiagramSamples.created",
OnCollectionChange = "DiagramSamples.changed",
OnConnectionChange = "DiagramSamples.changed"
};
}
return View();
}
private static UiDiagramNode Shape(string id, double x, double y, UiDiagramShapeType type, string shape, double width, double height, string text = null, string fill = null)
{
var node = new UiDiagramNode
{
Id = id, OffsetX = x, OffsetY = y, Width = width, Height = height,
Shape = new UiDiagramShape { Type = type, Shape = shape },
Style = new UiDiagramStyle { Fill = fill }
};
if (text != null) { node.Annotations.Add(new UiDiagramAnnotation { Content = text }); }
return node;
}
/// <summary>A connector symbol for a palette: a sample of the line, not attached to anything.</summary>
private static UiDiagramConnector LinkSymbol(string id, UiDiagramConnector look)
{
look.Id = id;
look.SourceID = null;
look.TargetID = null;
look.SourcePoint = new UiDiagramPoint { X = 0, Y = 0 };
look.TargetPoint = new UiDiagramPoint { X = 120, Y = 60 };
look.Annotations.Clear();
return look;
}
/// <summary>A gate (or an input or output) with its ports: in1 and in2 (or in) on the left, out on the right.</summary>
private static UiDiagramNode Gate(string id, double x, double y, string kind, string text = null)
{
bool io = kind == "Input" || kind == "Clock" || kind == "Output";
UiDiagramNode n = Shape(id, x, y, UiDiagramShapeType.Logic, kind, io ? 70 : 80, io ? 40 : 50, null);
if (text != null) { n.Annotations.Add(new UiDiagramAnnotation { Content = text, Offset = new UiDiagramPoint { X = kind == "Output" ? 1.45 : 0.37, Y = 0.5 } }); }
System.Action<string, double, double> port = (pid, px, py) => n.Ports.Add(new UiDiagramPort { Id = pid, Offset = new UiDiagramPoint { X = px, Y = py }, Width = 6, Height = 6, AllowDraw = true });
if (kind == "Output") { port("in", 0, 0.5); return n; }
if (kind == "NotGate" || kind == "Buffer") { port("in", 0, 0.5); }
else if (!io) { port("in1", 0, 1.0 / 3); port("in2", 0, 2.0 / 3); }
port("out", 1, 0.5);
return n;
}
private static UiDiagramConnector Wire(string id, string from, string to, string toPort, string fromPort = "out")
{
var c = new UiDiagramConnector { Id = id, SourceID = from, SourcePortID = fromPort, TargetID = to, TargetPortID = toPort, Type = UiDiagramConnectorType.Orthogonal };
c.TargetDecorator = new UiDiagramDecorator { Shape = UiDiagramDecoratorShape.None };
c.Style = new UiDiagramStyle { StrokeWidth = 2 };
return c;
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>