How can I get special characters using elm-html module? - elm

Disclaimer: I'm brand new to Elm
I'm fiddling around with the online Elm editor and I've run into an issue. I can't find a way to get certain special characters (copyright, trademark, etc.) to show up. I tried:
import Html exposing (text)
main =
text "©"
All that showed up was the actual text ©. I also tried to use the unicode character for it \u00A9 but that ended up giving me a syntax error:
(line 1, column 16): unexpected "u" expecting space, "&" or escape code
The only way I found was to actually go to someone's website and copy/paste their copyright symbol into my app:
import Html exposing (text)
main =
text "©"
This works, but I would much rather be able to type these characters out quickly instead of having to hunt down the actual symbols on other websites. Is there a preferred/recommended method of getting non-escaped text when returning HTML in Elm?
Edit:
Specifically for Mac:
option+g gives you ©
option+2 gives you ™
option+r gives you ®
All tested in the online editor and they worked. This still doesn't attack the core issue, but it's just something nice to note for these specific special characters.

Why this is (intentionally) not so easy
The "makers" of Elm are understandably reluctant to give us a way to insert "special" characters into HTML text. Two main reasons:
This would open a "text injection" hole where a malicious user could insert any HTML tags, even JavaScript code, into a Web page. Imagine if you could do that in a forum site like Stack Overflow: you could trick anyone reading your contribution into executing code of your choosing in their browser.
Elm works hard to produce optimal DOM updates. This only works with the content of tags that Elm is aware of, not with text that happens to contain tags. When people insert text containing HTML tags in an Elm program, there end up being parts of the DOM that can't be optimized.
How it's possible anyway
That said, the Elm user community has found a loophole that affords a workaround. For the reasons above, it's not recommended, especially not if your text is non-constant, i.e. comes from a source outside your program. Still, people will be wanting to do this anyway so I'm going to document it to save others the trouble I had digging everything up and getting it working:
If you don't already have it,
import Json.Encode exposing (string)
This is in package elm-lang/core so it should already be in your dependencies.
Similarly,
import Html.Attributes exposing (property)
Finally, create a tag having a property "innerHTML" and a JSON-Value representation of your text, e.g.:
span [ property "innerHTML" (string " ") ] []

I found, that there is a better solution:
you can convert special characters from Unicode to char, and then create a string from char:
resString = String.fromChar (Char.fromCode 187)

You can use directly the unicode escape code in Elm strings and chars:
We have a util module containing all our special chars like:
module Utils.SpecialChars exposing (noBreakSpace)
noBreakSpace : Char
noBreakSpace = '\x00A0'
Which can be used as:
let
emptyLabel = String.fromChar noBreakSpace
in
label []
[ span [ ] [ text emptyLabel ]
]
This will render a <span> </span>

I recently created an Elm package that solves this. If you use text' "©" it'll render the copyright symbol © instead of the escape code. Also works with "©" and "©". Hope this helps!

You don't need to hunt the symbols, you can get them from a list like this one.
If it's too bothersome to copy & paste, you can also create a helper function that you can use with your escaped characters like this:
import Html exposing (..)
import String
htmlDecode str =
let
replace (s1, s2) src= String.join s2 <| String.split s1 src
chrmap =
[ ("®", "®")
, ("©", "©" )
]
in
List.foldl replace str chrmap
main = text <| htmlDecode "hello ©"

Related

extracting part of success text using selenium webdriver

I have the following text appearing on the success page of my application.
This is to confirm that your application has been received. Your Order Number is “#00007942”. If further instructions or any clarification is needed regarding your application, a representative will contact you.
Complete text having same property.
Please help me in extracting the value 00007942 and store it in variable.
First, get your text in your way.
String successMessage = driver.findElement(By.cssSelector("your selector")).getText(); // use locator of your wish
Now, use replace all non-digit from your string as follows-
String orderNumber = successMessage.replaceAll("\\D+", ""); // this replaces all non-digits from your previous string
there is no way to retrieve partial text in selenium webdriver.
Instead, you access the complete text of an Web Element using element.getText() in Java or element.text in python and store it as a String variable.
Then you process the string to retrieve the substring you want.
In all programming languages, there are many ways to achieve it. some of them are substring method, regular expression.

Can I define a text property as rich text?

VS 2013, VB, EF6
I am creating an object that will keep user input in one of its properties. I would like that user input to be stored as rich text. What's involved to make that stored text be rich text format? So,
Public Property Text as <what?>
I thought I would post what was my answer for others who might ask the question the same way I did. I begin by stating that my question was poorly formed because I didn't understand I'm not really storing RTF, I'm storing WYSIWYG text with html tags. But I think the question as phrased is useful because that's how many people think until they are taught by others.
Ultimately this process opens a serious XSS vector, but first we have to at least collect the WYSIWYG text.
First step: using a script-based editor capture the text with html tags. I used CKEditor which is easy to download on NuGet. It comes in 3 flavors: basic, standard and full. Another popular one seems to be TinyMCE also available through NuGet.
CKEditor must be 'wired in' to replace the existing input element. I replaced #html.editorfor with a < textarea > directly as follows. Model.UserPost.Body is the property into which I want to place the WYSIWYG text. The Raw helper is required so the output is NOT encoded allowing us to see our WYSIWYG text.
<textarea name="model.UserPost.Body" id="model_UserPost_Body" class="form-control text-box multi-line">
#Html.Raw(Model.UserPost.Body)
</textarea>
CKEditor is 'wired in' using a script element to replace the < textarea > element.
#Section Scripts
<script src="~/scripts/ckeditor/ckeditor.js"></script>
<script>
CKEDITOR.replace('model.UserPost.Body');
</script>
End Section
The script above can be added to all pages via _layout.vbhtml, or just the target page via a #Section Scripts section as shown above, which is often recommended and what I did, but that may also require adding to the standard _Layout the following in the < head > section such as follows.
#RenderSection("Styles", False)
In the controller POST method for the view the following code is needed to capture the WYSIWYG text otherwise the default filter will raise an exception when it detects anything that looks like an html tag.
Dim rawBody = Request.Unvalidated.Form("model.UserPost.Body")
userPost.Body = rawBody
There are some possible gotcha's; The 'body' property has to be removed from the Include:= list of the < Bind > element in the method paramter list if < Bind > is being used. Also, although not directly related to this solution, you can't have a Data Annotation like < Required() > on this property in the model because background checking won't be able to confirm that condition so the ModelState.IsValid flag won't ever go true.
Second step: before saving the input it MUST be checked for XSS. Microsoft has a nice video explaining basic XSS that I recommend viewing; it's only 11 minutes.
Mikesdotnetting has a nice explaination for dealing with XSS and shows a whitelisting algorithm toward the bottom of this page. The following code is based on his work.
To create a white listing approach, the HTML Agility Pack is useful to catalogue the HTML nodes for review. This is easily loaded from Nu Get as well. This is the code I used in the POST method to invoke the white list methods (Yes, it could be more compact, but this is easier to read for us novices):
Dim tempDoc = New HtmlDocument()
tempDoc.LoadHtml(rawBody)
RemoveNodes(tempDoc.DocumentNode, allowedTags)
userPost.Body = tempDoc.DocumentNode.OuterHtml
The allowed tags are what you will allow, which means everything else is rejected, hence whitelisting. This is just a sample list:
Dim allowedTags As New List(Of String)() From {"p", "em", "s", "ol", "ul", "li", "h1", "h2", "h3", "h4", "h5", "h6", "strong"}
These are the methods based on Mikesdotnetting page:
Private Sub RemoveNodes(ByVal node As HtmlNode, allowedTags As List(Of String))
If (node.NodeType = HtmlNodeType.Element) Then
If Not allowedTags.Contains(node.Name) Then
node.ParentNode.RemoveChild(node)
Exit Sub
End If
End If
If (node.HasChildNodes) Then
RemoveChildren(node, allowedTags)
End If
End Sub
Private Sub RemoveChildren(ByVal parent As HtmlNode, allowedTags As List(Of String))
For i = parent.ChildNodes.Count() - 1 To 0 Step -1
RemoveNodes(parent.ChildNodes(i), allowedTags)
Next
End Sub
So basically, (1) CKEditor captures user input with html tags that looks nice, (2) the raw input is specially requested in the Controller POST method and then (3) cleaned using a white list. After that it can be output directly to the page using #Html.Raw() because it can be trusted.
That's it. I've not really posted solutions like this before, so if I've missed something let me know and I'll correct or add it.
Rich Text is stored in the Rich Text Format.
The Rich Text Format specifications can be found here:
http://www.microsoft.com/en-us/download/details.aspx?id=10725
It is just an ordinary string. You can extract the string from a RichTextBox using the SaveFile function:
Private Function GetRTF(ByRef Box As RichTextBox) As String
Using ms As New IO.MemoryStream
Box.SaveFile(ms, RichTextBoxStreamType.RichText)
Return System.Text.Encoding.ASCII.GetString(ms.ToArray)
End Using
End Function
You can load text in the Rich Text Format into a RichTextBox using the LoadFile method of the RichTextBox. The text needs to be in the correct format:
Dim rtf As String = "{\rtf1 {\colortbl;\red0\green0\blue255;\red255\green0\blue0;}Guten Tag!\line{\i Dies} ist ein\line formatierter {\b Text}.\line Das {\cf1 Ende}.}"
Using ms As New IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes(rtf))
RichTextBox1.LoadFile(ms, RichTextBoxStreamType.RichText)
End Using
Ordinary controls usually will not interpret this format in their text property.

mvc4 jquery autocomplete items showing up as asterisks instead of readable data

I got my autocomplete stuff working well enough to see that it's returning some data when I type in a field--but the data shown in the dropdown below the textbox is just a vertical column of asterisks or list item bullets. (I can't really tell what they are.)
When I query the web service directly in the browser, it returns a Json array as expected which looks like this where, for example ?term=chi (I've added some line breaks for readability)
[
{"Name":"Chihuahua"},
{"Name":"Chinese Crested"},
{"Name":"Chinese Shar-Pei"},
{"Name":"Japanese Chin"},
{"Name":"Schipperke"}
]
My JavaScript looks like this:
$(function() {
$("#Breed").autocomplete({
source: "#Url.Action("BreedList", "Patient")"
});
});
like I say, my textbox in question (#Breed) does respond sort of like an autocomplete box, but the dropdown data is weird. Any ideas?
Although I did have a CSS bundling problem (somehow I had omitted the jquery ui css from my bundle), a bigger issue was that the Json returned by my service needed a lower case "value" property for each item. I was using the column name as cased on my Linq query. The tip that pointed me in the right direction on this came from the answer here: jQueryUI autoComplete returns back empty list

How could I escape a & in Haml so that it compiles to & instead of &? (Haml noob)

I am trying to use the Icomoon icon font with Haml and can't seem to find a way to escape the & so that it stays just an & instead of &.
The Icomoon font allows you to use HTML entities with a data-icon="" attribute. Works smooth as butter in HTML and even in a Haml file if I just do a straight HTML link.
However, since I'm learning Haml I thought I'd see if anyone on here would like to recommend the best way to approach this.
Here's a sample of what happens.
This is the original Haml:
%a(href='/posts' data-icon="&#x0026" aria-hidden='true')
This is how it compiles:
<a aria-hidden='true' data-icon='&#x0026' href='/posts'>
This is how it needs to compile for the icon font to work:
<a aria-hidden='true' data-icon='&#x0026' href='/posts'>
and here is a codepen where you can see how the icon renders due to the amp; addition: http://codepen.io/dandenney/pen/3/6
I didn't like the top poster's way of completing this question. So far the best way I've found is to do:
- foo = "&#x0026".html_safe
%a(href='/posts' data-icon=foo aria-hidden='true')
I'm not fully happy with this, but think it's better for rails apps rather than turning off HTML escaping everywhere.
You can use the :escape_attrs option to control whether HTML sensitive characters in attributes are escaped:
require 'haml'
haml = "%a(href='/posts' data-icon=\"&#x0026\" aria-hidden='true')"
puts Haml::Engine.new(haml, :escape_attrs => false).to_html
Output:
<a aria-hidden='true' data-icon='&#x0026' href='/posts'></a>
Note that this will apply to all attributes in your Haml template.
In my opinion, I don't like the idea to disable the feature to escape the characters generally. Maybe you use relay at some point in your application on it.
For me the best way to do it is:
%a{ href: '/', 'data-icon' => "✐".html_safe }

subscript text in a locale .yml string

Is there any way of styling my en.yml text as per below...
en:
...
phosphorus: "lbs/ac of Phosphorus (P<sub>2</sub>O<sub>5</sub>)"
As you can see I want the numbers to be subscript text.
This text is used as a label in a form.
Any ideas?
To include HTML in your translations, your keys should end in _html or .html e.g.
en.phosphorus.html or en.phosphorus_html (I personally prefer the first version).
Rails will know not to HTML escape these strings.