Merge remote-tracking branch 'refs/remotes/praeclarum/master'

This commit is contained in:
Javier Suárez Ruiz 2018-02-08 20:07:51 +01:00
commit 03d545f3e3
54 changed files with 855 additions and 234 deletions

View File

@ -14,13 +14,16 @@ var ctx = canvas.getContext('2d');
var r = "static readonly double[] CharacterProportions = {\n ";
var head = "";
let size = 16;
let size = 24;
ctx.font = "bold " + size + "px \"Helvetica Neue\"";
var mmm = ctx.measureText("MM");
let sp = 0;
let np = 0;
let mw = 0;
let tx = 0;
let ty = size;
let widths = {};
for (let i = 0; i < 128; i++) {
if (i > 0 && i % 8 == 0) {
head = ",\n ";
@ -32,6 +35,13 @@ for (let i = 0; i < 128; i++) {
let s = "M" + c + "M";
let m = ctx.measureText(s);
let w = m.width - mmm.width;
if (tx + w > 320) {
tx = 0;
ty += size;
}
ctx.fillText(c, tx, ty);
ctx.strokeRect(tx, ty - size, w, size);
tx += w;
let p = w / size;
if (p > 1e-4) {
sp += p;
@ -41,9 +51,19 @@ for (let i = 0; i < 128; i++) {
mw = w;
}
r += head + p;
widths[c] = w;
console.log (c + " = " + w);
}
let test = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
let testLen = 0;
for (const i in test) {
const w = widths[test[i]];
testLen += w;
}
console.log("TEST COMP LEN = " + testLen);
console.log("TEST REAL LEN = " + ctx.measureText(test).width);
let ap = sp / np;
let padding = (mmm.width - mw*2)/size;
r += "\n};\nconst double AverageCharProportion = " + ap + ";";

View File

@ -1,33 +1,56 @@
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Ooui.AspNetCore
{
public class ElementResult : ActionResult
{
{
readonly Element element;
readonly string title;
readonly string title;
public ElementResult (Element element, string title = "")
{
{
this.element = element;
this.title = title;
this.title = title;
}
public override async Task ExecuteResultAsync (ActionContext context)
public override async Task ExecuteResultAsync (ActionContext context)
{
var response = context.HttpContext.Response;
response.StatusCode = 200;
response.ContentType = "text/html; charset=utf-8";
if (element.WantsFullScreen) {
element.Style.Width = GetCookieDouble (context.HttpContext.Request.Cookies, "oouiWindowWidth", 32, 640, 10000);
element.Style.Height = GetCookieDouble (context.HttpContext.Request.Cookies, "oouiWindowHeight", 24, 480, 10000);
}
var sessionId = WebSocketHandler.BeginSession (context.HttpContext, element);
var html = UI.RenderTemplate (WebSocketHandler.WebSocketPath + "?id=" + sessionId, title: title);
var initialHtml = element.OuterHtml;
var html = UI.RenderTemplate (WebSocketHandler.WebSocketPath + "?id=" + sessionId, title: title, initialHtml: initialHtml);
var htmlBytes = Encoding.UTF8.GetBytes (html);
response.ContentLength = htmlBytes.Length;
using (var s = response.Body) {
await s.WriteAsync (htmlBytes, 0, htmlBytes.Length).ConfigureAwait (false);
}
}
static double GetCookieDouble (IRequestCookieCollection cookies, string key, double min, double def, double max)
{
if (cookies.TryGetValue (key, out var s)) {
if (double.TryParse (s, out var d)) {
if (d < min) return min;
if (d > max) return max;
return d;
}
return def;
}
else {
return def;
}
}
}
}

View File

@ -0,0 +1,16 @@
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Ooui.AspNetCore.TagHelpers
{
public class OouiTagHelper : TagHelper
{
public Ooui.Element Element { get; set; }
public override void Process (TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
output.TagMode = TagMode.StartTagAndEndTag;
output.Content.SetHtmlContent (Element.OuterHtml);
}
}
}

View File

@ -13,19 +13,19 @@ namespace Ooui.AspNetCore
public static TimeSpan SessionTimeout { get; set; } = TimeSpan.FromMinutes (5);
static readonly ConcurrentDictionary<string, PendingSession> pendingSessions =
new ConcurrentDictionary<string, PendingSession> ();
static readonly ConcurrentDictionary<string, ActiveSession> activeSessions =
new ConcurrentDictionary<string, ActiveSession> ();
public static string BeginSession (HttpContext context, Element element)
{
var id = Guid.NewGuid ().ToString ("N");
var s = new PendingSession {
var s = new ActiveSession {
Element = element,
RequestTimeUtc = DateTime.UtcNow,
LastConnectTimeUtc = DateTime.UtcNow,
};
if (!pendingSessions.TryAdd (id, s)) {
if (!activeSessions.TryAdd (id, s)) {
throw new Exception ("Failed to schedule pending session");
}
@ -60,20 +60,21 @@ namespace Ooui.AspNetCore
}
//
// Find the pending session
// Clear old sessions
//
if (!pendingSessions.TryRemove (id, out var pendingSession)) {
BadRequest ("Unknown `id`");
return;
var toClear = activeSessions.Where (x => (DateTime.UtcNow - x.Value.LastConnectTimeUtc) > SessionTimeout).ToList ();
foreach (var c in toClear) {
activeSessions.TryRemove (c.Key, out var _);
}
//
// Reject the session if it's old
// Find the pending session
//
if ((DateTime.UtcNow - pendingSession.RequestTimeUtc) > SessionTimeout) {
BadRequest ("Old `id`");
if (!activeSessions.TryGetValue (id, out var activeSession)) {
BadRequest ("Unknown `id`");
return;
}
activeSession.LastConnectTimeUtc = DateTime.UtcNow;
//
// Set the element's dimensions
@ -97,14 +98,14 @@ namespace Ooui.AspNetCore
//
var token = CancellationToken.None;
var webSocket = await context.WebSockets.AcceptWebSocketAsync ("ooui");
var session = new Ooui.UI.Session (webSocket, pendingSession.Element, w, h, token);
var session = new Ooui.UI.Session (webSocket, activeSession.Element, w, h, token);
await session.RunAsync ().ConfigureAwait (false);
}
class PendingSession
class ActiveSession
{
public Element Element;
public DateTime RequestTimeUtc;
public DateTime LastConnectTimeUtc;
}
}
}

View File

@ -6,13 +6,21 @@ namespace Ooui.Forms
public class LinkLabel : Xamarin.Forms.Label
{
public static readonly BindableProperty HRefProperty = BindableProperty.Create ("HRef", typeof (string),
typeof (LinkView), string.Empty, BindingMode.OneWay, null, null, null, null);
typeof (LinkLabel), string.Empty, BindingMode.OneWay, null, null, null, null);
public string HRef {
get { return (string)base.GetValue (HRefProperty); }
set { base.SetValue (HRefProperty, value); }
}
public static readonly BindableProperty TargetProperty = BindableProperty.Create ("Target", typeof (string),
typeof (LinkLabel), string.Empty, BindingMode.OneWay, null, null, null, null);
public string Target {
get { return (string)base.GetValue (TargetProperty); }
set { base.SetValue (TargetProperty, value); }
}
public LinkLabel ()
{
}

View File

@ -13,6 +13,14 @@ namespace Ooui.Forms
set { base.SetValue (HRefProperty, value); }
}
public static readonly BindableProperty TargetProperty = BindableProperty.Create ("Target", typeof (string),
typeof (LinkView), string.Empty, BindingMode.OneWay, null, null, null, null);
public string Target {
get { return (string)base.GetValue (TargetProperty); }
set { base.SetValue (TargetProperty, value); }
}
public LinkView ()
{
}

View File

@ -14,7 +14,7 @@ namespace Ooui.Forms.Extensions
var measured = false;
if (self.Style.Width.Equals ("inherit")) {
s = self.Text.MeasureSize (self.Style);
s = self.Text.MeasureSize (self.Style, widthConstraint, heightConstraint);
measured = true;
rw = double.IsPositiveInfinity (s.Width) ? double.PositiveInfinity : Math.Ceiling (s.Width);
}
@ -24,7 +24,7 @@ namespace Ooui.Forms.Extensions
if (self.Style.Height.Equals ("inherit")) {
if (!measured) {
s = self.Text.MeasureSize (self.Style);
s = self.Text.MeasureSize (self.Style, widthConstraint, heightConstraint);
measured = true;
}
rh = double.IsPositiveInfinity (s.Height) ? double.PositiveInfinity : Math.Ceiling (s.Height * 1.4);

View File

@ -38,36 +38,65 @@ namespace Ooui.Forms.Extensions
}
}
public static Size MeasureSize (this string text, string fontFamily, double fontSize, FontAttributes fontAttrs)
public static Size MeasureSize (this string text, string fontFamily, double fontSize, FontAttributes fontAttrs, double widthConstraint, double heightConstraint)
{
if (string.IsNullOrEmpty (text))
return Size.Zero;
var fontHeight = fontSize;
var lineHeight = fontHeight * 1.4;
var isBold = fontAttrs.HasFlag (FontAttributes.Bold);
var props = isBold ? BoldCharacterProportions : CharacterProportions;
var avgp = isBold ? BoldAverageCharProportion : AverageCharProportion;
var pwidth = 1.0e-6; // Tiny little padding to account for sampling errors
for (var i = 0; i < text.Length; i++) {
var c = (int)text[i];
if (c < 128) {
pwidth += props[c];
}
else {
pwidth += avgp;
}
}
var width = fontSize * pwidth;
var px = 0.0;
var lines = 1;
var maxPWidth = 0.0;
var pwidthConstraint = double.IsPositiveInfinity (widthConstraint) ? double.PositiveInfinity : widthConstraint / fontSize;
var lastSpaceWidth = -1.0;
return new Size (width, fontHeight);
// Tiny little padding to account for sampling errors
var pwidthHack = 1.0e-6;
var plineHack = 0.333;
var n = text != null ? text.Length : 0;
for (var i = 0; i < n; i++) {
var c = (int)text[i];
var pw = (c < 128) ? props[c] : avgp;
// Should we wrap?
if (px + pw + plineHack > pwidthConstraint) {
lines++;
if (lastSpaceWidth > 0) {
maxPWidth = Math.Max (maxPWidth, lastSpaceWidth + pwidthHack);
px = pw - lastSpaceWidth;
lastSpaceWidth = -1;
}
else {
maxPWidth = Math.Max (maxPWidth, px + pwidthHack);
px = 0;
}
}
if (c == ' ') {
lastSpaceWidth = pw;
}
px += pw;
}
maxPWidth = Math.Max (maxPWidth, px + pwidthHack);
var width = fontSize * maxPWidth;
var height = lines * lineHeight;
// Console.WriteLine ($"MEASURE TEXT SIZE {widthConstraint}x{heightConstraint} \"{text}\" == {width}x{height}");
return new Size (width, height);
}
public static Size MeasureSize (this string text, Style style)
public static Size MeasureSize (this string text, Style style, double widthConstraint, double heightConstraint)
{
return MeasureSize (text, "", 14, FontAttributes.None);
// System.Console.WriteLine("!!! MEASURE STYLED TEXT SIZE: " + style);
return MeasureSize (text, "", 14, FontAttributes.None, widthConstraint, heightConstraint);
}
public static string ToOouiTextAlign (this TextAlignment align)

View File

@ -139,6 +139,10 @@ namespace Xamarin.Forms
}), null, (int)interval.TotalMilliseconds, (int)interval.TotalMilliseconds);
}
}
public void QuitApplication()
{
}
}
public class ViewInitializedEventArgs

View File

@ -20,7 +20,7 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Xamarin.Forms" Version="2.4.0.38779" />
<PackageReference Include="Xamarin.Forms" Version="2.5.0.122203" />
</ItemGroup>
<ItemGroup>
<Folder Include="Extensions\" />

View File

@ -14,8 +14,8 @@ namespace Ooui.Forms.Renderers
public override SizeRequest GetDesiredSize (double widthConstraint, double heightConstraint)
{
var size = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes);
size = new Size (size.Width, size.Height * 1.428 + 14);
var size = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes, widthConstraint, heightConstraint);
size = new Size (size.Width + 2 * Element.FontSize, size.Height + Element.FontSize);
return new SizeRequest (size, size);
}

View File

@ -13,8 +13,8 @@ namespace Ooui.Forms.Renderers
public override SizeRequest GetDesiredSize (double widthConstraint, double heightConstraint)
{
var size = "00/00/0000".MeasureSize ("", 16.0, FontAttributes.None);
size = new Size (size.Width, size.Height * 1.428 + 14);
var size = "00/00/0000".MeasureSize ("", 16.0, FontAttributes.None, widthConstraint, heightConstraint);
size = new Size (size.Width, size.Height);
return new SizeRequest (size, size);
}

View File

@ -21,14 +21,12 @@ namespace Ooui.Forms.Renderers
if (text == null || text.Length == 0) {
text = Element.Placeholder;
}
Size size;
if (text == null || text.Length == 0) {
size = new Size (Element.FontSize * 0.25, Element.FontSize);
text = " ";
}
else {
size = text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes);
}
size = new Size (size.Width, size.Height * 1.428 + 14);
var size = text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes, widthConstraint, heightConstraint);
var vpadding = Element.FontSize;
size = new Size (size.Width, size.Height + vpadding);
return new SizeRequest (size, size);
}
@ -149,7 +147,7 @@ namespace Ooui.Forms.Renderers
{
if (initialSize == Size.Zero) {
var testString = "Tj";
initialSize = testString.MeasureSize (Control.Style);
initialSize = testString.MeasureSize (Control.Style, double.PositiveInfinity, double.PositiveInfinity);
}
Element.SetStyleFont (Element.FontFamily, Element.FontSize, Element.FontAttributes, Control.Style);

View File

@ -16,11 +16,12 @@ namespace Ooui.Forms.Renderers
public override SizeRequest GetDesiredSize (double widthConstraint, double heightConstraint)
{
// System.Console.WriteLine($"Label.GetDesiredSize ({widthConstraint}, {heightConstraint})");
if (!_perfectSizeValid) {
var size = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes);
var size = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes, double.PositiveInfinity, double.PositiveInfinity);
size.Width = Math.Ceiling (size.Width);
size.Height = Math.Ceiling (size.Height * 1.4);
_perfectSize = new SizeRequest (size, size);
size.Height = Math.Ceiling (size.Height);
_perfectSize = new SizeRequest (size, new Size (Element.FontSize, Element.FontSize));
_perfectSizeValid = true;
}
@ -30,7 +31,8 @@ namespace Ooui.Forms.Renderers
if (widthFits && heightFits)
return _perfectSize;
var result = base.GetDesiredSize (widthConstraint, heightConstraint);
var resultRequestSize = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes, widthConstraint, heightConstraint);
var result = new SizeRequest (resultRequestSize, resultRequestSize);
var tinyWidth = Math.Min (10, result.Request.Width);
result.Minimum = new Size (tinyWidth, result.Request.Height);

View File

@ -14,10 +14,10 @@ namespace Ooui.Forms.Renderers
public override SizeRequest GetDesiredSize (double widthConstraint, double heightConstraint)
{
if (!_perfectSizeValid) {
var size = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes);
var size = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes, double.PositiveInfinity, double.PositiveInfinity);
size.Width = Math.Ceiling (size.Width);
size.Height = Math.Ceiling (size.Height * 1.4);
_perfectSize = new SizeRequest (size, size);
size.Height = Math.Ceiling (size.Height);
_perfectSize = new SizeRequest (size, new Size (Element.FontSize, Element.FontSize));
_perfectSizeValid = true;
}
@ -27,7 +27,8 @@ namespace Ooui.Forms.Renderers
if (widthFits && heightFits)
return _perfectSize;
var result = base.GetDesiredSize (widthConstraint, heightConstraint);
var resultRequestSize = Element.Text.MeasureSize (Element.FontFamily, Element.FontSize, Element.FontAttributes, widthConstraint, heightConstraint);
var result = new SizeRequest (resultRequestSize, resultRequestSize);
var tinyWidth = Math.Min (10, result.Request.Width);
result.Minimum = new Size (tinyWidth, result.Request.Height);
@ -57,6 +58,7 @@ namespace Ooui.Forms.Renderers
}
UpdateHRef ();
UpdateTarget ();
UpdateText ();
UpdateTextColor ();
@ -78,6 +80,8 @@ namespace Ooui.Forms.Renderers
if (e.PropertyName == Ooui.Forms.LinkLabel.HRefProperty.PropertyName)
UpdateHRef ();
if (e.PropertyName == Ooui.Forms.LinkLabel.TargetProperty.PropertyName)
UpdateTarget ();
else if (e.PropertyName == Xamarin.Forms.Label.HorizontalTextAlignmentProperty.PropertyName)
UpdateAlignment ();
else if (e.PropertyName == Xamarin.Forms.Label.VerticalTextAlignmentProperty.PropertyName)
@ -107,6 +111,11 @@ namespace Ooui.Forms.Renderers
Control.HRef = Element.HRef;
}
void UpdateTarget ()
{
Control.Target = Element.Target;
}
void UpdateAlignment ()
{
this.Style.Display = "table";

View File

@ -15,6 +15,7 @@ namespace Ooui.Forms.Renderers
base.OnElementChanged (e);
UpdateHRef ();
UpdateTarget ();
}
protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
@ -24,13 +25,20 @@ namespace Ooui.Forms.Renderers
if (Control == null)
return;
if (e.PropertyName == Ooui.Forms.LinkLabel.HRefProperty.PropertyName)
if (e.PropertyName == Ooui.Forms.LinkView.HRefProperty.PropertyName)
UpdateHRef ();
if (e.PropertyName == Ooui.Forms.LinkView.TargetProperty.PropertyName)
UpdateTarget ();
}
void UpdateHRef ()
{
this.SetAttribute ("href", Element.HRef);
}
void UpdateTarget ()
{
this.SetAttribute ("target", Element.Target);
}
}
}

View File

@ -27,9 +27,9 @@ namespace Ooui.Forms.Renderers
}
else
{
size = text.MeasureSize(Element.FontFamily, Element.FontSize, Element.FontAttributes);
size = text.MeasureSize(Element.FontFamily, Element.FontSize, Element.FontAttributes, widthConstraint, heightConstraint);
}
size = new Size(size.Width, size.Height * 1.428 + 14);
size = new Size(size.Width, size.Height + Element.FontSize);
return new SizeRequest(size, size);
}

View File

@ -3,7 +3,7 @@ using Xamarin.Forms;
namespace Ooui.Forms.Renderers
{
public class SwitchRenderer : ViewRenderer<Switch, Input>
public class SwitchRenderer : ViewRenderer<Switch, SwitchRenderer.SwitchElement>
{
public override SizeRequest GetDesiredSize (double widthConstraint, double heightConstraint)
{
@ -26,10 +26,8 @@ namespace Ooui.Forms.Renderers
if (e.NewElement != null) {
if (Control == null) {
var input = new Input (InputType.Checkbox);
input.SetAttribute ("data-toggle", "toggle");
var input = new SwitchElement ();
SetNativeControl (input);
input.Call ("$.bootstrapToggle");
Control.Change += OnControlValueChanged;
}
@ -49,5 +47,52 @@ namespace Ooui.Forms.Renderers
{
Control.IsChecked = Element.IsToggled;
}
public class SwitchElement : Div
{
public event EventHandler Change;
bool isChecked = false;
readonly Div knob = new Div ();
public bool IsChecked {
get => isChecked;
set {
isChecked = value;
UpdateUI ();
}
}
public SwitchElement ()
{
AppendChild (knob);
knob.Style.Position = "absolute";
knob.Style.BorderRadius = "10px";
knob.Style.Cursor = "pointer";
knob.Style.Top = "2px";
knob.Style.Width = "18px";
knob.Style.Height = "34px";
Style.BorderRadius = "10px";
Style.Cursor = "pointer";
Style.BorderStyle = "solid";
Style.BorderWidth = "2px";
Click += (s, e) => {
IsChecked = !IsChecked;
Change?.Invoke (this, EventArgs.Empty);
};
UpdateUI ();
}
void UpdateUI ()
{
Style.BackgroundColor = isChecked ? "#337ab7" : "#888";
Style.BorderColor = Style.BackgroundColor;
knob.Style.BackgroundColor = isChecked ? "#FFF" : "#EEE";
if (isChecked) {
knob.Style.Left = "34px";
}
else {
knob.Style.Left = "2px";
}
}
}
}
}

View File

@ -13,8 +13,9 @@ namespace Ooui.Forms.Renderers
public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
var size = "00:00:00".MeasureSize(string.Empty, 16.0, FontAttributes.None);
size = new Size(size.Width, size.Height * 1.428 + 14);
var fontSize = 16.0;
var size = "00:00:00".MeasureSize(string.Empty, fontSize, FontAttributes.None, widthConstraint, heightConstraint);
size = new Size(size.Width, size.Height + fontSize);
return new SizeRequest(size, size);
}

View File

@ -21,6 +21,8 @@ namespace Ooui.Forms.Renderers
/// </summary>
protected virtual bool ManageNativeControlLifetime => true;
protected override bool HtmlNeedsFullEndElement => TagName == "div";
public ViewRenderer (string tagName = "div")
: base (tagName)
{

View File

@ -24,7 +24,7 @@ namespace Ooui.Forms.Renderers
if (_iframe != null)
{
_iframe.Src = html;
_iframe.Source = html;
}
}
catch (Exception ex)
@ -47,7 +47,7 @@ namespace Ooui.Forms.Renderers
if (_iframe != null)
{
_iframe.Src = url;
_iframe.Source = url;
}
}
catch (Exception ex)

View File

@ -62,6 +62,8 @@ namespace Ooui.Forms
}
}
protected override bool HtmlNeedsFullEndElement => TagName == "div";
public VisualElementRenderer (string tagName = "div") : base (tagName)
{
_propertyChangedHandler = OnElementPropertyChanged;

View File

@ -4,15 +4,32 @@ namespace Ooui
{
public class Anchor : Element
{
string href = "";
public string HRef {
get => href;
set => SetProperty (ref href, value ?? "", "href");
get => GetStringAttribute ("href", "");
set => SetAttributeProperty ("href", value);
}
public string Target {
get => GetStringAttribute ("target", "");
set => SetAttributeProperty ("target", value);
}
public Anchor ()
: base ("a")
{
}
public Anchor (string href)
: this ()
{
HRef = href;
}
public Anchor (string href, string text)
: this ()
{
HRef = href;
Text = text;
}
}
}

View File

@ -9,8 +9,8 @@ namespace Ooui
{
ButtonType typ = ButtonType.Submit;
public ButtonType Type {
get => typ;
set => SetProperty (ref typ, value, "type");
get => GetAttribute ("type", ButtonType.Submit);
set => SetAttributeProperty ("type", value);
}
public Button ()

View File

@ -7,16 +7,14 @@ namespace Ooui
CanvasRenderingContext2D context2d = new CanvasRenderingContext2D ();
int gotContext2d = 0;
int width = 300;
public int Width {
get => width;
set => SetProperty (ref width, value <= 0 ? 150 : value, "width");
get => GetAttribute ("width", 300);
set => SetAttributeProperty ("width", value < 0 ? 0 : value);
}
int height = 150;
public int Height {
get => height;
set => SetProperty (ref height, value <= 0 ? 150 : value, "height");
get => GetAttribute ("height", 150);
set => SetAttributeProperty ("height", value < 0 ? 0 : value);
}
public Canvas ()

View File

@ -1,7 +1,9 @@
// Ooui v1.0.0
var debug = false;
const nodes = {};
const hasText = {};
let socket = null;
@ -35,19 +37,39 @@ function getSize () {
};
}
function setCookie (name, value, days) {
var expires = "";
if (days) {
var date = new Date ();
date.setTime(date.getTime () + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function saveSize (s) {
setCookie ("oouiWindowWidth", s.width, 7);
setCookie ("oouiWindowHeight", s.height, 7);
}
// Main entrypoint
function ooui (rootElementPath) {
var opened = false;
var initialSize = getSize ();
saveSize (initialSize);
var wsArgs = (rootElementPath.indexOf("?") >= 0 ? "&" : "?") +
"w=" + initialSize.width + "&h=" + initialSize.height;
socket = new WebSocket ("ws://" + document.location.host + rootElementPath + wsArgs, "ooui");
var proto = "ws";
if (location.protocol == "https:") {
proto = "wss";
}
socket = new WebSocket (proto + "://" + document.location.host + rootElementPath + wsArgs, "ooui");
socket.addEventListener ("open", function (event) {
console.log ("Web socket opened");
opened = true;
});
socket.addEventListener ("error", function (event) {
@ -56,29 +78,17 @@ function ooui (rootElementPath) {
socket.addEventListener ("close", function (event) {
console.error ("Web socket close", event);
if (opened) {
alert ("Connection to the server has been lost. Please try refreshing the page.");
opened = false;
}
});
socket.addEventListener("message", function (event) {
const messages = JSON.parse (event.data);
if (debug) console.log("Messages", messages);
if (Array.isArray (messages)) {
const jqs = []
messages.forEach (function (m) {
// console.log('Raw value from server', m.v);
m.v = fixupValue (m.v);
if (m.k.startsWith ("$.")) {
jqs.push (m);
}
else {
processMessage (m);
}
processMessage (m);
});
// Run jQuery functions last since they usually require a fully built DOM
jqs.forEach (processMessage);
}
});
@ -105,6 +115,7 @@ function ooui (rootElementPath) {
k: "resize",
v: getSize (),
};
saveSize (em.v);
const ems = JSON.stringify (em);
if (socket != null)
socket.send (ems);
@ -124,12 +135,22 @@ function getNode (id) {
}
}
function getOrCreateElement (id, tagName) {
var e = document.getElementById (id);
if (e) {
if (e.firstChild && e.firstChild.nodeType == Node.TEXT_NODE)
hasText[e.id] = true;
return e;
}
return document.createElement (tagName);
}
function msgCreate (m) {
const id = m.id;
const tagName = m.k;
const node = tagName === "#text" ?
document.createTextNode ("") :
document.createElement (tagName);
getOrCreateElement (id, tagName);
if (tagName !== "#text")
node.id = id;
nodes[id] = node;
@ -165,6 +186,17 @@ function msgSetAttr (m) {
if (debug) console.log ("SetAttr", node, m.k, m.v);
}
function msgRemAttr (m) {
const id = m.id;
const node = getNode (id);
if (!node) {
console.error ("Unknown node id", m);
return;
}
node.removeAttribute(m.k);
if (debug) console.log ("RemAttr", node, m.k);
}
function msgCall (m) {
const id = m.id;
const node = getNode (id);
@ -172,9 +204,14 @@ function msgCall (m) {
console.error ("Unknown node id", m);
return;
}
const isJQuery = m.k.startsWith ("$.");
const target = isJQuery ? $(node) : node;
const f = isJQuery ? target[m.k.slice(2)] : target[m.k];
const target = node;
if (m.k === "insertBefore" && m.v[0].nodeType == Node.TEXT_NODE && m.v[1] == null && hasText[id]) {
// Text is already set so it clear it first
if (target.firstChild)
target.removeChild (target.firstChild);
delete hasText[id];
}
const f = target[m.k];
if (debug) console.log ("Call", node, f, m.v);
const r = f.apply (target, m.v);
if (typeof m.rid === 'string' || m.rid instanceof String) {
@ -228,6 +265,9 @@ function processMessage (m) {
case "setAttr":
msgSetAttr (m);
break;
case "remAttr":
msgRemAttr (m);
break;
case "call":
msgCall (m);
break;

View File

@ -65,15 +65,47 @@ namespace Ooui
if (styleValue == "inherit")
return Colors.Clear;
//if (styleValue[0] == '#' && styleValue.Length == 4) {
//}
if (styleValue[0] == '#' && styleValue.Length == 4) {
var r = ReadHexNibble (styleValue[1]);
var g = ReadHexNibble (styleValue[2]);
var b = ReadHexNibble (styleValue[3]);
return new Color (r, g, b, 255);
}
//if (styleValue[0] == '#' && styleValue.Length == 7) {
//}
if (styleValue[0] == '#' && styleValue.Length == 7) {
var r = ReadHexByte (styleValue[1], styleValue[2]);
var g = ReadHexByte (styleValue[3], styleValue[4]);
var b = ReadHexByte (styleValue[5], styleValue[6]);
return new Color (r, g, b, 255);
}
throw new ArgumentException ($"Cannot parse color string `{styleValue}`", nameof (styleValue));
}
static byte ReadHexByte (char c0, char c1)
{
var n0 = ReadHex (c0);
var n1 = ReadHex (c1);
return (byte)((n0 << 4) | n1);
}
static byte ReadHexNibble (char c)
{
var n = ReadHex (c);
return (byte)((n << 4) | n);
}
static byte ReadHex (char c)
{
if ('0' <= c && c <= '9')
return (byte)(c - '0');
if ('a' <= c && c <= 'z')
return (byte)((c - 'a') + 10);
if ('A' <= c && c <= 'Z')
return (byte)((c - 'A') + 10);
return 0;
}
public override string ToString ()
{
if (A == 255)

View File

@ -5,6 +5,8 @@ namespace Ooui
{
public class Div : Element
{
protected override bool HtmlNeedsFullEndElement => true;
public Div ()
: base ("div")
{

View File

@ -1,28 +1,29 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Ooui
{
public abstract class Element : Node
{
string className = "";
readonly Dictionary<string, object> attributes = new Dictionary<string, object> ();
public string ClassName {
get => className;
set => SetProperty (ref className, value, "className");
get => GetStringAttribute ("class", "");
set => SetAttributeProperty ("class", value);
}
public Style Style { get; private set; } = new Style ();
string title = "";
public string Title {
get => title;
set => SetProperty (ref title, value, "title");
get => GetStringAttribute ("title", "");
set => SetAttributeProperty ("title", value);
}
bool hidden = false;
public bool IsHidden {
get => hidden;
set => SetProperty (ref hidden, value, "hidden");
get => GetBooleanAttribute ("hidden");
set => SetBooleanAttributeProperty ("hidden", value);
}
public event TargetEventHandler Click {
@ -102,8 +103,64 @@ namespace Ooui
Style.PropertyChanged += HandleStylePropertyChanged;
}
public void SetAttribute (string attributeName, string value)
protected bool SetAttributeProperty (string attributeName, object newValue, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
var old = GetAttribute (attributeName);
if (old != null && old.Equals (newValue))
return false;
SetAttribute (attributeName, newValue);
OnPropertyChanged (propertyName);
return true;
}
protected bool SetBooleanAttributeProperty (string attributeName, bool newValue, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
var old = GetAttribute (attributeName) != null;
if (old == newValue)
return false;
if (newValue)
SetAttribute (attributeName, string.Empty);
else
RemoveAttribute (attributeName);
OnPropertyChanged (propertyName);
return true;
}
protected bool UpdateAttributeProperty (string attributeName, object newValue, string propertyName)
{
lock (attributes) {
if (attributes.TryGetValue (attributeName, out var oldValue)) {
if (newValue != null && newValue.Equals (oldValue))
return false;
}
attributes[attributeName] = newValue;
}
OnPropertyChanged (propertyName);
return true;
}
protected bool UpdateBooleanAttributeProperty (string attributeName, bool newValue, string propertyName)
{
lock (attributes) {
var oldValue = attributes.ContainsKey (attributeName);
if (newValue == oldValue)
return false;
if (newValue) {
attributes[attributeName] = "";
}
else {
attributes.Remove (attributeName);
}
}
OnPropertyChanged (propertyName);
return true;
}
public void SetAttribute (string attributeName, object value)
{
lock (attributes) {
attributes[attributeName] = value;
}
Send (new Message {
MessageType = MessageType.SetAttribute,
TargetId = Id,
@ -112,22 +169,97 @@ namespace Ooui
});
}
public object GetAttribute (string attributeName)
{
lock (attributes) {
attributes.TryGetValue (attributeName, out var v);
return v;
}
}
public T GetAttribute<T> (string attributeName, T defaultValue)
{
lock (attributes) {
attributes.TryGetValue (attributeName, out var v);
if (v is T) {
return (T)v;
}
else {
return defaultValue;
}
}
}
public bool GetBooleanAttribute (string attributeName)
{
lock (attributes) {
return attributes.TryGetValue (attributeName, out var _);
}
}
public string GetStringAttribute (string attributeName, string defaultValue)
{
lock (attributes) {
if (attributes.TryGetValue (attributeName, out var v)) {
if (v == null) return "null";
else return v.ToString ();
}
else {
return defaultValue;
}
}
}
public void RemoveAttribute (string attributeName)
{
bool removed;
lock (attributes) {
removed = attributes.Remove (attributeName);
}
if (removed) {
Send (new Message {
MessageType = MessageType.RemoveAttribute,
TargetId = Id,
Key = attributeName,
});
}
}
void HandleStylePropertyChanged (object sender, PropertyChangedEventArgs e)
{
SendSet ("style." + Style.GetJsName (e.PropertyName), Style[e.PropertyName]);
}
protected override bool SaveStateMessageIfNeeded (Message message)
{
if (message.TargetId != Id)
return false;
protected virtual bool HtmlNeedsFullEndElement => false;
switch (message.MessageType) {
case MessageType.Call when message.Key.StartsWith ("$.", StringComparison.Ordinal):
AddStateMessage (message);
return true;
default:
return base.SaveStateMessageIfNeeded (message);
public override void WriteOuterHtml (System.Xml.XmlWriter w)
{
w.WriteStartElement (TagName);
w.WriteAttributeString ("id", Id);
var style = Style.ToString ();
if (style.Length > 0) {
w.WriteAttributeString ("style", style);
}
lock (attributes) {
foreach (var a in attributes) {
var value = (a.Value == null) ? "null" : Convert.ToString (a.Value, System.Globalization.CultureInfo.InvariantCulture);
w.WriteAttributeString (a.Key, value);
}
}
WriteInnerHtml (w);
if (HtmlNeedsFullEndElement) {
w.WriteFullEndElement ();
}
else {
w.WriteEndElement ();
}
}
public virtual void WriteInnerHtml (System.Xml.XmlWriter w)
{
var children = Children;
foreach (var c in children) {
c.WriteOuterHtml (w);
}
}
}

View File

@ -83,12 +83,12 @@ namespace Ooui
}
}
protected bool SetProperty<T> (ref T backingStore, T newValue, string attributeName, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
protected bool SetProperty<T> (ref T backingStore, T newValue, string jsPropertyName, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
if (EqualityComparer<T>.Default.Equals (backingStore, newValue))
return false;
backingStore = newValue;
SendSet (attributeName, newValue);
SendSet (jsPropertyName, newValue);
OnPropertyChanged (propertyName);
return true;
}
@ -120,12 +120,12 @@ namespace Ooui
Send (Message.Call (Id, methodName, args));
}
protected void SendSet (string attributeName, object value)
protected void SendSet (string jsPropertyName, object value)
{
Send (new Message {
MessageType = MessageType.Set,
TargetId = Id,
Key = attributeName,
Key = jsPropertyName,
Value = value,
});
}
@ -169,6 +169,11 @@ namespace Ooui
state.Add (message);
});
break;
case MessageType.RemoveAttribute:
this.UpdateStateMessages (state => {
state.RemoveAll (x => x.MessageType == MessageType.SetAttribute && x.Key == message.Key);
});
return true;
case MessageType.Listen:
AddStateMessage (message);
break;
@ -177,6 +182,24 @@ namespace Ooui
return true;
}
protected virtual bool TriggerEvent (string name)
{
List<TargetEventHandler> handlers = null;
lock (eventListeners) {
List<TargetEventHandler> hs;
if (eventListeners.TryGetValue (name, out hs)) {
handlers = new List<TargetEventHandler> (hs);
}
}
if (handlers != null) {
var args = new TargetEventArgs ();
foreach (var h in handlers) {
h.Invoke (this, args);
}
}
return true;
}
protected virtual bool TriggerEventFromMessage (Message message)
{
if (message.TargetId != Id)

View File

@ -6,20 +6,18 @@ namespace Ooui
{
string action = "";
public string Action {
get => action;
set => SetProperty (ref action, value ?? "", "action");
get => GetStringAttribute ("action", "");
set => SetAttributeProperty ("action", value ?? "");
}
string method = "GET";
public string Method {
get => method;
set => SetProperty (ref method, value ?? "", "method");
get => GetStringAttribute ("method", "GET");
set => SetAttributeProperty ("method", value ?? "");
}
string enctype = "application/x-www-form-urlencoded";
public string EncodingType {
get => enctype;
set => SetProperty (ref enctype, value ?? "", "enctype");
get => GetStringAttribute ("enctype", "application/x-www-form-urlencoded");
set => SetAttributeProperty ("enctype", value ?? "");
}
public event TargetEventHandler Submit {

View File

@ -4,16 +4,15 @@ namespace Ooui
{
public abstract class FormControl : Element
{
string name = "";
public string Name {
get => name;
set => SetProperty (ref name, value, "name");
get => GetStringAttribute ("name", "");
set => SetAttributeProperty ("name", value);
}
bool isDisabled = false;
public bool IsDisabled {
get => isDisabled;
set => SetProperty (ref isDisabled, value, "disabled");
get => GetBooleanAttribute ("disabled");
set => SetBooleanAttributeProperty ("disabled", value);
}
public FormControl (string tagName)

View File

@ -2,17 +2,15 @@
{
public class Iframe : Element
{
public Iframe()
: base("iframe")
public string Source
{
get => GetStringAttribute ("src", null);
set => SetAttributeProperty ("src", value);
}
string src = null;
public string Src
public Iframe ()
: base ("iframe")
{
get => src;
set => SetProperty(ref src, value, "src");
}
}
}

View File

@ -4,10 +4,10 @@ namespace Ooui
{
public class Image : Element
{
string src = "";
public string Source {
get => src;
set => SetProperty (ref src, value ?? "", "src");
public string Source
{
get => GetStringAttribute ("src", null);
set => SetAttributeProperty ("src", value);
}
public Image ()

View File

@ -7,16 +7,14 @@ namespace Ooui
{
public class Input : FormControl
{
InputType typ = InputType.Text;
public InputType Type {
get => typ;
set => SetProperty (ref typ, value, "type");
get => GetAttribute ("type", InputType.Text);
set => SetAttributeProperty ("type", value);
}
string val = "";
public string Value {
get => val;
set => SetProperty (ref val, value ?? "", "value");
get => GetStringAttribute ("value", "");
set => SetAttributeProperty ("value", value ?? "");
}
public double NumberValue {
@ -35,37 +33,33 @@ namespace Ooui
remove => RemoveEventListener ("change", value);
}
string placeholder = "";
public string Placeholder {
get => placeholder;
set => SetProperty (ref placeholder, value, "placeholder");
get => GetStringAttribute ("placeholder", "");
set => SetAttributeProperty ("placeholder", value ?? "");
}
bool isChecked = false;
public bool IsChecked {
get => isChecked;
get => GetBooleanAttribute ("checked");
set {
SetProperty (ref isChecked, value, "checked");
TriggerEventFromMessage (Message.Event (Id, "change", isChecked));
if (SetBooleanAttributeProperty ("checked", value)) {
TriggerEvent ("change");
}
}
}
double minimum = 0;
public double Minimum {
get => minimum;
set => SetProperty (ref minimum, value, "min");
get => GetAttribute ("min", 0.0);
set => SetAttributeProperty ("min", value);
}
double maximum = 100;
public double Maximum {
get => maximum;
set => SetProperty (ref maximum, value, "max");
get => GetAttribute ("max", 100.0);
set => SetAttributeProperty ("max", value);
}
double step = 1;
public double Step {
get => step;
set => SetProperty (ref step, value, "step");
get => GetAttribute ("step", 1.0);
set => SetAttributeProperty ("step", value);
}
public Input ()
@ -86,10 +80,10 @@ namespace Ooui
if (message.TargetId == Id && message.MessageType == MessageType.Event && (message.Key == "change" || message.Key == "input")) {
// Don't need to notify here because the base implementation will fire the event
if (Type == InputType.Checkbox) {
isChecked = message.Value != null ? Convert.ToBoolean (message.Value) : false;
UpdateBooleanAttributeProperty ("checked", message.Value != null ? Convert.ToBoolean (message.Value) : false, "IsChecked");
}
else {
val = message.Value != null ? Convert.ToString (message.Value) : "";
UpdateAttributeProperty ("value", message.Value != null ? Convert.ToString (message.Value) : "", "Value");
}
}
return base.TriggerEventFromMessage (message);

View File

@ -4,10 +4,9 @@ namespace Ooui
{
public class Label : Element
{
Element htmlFor = null;
public Element For {
get => htmlFor;
set => SetProperty (ref htmlFor, value, "htmlFor");
get => GetAttribute<Element> ("for", null);
set => SetAttributeProperty ("for", value);
}
public Label ()

View File

@ -48,6 +48,8 @@ namespace Ooui
Set,
[EnumMember (Value = "setAttr")]
SetAttribute,
[EnumMember(Value = "remAttr")]
RemoveAttribute,
[EnumMember(Value = "call")]
Call,
[EnumMember(Value = "listen")]

View File

@ -180,5 +180,24 @@ namespace Ooui
}
return false;
}
public virtual string OuterHtml {
get {
using (var stream = new System.IO.MemoryStream ()) {
var settings = new System.Xml.XmlWriterSettings {
OmitXmlDeclaration = true,
ConformanceLevel = System.Xml.ConformanceLevel.Fragment,
CloseOutput = false,
};
using (var w = System.Xml.XmlWriter.Create (stream, settings)) {
WriteOuterHtml (w);
}
stream.Position = 0;
return new System.IO.StreamReader (stream).ReadToEnd ();
}
}
}
public abstract void WriteOuterHtml (System.Xml.XmlWriter w);
}
}

View File

@ -4,22 +4,19 @@ namespace Ooui
{
public class Option : Element
{
string val = "";
public string Value {
get => val;
set => SetProperty (ref val, value ?? "", "value");
get => GetStringAttribute ("value", "");
set => SetAttributeProperty ("value", value ?? "");
}
string label = "";
public string Label {
get => label;
set => SetProperty (ref label, value ?? "", "label");
get => GetStringAttribute ("label", "");
set => SetAttributeProperty ("label", value ?? "");
}
bool defaultSelected = false;
public bool DefaultSelected {
get => defaultSelected;
set => SetProperty (ref defaultSelected, value, "defaultSelected");
get => GetBooleanAttribute ("selected");
set => SetBooleanAttributeProperty ("selected", value);
}
public Option ()

View File

@ -4,10 +4,9 @@ namespace Ooui
{
public class Select : FormControl
{
string val = "";
public string Value {
get => val;
set => SetProperty (ref val, value ?? "", "value");
get => GetStringAttribute ("value", "");
set => SetAttributeProperty ("value", value ?? "");
}
public event TargetEventHandler Change {
@ -35,6 +34,7 @@ namespace Ooui
protected override void OnChildInsertedBefore (Node newChild, Node referenceChild)
{
base.OnChildInsertedBefore (newChild, referenceChild);
var val = Value;
if (string.IsNullOrEmpty (val) && newChild is Option o && !string.IsNullOrEmpty (o.Value)) {
val = o.Value;
}
@ -43,7 +43,8 @@ namespace Ooui
protected override bool TriggerEventFromMessage (Message message)
{
if (message.TargetId == Id && message.MessageType == MessageType.Event && (message.Key == "change" || message.Key == "input")) {
val = message.Value != null ? Convert.ToString (message.Value) : "";
SetAttribute ("value", message.Value != null ? Convert.ToString (message.Value) : "");
OnPropertyChanged ("Value");
}
return base.TriggerEventFromMessage (message);
}

View File

@ -399,7 +399,7 @@ namespace Ooui
o.Append (head);
o.Append (p.Key);
o.Append (":");
o.Append (String.Format (System.Globalization.CultureInfo.InvariantCulture, "{0}", p.Value));
o.Append (Convert.ToString (p.Value, System.Globalization.CultureInfo.InvariantCulture));
head = ";";
}
}

View File

@ -20,18 +20,19 @@ namespace Ooui
set => SetProperty (ref val, value ?? "", "value");
}
int rows = 2;
public int Rows {
get => rows;
set => SetProperty (ref rows, value, "rows");
get => GetAttribute ("rows", 2);
set => SetAttributeProperty ("rows", value);
}
int cols = 20;
public int Columns {
get => cols;
set => SetProperty (ref cols, value, "cols");
get => GetAttribute ("cols", 20);
set => SetAttributeProperty ("cols", value);
}
protected override bool HtmlNeedsFullEndElement => true;
public TextArea ()
: base ("textarea")
{
@ -53,5 +54,10 @@ namespace Ooui
}
return base.TriggerEventFromMessage (message);
}
public override void WriteInnerHtml (System.Xml.XmlWriter w)
{
w.WriteString (val ?? "");
}
}
}

View File

@ -20,5 +20,10 @@ namespace Ooui
{
Text = text;
}
public override void WriteOuterHtml (System.Xml.XmlWriter w)
{
w.WriteString (text);
}
}
}

View File

@ -40,14 +40,14 @@ namespace Ooui
<title>@Title</title>
<meta name=""viewport"" content=""width=device-width, initial-scale=1"" />
<link rel=""stylesheet"" href=""https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"" />
<link rel=""stylesheet"" href=""https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css"" />
<style>@Styles</style>
</head>
<body>
<div id=""ooui-body"" class=""container-fluid""></div>
<script type=""text/javascript"" src=""https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js""></script>
<script type=""text/javascript"" src=""https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js""></script>
<div id=""ooui-body"" class=""container-fluid"">
@InitialHtml
</div>
<script src=""/ooui.js""></script>
<script>ooui(""@WebSocketPath"");</script>
</body>
@ -390,9 +390,9 @@ namespace Ooui
}
}
public static string RenderTemplate (string webSocketPath, string title = "")
public static string RenderTemplate (string webSocketPath, string title = "", string initialHtml = "")
{
return Template.Replace ("@WebSocketPath", webSocketPath).Replace ("@Styles", rules.ToString ()).Replace ("@Title", title);
return Template.Replace ("@WebSocketPath", webSocketPath).Replace ("@Styles", rules.ToString ()).Replace ("@Title", title).Replace ("@InitialHtml", initialHtml);
}
class DataHandler : RequestHandler

View File

@ -9,7 +9,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Xamarin.Forms" Version="2.4.0.38779" />
<PackageReference Include="Xamarin.Forms" Version="2.5.0.122203" />
</ItemGroup>
<ItemGroup>

View File

@ -1,5 +1,7 @@
@{
ViewData["Title"] = "Ooui";
var formsSamples = SamplesController.Samples.Where(x => x.Title.StartsWith("Xamarin.Forms "));
var otherSamples = SamplesController.Samples.Where(x => !x.Title.StartsWith("Xamarin.Forms "));
}
<div class="row" style="margin-top:4em;">
@ -9,14 +11,26 @@
<div class="col-md-2">
<h1>Ooui</h1>
<p>Write interactive web apps in C# and F#</p>
<p><a href="https://github.com/praeclarum/Ooui">Source Code on GitHub</a></p>
</div>
</div>
<div class="row" style="margin-top:4em;">
<div class="col-md-4">
<h3>Samples</h3>
<h3>Xamarin.Forms Samples</h3>
<ul>
@foreach (var s in SamplesController.Samples) {
@foreach (var s in formsSamples) {
<li>
<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title">@s.Title.Substring(14)</a>
(<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title" asp-route-shared="@true">Shared</a>)
</li>
}
</ul>
</div>
<div class="col-md-4">
<h3>Plain Web Samples</h3>
<ul>
@foreach (var s in otherSamples) {
<li>
<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title">@s.Title</a>
(<a asp-area="" asp-controller="Samples" asp-action="Run" asp-route-name="@s.Title" asp-route-shared="@true">Shared</a>)
@ -24,10 +38,4 @@
}
</ul>
</div>
<div class="col-md-3">
<h3>Get it</h3>
<ul>
<li><a href="https://github.com/praeclarum/Ooui">Source Code on Github</a></li>
</ul>
</div>
</div>

View File

@ -40,7 +40,10 @@
@RenderBody()
<hr />
<footer>
<p>&copy; 2017 - Frank A. Krueger</p>
<p>&copy; 2017 - @DateTime.UtcNow.Year Frank A. Krueger</p>
@{ var e = new Ooui.Anchor ("https://github.com/praeclarum/Ooui", "π"); }
<ooui element="e" />
<!--Html.Ooui (e)-->
</footer>
</div>

View File

@ -2,3 +2,4 @@
@using AspNetCoreMvc.Models
@using AspNetCoreMvc.Controllers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Ooui.AspNetCore

View File

@ -27,7 +27,7 @@ msbuild
dotnet run --project Samples/Samples.csproj --no-build
```
There is currently an issue with Xamarin.Forms and building from the dotnet cli, so for now we use the msbuild command and then set the --no-build flag on dotnet run but this will eventually change when the issue is resolved.
*(There is currently an issue with Xamarin.Forms and building from the dotnet cli, so for now we use the msbuild command and then set the --no-build flag on dotnet run but this will eventually change when the issue is resolved.)*
This will open the default starting page for the Samples. Now point your browser at [http://localhost:8080/shared-button](http://localhost:8080/shared-button)
@ -111,8 +111,8 @@ When the user clicks or otherwise interacts with the UI, those events are sent b
<tr>
<th>How big is it?</th>
<td>50 KB</td>
<td>650 KB</td>
<td>80 KB</td>
<td>850 KB</td>
<td>1,300 KB</td>
</tr>
@ -160,18 +160,11 @@ When the user clicks or otherwise interacts with the UI, those events are sent b
<tr>
<th>How do I style things?</th>
<td>CSS baby! (soon)</td>
<td>CSS baby!</td>
<td>XAML resources</td>
<td>CSS</td>
</tr>
<tr>
<th>Is there databinding?</th>
<td>No :-(</td>
<td>Yes!</td>
<td>Debatable</td>
</tr>
<tr>
<th>Do I need to run a server?</th>
<td>Nope</td>

View File

@ -10,7 +10,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Xamarin.Forms" Version="2.4.0.38779" />
<PackageReference Include="Xamarin.Forms" Version="2.5.0.122203" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,40 @@
using Ooui;
using Xamarin.Forms;
namespace Samples
{
// From https://github.com/praeclarum/Ooui/issues/48
public class SwitchErrorSample : ISample
{
public string Title => "Xamarin.Forms Switch Error";
public Ooui.Element CreateElement ()
{
var layout = new StackLayout();
var label = new Xamarin.Forms.Label
{
Text = "Switch state goes here",
HorizontalTextAlignment = TextAlignment.Center
};
var sw = new Switch
{
HorizontalOptions = LayoutOptions.CenterAndExpand
};
sw.Toggled += (sender, args) =>
{
label.Text = $"Switch state is: {((Switch)sender).IsToggled}";
};
layout.Children.Add(label);
layout.Children.Add(sw);
return new ContentPage
{
Content = layout
}.GetOouiElement();
}
public void Publish()
{
UI.Publish ("/switch", CreateElement);
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using Xamarin.Forms;
namespace Samples
{
public class WrappingTextSample : ISample
{
public string Title => "Xamarin.Forms Wrapping Text";
public Ooui.Element CreateElement()
{
var rows = new StackLayout { Orientation = StackOrientation.Vertical };
var row0 = new StackLayout { Orientation = StackOrientation.Horizontal, BackgroundColor = Color.Azure };
row0.Children.Add (new Label { Text = shortText, LineBreakMode = LineBreakMode.WordWrap });
row0.Children.Add (new Label { Text = mediumText, LineBreakMode = LineBreakMode.WordWrap });
row0.Children.Add (new Label { Text = longText, LineBreakMode = LineBreakMode.WordWrap });
rows.Children.Add (row0);
var row1 = new StackLayout { Orientation = StackOrientation.Horizontal, BackgroundColor = Color.GhostWhite };
row1.Children.Add (new Label { Text = shortText, FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.Start });
row1.Children.Add (new Label { Text = mediumText, FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.FillAndExpand });
row1.Children.Add (new Label { Text = longText, FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.End });
rows.Children.Add (row1);
var page = new ContentPage
{
Content = rows
};
return page.GetOouiElement();
}
public void Publish()
{
Ooui.UI.Publish("/wrapping", CreateElement);
}
const string shortText = "Lorem ipsum dolor sit amet.";
const string mediumText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
const string longText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
}
}

View File

@ -58,8 +58,8 @@ namespace Tests
Assert.AreEqual (480, c.Height);
c.Width = 0;
c.Height = -100;
Assert.AreEqual (150, c.Width);
Assert.AreEqual (150, c.Height);
Assert.AreEqual (0, c.Width);
Assert.AreEqual (0, c.Height);
}
}
}

95
Tests/WriteHtmlTests.cs Normal file
View File

@ -0,0 +1,95 @@
using System;
#if NUNIT
using NUnit.Framework;
using TestClassAttribute = NUnit.Framework.TestFixtureAttribute;
using TestMethodAttribute = NUnit.Framework.TestCaseAttribute;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using Ooui;
namespace Tests
{
[TestClass]
public class WriteHtmlTests
{
System.Text.RegularExpressions.Regex idre = new System.Text.RegularExpressions.Regex ("\\sid=\"[^\"]*\"");
string OuterHtmlWithoutIds (Element e)
{
return idre.Replace (e.OuterHtml, "");
}
[TestMethod]
public void TextAreaWithTextStyled ()
{
var e = new TextArea {
Value = "Hello World!",
};
e.Style.BackgroundColor = "#18f";
Assert.AreEqual ("<textarea style=\"background-color:#18f\">Hello World!</textarea>", OuterHtmlWithoutIds (e));
}
[TestMethod]
public void TextAreaEmptyStyled ()
{
var e = new TextArea ();
e.Style.BackgroundColor = "#18f";
Assert.AreEqual ("<textarea style=\"background-color:#18f\"></textarea>", OuterHtmlWithoutIds (e));
}
[TestMethod]
public void Style ()
{
var e = new Div ();
e.Style.BackgroundColor = "#18f";
Assert.AreEqual ("<div style=\"background-color:#18f\"></div>", OuterHtmlWithoutIds (e));
}
[TestMethod]
public void TwoGrandChildren ()
{
var e = new Div (new Div (new Anchor (), new Anchor ()), new Paragraph ());
Assert.AreEqual ("<div><div><a /><a /></div><p /></div>", OuterHtmlWithoutIds (e));
}
[TestMethod]
public void Child ()
{
var e = new Div (new Anchor ());
Assert.AreEqual ("<div><a /></div>", OuterHtmlWithoutIds (e));
}
[TestMethod]
public void TextChild ()
{
var e = new Paragraph ("Hello world!");
Assert.AreEqual ("<p>Hello world!</p>", OuterHtmlWithoutIds (e));
}
[TestMethod]
public void IdIsFirst ()
{
var e = new Anchor ();
Assert.IsTrue (e.OuterHtml.StartsWith ("<a id=\""));
}
[TestMethod]
public void EmptyElement ()
{
var e = new Anchor ();
Assert.AreEqual ("<a />", OuterHtmlWithoutIds (e));
}
[TestMethod]
public void AnchorHRef ()
{
var e = new Anchor {
HRef = "http://google.com"
};
Assert.AreEqual ("<a href=\"http://google.com\" />", OuterHtmlWithoutIds (e));
}
}
}