I am working on an application where user can add comments to certain fields. these comments can also be links. So, as a user I want to be able to click on those links rather than copy pasting them in a new tab.
If a normal web link ([http://|http:]... or [https://|https:]...) occurs in a comment/attribute value, it should be presented as a clickable link.
Multiple links may occur in the same comment/attribute value.
Clicking on a link opens a new browser tab that calls up this link.
This is how the formControl is being managed. I think i can identify multiply links with the help of regex but how do I make them clickable as well?
Thanks for answering and helping in advance.
this.formControl = new FormControl('', [this.params.customValidations(this.params)]);
this.formControl.valueChanges.subscribe(() => {
this.sendStatusToServices();
});
Outside the form editor/input (most likely what you're looking for)
Either before saving the value of the Form Field to the Database, or editing the received body from the database just before presenting to the user, you can use Regex to replace links with anchor tags.
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
Rich text editor
If however, you're trying to enable links INSIDE the form input (like WordPress's text editor), that's going to be a bit more difficult. You'll need a <textarea> to enable custom HTML elements. Then you need to detect when the user has typed a URL, so you can call replaceURLWithHTMLLinks(). Honestly, you should just use a package. There's several good one out there.
Angular Rich Text Editor - A WYSIWYG Markdown Editor, by SyncFusion
NgxEditor, by sibiraj-s
typester-editor
Hope this helps
Using a regex approach and a pipe I was able to come up with something like below.
What I'm doing is replacing the links with hyperlink tags using a proper regex.
url replacement regex is taken from here
Supports multiple links within same comment.
Here is the sample pipe code
#Pipe({
name: 'comment'
})
export class CommentPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){}
transform(value: any, args?: any): any {
const replacedValue = this.linkify(value);
return this.sanitizer.bypassSecurityTrustHtml(replacedValue)
}
// https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links#21925491
// this method is taken from above answer
linkify(inputText: string) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '$1');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1$2');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+#[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '$1');
return replacedText;
}
}
Here is the completed stackblitz
If you want links within Input itself you might want to try different approach
Related
I'm building a nodejs express app with mongoDB.
I want to make user be able to choose certain predefined tags when submitting a register form.
Register for studios, an attribute is "equipment”,want user to choose from tags "drums","guitar","amp","mic", etc.
And I want to use the tags for search bar function.
Thank you in advance!
So, at the database, you can create a model with 'tags' of String data type. Make an app.post('someURL/:tag'). Get the value of tag using req.params , check if the tags in your model is empty, if it's not , set its value otherwise send back an error.
Anytime you click on the frontend, make a req to the backend using the same API point
Firstly You want to open a tag system. If you do it for user when you search tags you will find users. But in your project there are articles which user can post, it is better to add tags to articles.
I will just show a example.
In your Model.js script just add:
tags:{
type:String,
required:True,//If you want to make tags as a obligation.
},
You should look at here:
Mongodb Nodejs Regex Search
https://www.youtube.com/watch?v=9_lKMTXVk64
Fuzzy Searching with Mongodb?
Add a search.pug:(Or add form in your layout, it depends on your preferences)
form.form-inline.my-2.my-lg-0(action="/sonuc" method="GET")
<input type="text" name="search" placeholder="Search Here..." class="form-control">
After that in your app.js(or whatever you name it):
You can also look here:
https://docs.mongodb.com/manual/reference/operator/query/regex/#examples
app.get('/search', function(req, res){
if (req.query.search) {
const regex = new RegExp(escapeRegex(req.query.search), 'gi');
Article.find({"tags": regex}, function(err, articles) {
if(err) {
console.log(err);
} else {
res.render("index", {
articles: articles
});
}
});
}
});
And in article.pug:
.
.
input.form-control(name='', type='text')
.
.
In app.js you will just add these codes to add articles(post)
let article = new Article({
...
...
...
tags:req.body.tags,
});
You can just change the codes and follow the steps. But I recomend you to write these scripts to your notebook. And then write the meanings of them.
In this project, you will use regex.
Please look at the links that I have send to you and then please write scripts in your notebook and write the meaning of codes.(To learn the structure and steps.)
I am attempting to create a search bar using a custom HTML component for predictive text input. The way this component is built, it generates several plain HTML children that I need to act on to get full features. Specifically, I need to execute a blur action on one of the generated elements when the user presses escape or enter.
I got it to work using a ref on the custom component and calling getElementsByClassName on the ref, but using getElementsByClassName does not seem like the best solution. It pierces through the virtual and has odd side effects when testing.
This is a snippet of the component being rendered:
<predictive-input id='header-search-bar-input' type='search'
value={this.state.keywords}
ref={(ref: any) => this.predictiveInput = ref}
onKeyDown={(e: React.KeyboardEvent<any>) => this.handleKeyDown(e)}>
</predictive-input>
and the keyDown handler:
private handleKeyDown(e: React.KeyboardEvent<any>) {
// must access the underlying input element of the kat-predictive-input
let input: HTMLElement = this.predictiveInput.getElementsByClassName('header-row-text value')[0] as HTMLElement;
if (e.key === 'Escape') {
// blur the predictive input when the user presses escape
input.blur();
} else if (e.key === 'Enter') {
// commit the search when user presses enter
input.blur();
// handles action of making actual search, using search bar contents
this.commitSearch();
}
}
The element renders two children, one for the bar itself and one for the predictive dropdown. The classes of the underlying in the first are 'header-row-text' and 'value', so the element is correctly selected, but I am worried that this is violating proper React style.
I am using React 16.2, so only callback refs are available. I would rather avoid upgrading, but if a 16.3+ solution is compelling enough, I could consider it.
If you don't have any control over the input then this is the best approach in my opinion.
It's not ideal, but as you're stuck with a 3rd party component you can only choose from the methods that are available to you. In this case, your only real options are to find the element based on its class, or its position in the hierarchy. Both might change if the package is updated, but if I had to choose which would be more stable, I'd go for className.
We have a component that contains a background image. Our front-end guy needs it to be loaded through CSS (i.e. background: url(/*path here*/)...). The following is a possible solution we came up with:
#string src = // Get image path from Sitecore().Field("Picture");
<div style="background: url(#src) left top no-repeat;"> ... </div>
However, there are two problems with this approach:
It makes it very difficult for the content editor to swap out the image. They will have to manually change it through edit item.
It feels like a hack/workaround.
So the question is as follows: Is there a way to edit the CSS of an element through Razor/Sitecore? Specifically, the background: field.
I had a similar case and I used :
<footer class="layout_footer" style="background-color: #Model.BackgroundColor">
on view rendering (cshtml file)
And on the model we have :
public string BackgroundColor
{
get
{
Sitecore.Data.Fields.ImageField imgField =((Sitecore.Data.Fields.ImageField)item.Fields["BackgroundImage"]);
return Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem);
}
}
For editing this field in page editor you can use Sitecore Field Editor from a command : http://blog.istern.dk/2012/05/21/running-sitecore-field-editor-from-a-command/
Check for edit mode, and display in edit mode a editable field. Also create a Custom Experience Button from the Field Editor Button Type. You can also display. See User friendly developing with the Sitecore Experience Editor
#string src = // Get image path from Sitecore().Field("Picture");
<div style="background: url(#src) left top no-repeat;">
#if (IsInEditingMode)
{
<h3>Backgroiund Picture: #Editable(m => m.Picture)</h3>
}
</div>
There is no Sitecore extension method which will do this out of the box (i.e. #Html.Sitecore().Field("fieldName") will not work here as it would render the entire image tag (also a load of other non-image markup in page editor mode) as you probably know.
The method that #sitecore climber mentions is useful for controller renderings (or view renderings with a custom RenderingModel). If you want to stick with simple view renderings (i.e. not create a RenderingModel) then you could create a Html extension method which can be re-used on any view rendering. This could be something like the following:
public string ImageFieldSrc(this SitecoreHelper sitecoreHelper, string fieldName, Item item = null)
{
if (item == null) {
item = sitecoreHelper.CurrentItem;
}
var imageField = new ImageField(item.Fields[fieldName]);
var mediaItem = imageField.MediaItem;
var mediaUrl = MediaManager.GetMediaUrl(mediaItem);
mediaUrl = HashingUtils.ProtectAssetUrl(mediaUrl); //if you want to use media request protection (adding the hash onto the end of the URL, use this line
return mediaUrl;
}
It's worth noting that if you are using Sitecore 7.5 or above there is a feature to protect media URLs with a hash to prevent malicious DoS type attacks described in this blog post by Adam Najmanowicz.
In summary; if you are using Sitecore 7.5+ and you use media hashing then you will need to call HashingUtils.ProtectAssetUrl on the media URL if it is to respect size parameters.
I need to change the function that dictates the behavior of my Search form. I want the text to be "GO" instead of "Search" and the input type to be search instead of text.
Now, I already done that by editing the search.module, but is there a more convenient way? I want the theme to be 1 package deal and ready to go, not to have to edit other files from the Drupal installation.
It is for Drupal v.7.16
Thank you!
In your theme's template.php you can override any part of the search form by implement MYTHEME_form_alter.
For your example, it might look something like this:
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'search_block_form') {
// Change form submit text
$form['actions']['submit']['#value'] = t('GO!');
// Change type to 'search'
$form['search_block_form']['#type'] = 'search';
}
}
For more background information about Tanis' solution, see the API documentation for hook_form_alter() and hook_form_FORM_ID_alter().
I´m evaluating GWT as one of the alternatives to develop AJAX applications for my future projects. Untill now it is as good as it gets, but now I´m stuck looking for a way to capture a click on a tag inside HTML widget. I want to write links inside the HTML but I want to process the clicks in my application, withou reloading the page. Imagine I have the following HTML:
<p>GWT is a great tool and I think it will be my preferred tool to develop web applications. To check out my samples <a id='mylink'>click here</a></p>
I want to capture the click over the "click here" part of the text. What I´ve done so far is to try to attach the id "mylink" to some sort of clickable widget and process the click with a ClickHandler for that widget, but nothing is working.
Is there a way to do that? By the way, I know very little about Javascript.
Thank you in advance.
You can also do it like this:
Anchor.wrap(DOM.getElementById("mylink")).addClickHandler(yourClickHandler);
DOM class is com.google.gwt.user.client.DOM.
Edit after comments.
OK, the method works for elements out of GWT widgets (element comes with HTML file). If you need to generate it in GWT code then you can add link element separately. But it won't work if your content goes for instance from DB.
HTMLPanel html = new HTMLPanel("GWT is a great tool and I think it will be my preferred tool to develop web applications. To check out my samples ");`
Anchor a = new Anchor("click here");
a.addClickHandler(yourClickHandler);
html.add(a);
If it is fully dynamic I don't have an idea at this point. I was trying with HTML() widget, where you can plug your click handler, but I couldn't find a right way to determine whether the click was in A element. Strange.
The final approach (I hope)
This one should work finally. And I think this is the way it should be done, especially that it allows any structure of the HTML. The are two ways:
1. Convert links within HTMLPanel
This one will find all A elements and convert them into Anchors. It ignores href attribute, but you can add it easily :)
HTMLPanel html = new HTMLPanel("<p>Multilink example 2: <a>link1</a> and <a>link2</a></p>");
NodeList<Element> anchors = html.getElement().getElementsByTagName("a");
for ( int i = 0 ; i < anchors.getLength() ; i++ ) {
Element a = anchors.getItem(i);
Anchor link = new Anchor(a.getInnerHTML());
link.addClickHandler(...);
html.addAndReplaceElement(link, a);
}
2. Insert links into prepared spots
Just insert placeholders, where the widgets should be inserted. You could also use the addAndReplaceElement() method but with string ID.
Anchor a1 = new Anchor("a1");
a1.addClickHandler(...);
Anchor a2 = new Anchor("a2");
a2.addClickHandler(...);
HTMLPanel html = new HTMLPanel("<p>Multilink example: <span id='a1'></span> and <span id='a2'></span></p>");
html.add(a1, "a1");
html.add(a2, "a2");
Try something like this.
For your web page, you can use UiBinder:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<g:HTMLPanel ui:field="panel">
<p>
GWT is a great tool and I think it will be my preferred tool to
develop web applications. To check out my samples
<g:Anchor ui:field="myLink" text="click here" />
</p>
</g:HTMLPanel>
</ui:UiBinder>
Notice that I've replaced your tag with an Anchor widget. There is also a Hyperlink widget, which has hooks into the history system.
The Anchor has a id of "myLink", which is used in the GWT companion to the XML file:
public class So extends Composite {
private static SoUiBinder uiBinder = GWT.create(SoUiBinder.class);
interface SoUiBinder extends UiBinder<Widget, So> {
}
#UiField
Anchor myLink;
public So() {
initWidget(uiBinder.createAndBindUi(this));
myLink.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
GWT.log("caught the click");
}
});
}
}
I've added a ClickHandler that captures and acts on the click event.
The main program is simple:
public class SOverflow implements EntryPoint {
public void onModuleLoad() {
RootLayoutPanel.get().add(new So());
}
}
Run this after and a webpage appears with the text and hyperlink. Click on it and "caught the click" appears in the console window (I'm using Eclipse).
I hope this is what you're after. If not exactly, it might at least give you some ideas of how to attack your problem.