Replacing JSON strings with images - javascript

I have a table column that's populated by documents and in the next column I've rendered what the file extension of that document is (i.e. .docx).
I want to be able to replace the file extension text with icon images that are locally stored (folder/src/SiteAssets/Images/docx.gif).
Would I be able to work with the original code I have:
// -- Generating extension names -- //
function docType(fileName) {
return [fileName].filter(function() {
return true;
}).map(function(fileName) {
return fileName.split('.').pop();
}).pop();
}
to replace the text with the icons? I was thinking of something like if (extension===true), replace with icon.gif. If need be I can get rid of this code and work with something else.
Loading document data:
$.noConflict();
let tableRes = JSONfile.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name,
"Categories": obj.ResourceType.results.map(function(val) {
return val.Label;
}).join(";"),
"Blank": "",
"docImg": docType(obj.File.Name) // "Getting the docType of obj.File.Name"
}
})
Rendering table:
$('#km-table-id').DataTable( {
columns: [
// { data: "Blank" },
{ data: "Categories" }, // hidden
{ data: "docImg" },
{ data: "Titles" }
],
...etc

Related

Zoomchart net chart form links issue

I'm using the Zoomchart library's NetChart class to form netchart. But I'm facing issue with links. And not able to find any solution.
Below is the case which I want to achieve:-
Let suppose we have two nodes A and B. Here A is the seller and B is the buyer.
Seller A -> B
Buyer B -> A
I'm loading data dynamically. And when we initially loading A then we are getting B as Buyer of A. And this forms a link like A -> B. But when B loads its related data then it is getting A as it is buying data from it(A).
And this form two link nodes:-
{
"from": "A",
"to": "B"
}
{
"from": "B",
"to": "A"
}
It is creating a chart like this:-
But it should be a single link. Below is the code:-
this.chartObject = new NetChart({
container: document.getElementById('sellerBuyersLinkingChart'),
area: { height: null },
navigation:{
focusNodeExpansionRadius: 1,
initialNodes: ["n-1"],
mode:"focusnodes"
},
data: {
dataFunction: (nodeList, success, error) => {
$.ajax({
url:url+'?nodes='+nodeList.toString(),
success: (response, textStatus, jqXHR) => {
success(response, textStatus, jqXHR);
},
error: error
});
},
requestMaxUnits: 1
},
style: {
nodeStyleFunction: (node) => {
},
linkStyleFunction: (link) => {
let type = link.data['extra']['type'];
if(type == 'sellers') {
link['fromDecoration'] = "arrow";
link['fillColor'] = "rgba(47,195,47,0.8)";
link['direction'] = "L";
} else {
link['toDecoration'] = "arrow";
link['fillColor'] = "rgba(236,46,46,0.8)";
link['direction'] = "R";
}
},
nodeFocused: {
fillColor: 'rgba(232,189,43,1)'
}
}
});
Expectations: Is there any way that I can send to link id with URL. With that way, I can remove the same node from the link.
This chart should create nodes like this:-
1) You can use multiLinkProcessor to combine multiple links if they are not unique
2) If you add unique id to links, then you can update, remove or manipulate them individually (in fact it's recommended to always add id for links and nodes and that will prevent duplicates). Not having ids will prompt notice in console log as well.

Rendering local JSON data into a Tabulator Table

I'm attempting to implement local JSON data into a Tabulator table. I specifically want to display the obj.File.Name JSON element.
I can render the data into a regular table, but when I incorporate Tabulator the data doesn't render at all. I think the problem lies with the Tabulator Section that's listed in the JS Snippet, but I'm not 100% sure. I'm interested in using Tabulator because of the features it offers.
Unless I misread it, the Tabulator docs on loading data seems to be less focused on local files and more on external URLs, which is why I've come to ask about it here.
I've included a JS Fiddle that shows the HTML and the JS.
JS snippet:
import $ from 'jquery';
import JSONfile from '../../../public/JSONfile.json';
import { basename } from 'path';
var Tabulator = require('tabulator-tables');
var categories = '';
var tableRes = '';
export default class {
constructor() {
this.loadData();
this.loadTableData();
}
loadTableData() {
let tableRes = JSONfile.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
// "FileName": obj.FileLeafRef,
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name
}
});
///// Tabulator Section /////
let tableData = tableRes;
let table = new Tabulator("#km-table-id", {
data:tableData,
columns:[
{title:"", field:" "},
{title:"All Templates", field:"Name"},
{title:"My Favorites", field:"faves"}
],
pagination:"local",
paginationSize:100,
placeholder:"No data available"
});
table.setData(tableData);
} // ------------------ loadTableData
} // ------------- export default class
JSON snippet:
{
"d": {
"results": [
{
"__metadata": {
...
},
"File": {
"__metadata": {
...
},
"Name": "Guide to Product IDs.docx"
},
"FileLeafRef": "Guide to Product IDs.docx",
"ResourceType": {
...
},
"results": [
{
...
}
]
},
"EncodedAbsUrl": [redacted]
},
...
...
The issue you are having is because the data is not in the format that Tabulator is expecting.
Tabulator requires an array of row data objects, based on your column definitions it is looking for this:
[
{Name:"steve", faves:"this, that, the other"},
{Name:"bob", faves:"this, that, the other"},
]
Loading local data into the table is covered in the Documentation

ElasticSearch Javascript, Highlight not working

we switched recently to ElasticSearch Angular version and everything is working as expected except the Highlight, which is not returned at all.
This is how I setup a demo query:
$esClient.search({
index: 'myIndex',
body: {
size: 10,
from: 0,
query: query,
highlight: {
fields: {
"_all": { "pre_tags": ["<em>"], "post_tags": ["</em>"] }
}
}
}
}).then(function (result) {
// map the resultset for Row Template
var currentRows = result.hits.hits.map(function (record) {
return {
"type": record._type,
"entity": record._source, // the result
"highlight": record.highlight, // the highlights
"id": record._id // Search record ID
};
});
});
If I use the same code with a classic XmlHttpRequest and pass the query model inlcuding the highlight, I get back a JSON which contains an highlight array per each result, while using the ElasticSearch Angular client the query succeed but I don't get back the highlight.
Am I doing something wrong?
I think you might want to change to this format:
{
"query" : {...},
"highlight" : {
"pre_tags" : ["<tag1>"],
"post_tags" : ["</tag1>"],
"fields" : {
"_all" : {}
}
}}
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html

Swapping data in Angular UI-Grid, new columns not visible when changing dataset externally

I've got a query tool I've been working on, which has an angular form that is filled out, and then when it's submitted it uses AJAX which returns JSON, which is then rendered into ui-grid, that JSON response looks like
{
"success": true,
"message": "",
"columns": ["first_name", "last_name", "company", "employed"]
"results": [
{first_name: "John", last_name: "Smith", company: "Abc Inc", employed: true},
{first_name: "Johnny", last_name: "Rocket", company: "Abc Inc", employed: true}]
}
I'm working on both the PHP and angular so I have full control over this JSON response if need be. I'm running into an issue when my JSON response from a first AJAX call is rendered, and then I run another, seperate AJAX call on the same page and get a new data set: this new data set does not render any of the columns that were not in the original data set. This is hugely problematic as the table is essentially cleared when none of the columns are the same, and I often need to load completely different data into ui-grid in this single page app.
When the JSON is recieved I simply bind the jsonResult.results to the old $scope.myData variable that ui-grid is bound to.
I've made a plunker isolating this issue. A dataset with a "punk" column is loaded, and then clicking "swap data" will try to load a dataset with "employee" column instead of "punk". I've so far looked into directives that will refresh or reload when the $scope.myData variable changes using $watch, and looked at finding something like $scope.columnDefs to let ui-grid know. Relatively new to angular and javascript so directives are still a bit over my head.
I have updated your plunker slightly:
$scope.swapData = function() {
if ($scope.gridOpts.data === data1) {
$scope.gridOpts.columnDefs = [
{ name:'firstName' },
{ name:'lastName' },
{ name:'company' },
{ name:'employee' }
];
$scope.gridOpts.data = data2;
//punk column changes to employee
}
else {
$scope.gridOpts.columnDefs = [
{ name:'firstName' },
{ name:'lastName' },
{ name:'company' },
{ name:'punk' }
];
$scope.gridOpts.data = data1;
//employee column changes to punk
}
};
http://plnkr.co/edit/OFt86knctJxcbtf2MwYI?p=preview
Since you have the columns in your json, it should be fairly easy to do.
One additional piece that I figured out with the help of Kevin Sage's answer and the plunker example... If you are using the backward-compatible "field" attribute the swapping does not work properly when there are field name overlaps between the two sets of column definitions. The column headers and the column widths are not rendered properly in this case. Using the "name" attribute of the column definition corrects this.
$scope.swapData = function() {
if ($scope.gridOpts.data === data1) {
$scope.gridOpts.columnDefs = [
{ field:'firstName' },
{ field:'lastName' },
{ field:'company' },
{ field:'employee' }
];
$scope.gridOpts.data = data2;
//punk column changes to employee
}
else {
$scope.gridOpts.columnDefs = [
{ field:'firstName' },
{ field:'lastName' },
{ field:'company' },
{ field:'punk' }
];
$scope.gridOpts.data = data1;
//employee column changes to punk
}
};
Example here: Plunker
My solution:
$http.get('url').success(function(res) {
// clear data
gridOptions.data.length = 0;
// update data in next digest
$timeout(function() {
gridOptions.data = res;
});
});

how to write json files in javascript

Ok, so I am programming a web operating system using js. I am using JSON for the file system. I have looking online for tutorials on JSON stuff for about a week now, but I cannot find anything on writing JSON files from a web page. I need to create new objects in the file, not change existing ones. Here is my code so far:
{"/": {
"Users/": {
"Guest/": {
"bla.txt": {
"content":
"This is a test text file"
}
},
"Admin/": {
"html.html": {
"content":
"yo"
}
}
},
"bin/": {
"ls": {
"man": "Lists the contents of a directory a files<br/>Usage: ls"
},
"cd": {
"man": "Changes your directory<br/>Usage: cd <directory>"
},
"fun": {
"man": "outputs a word an amount of times<br/>Usage: fun <word> <times>"
},
"help": {
"man": "shows a list of commands<br/>Usage: help"
},
"clear": {
"man": "Clears the terminal<br/>Usage: clear"
},
"cat": {
"man": "prints content of a file<br/>Usage: cat <filename>"
}
},
"usr/": {
"bin/": {
},
"dev/": {
}
}
}}
I think the better solution is to stringify your JSON, encode with base64 encoding and then send it to a server-side script (a PHP page, for instance) which could save this file. See:
var json = JSON.stringify(myJson);
var encoded = btoa(json);
You can use ajax for sending:
var xhr = new XMLHttpRequest();
xhr.open('POST','myServerPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send('json=' + encoded);
And in the server-side:
$decoded = base64_decode($_POST['json'])
$jsonFile = fopen('myJson.json','w+');
fwrite($jsonFile,$decoded);
fclose($jsonFile);
I'd take off the "/"'s from the keys then could split on "/" and walk the tree by shifting values off the result. For example, the following code will create the full path if it doesn't already exist, but preserving the folder & contents if it does.
var fs = {
"bin": {
"mkdir": function(inPath) {
// Gets rid of the initial empty string due to starting /
var path = inPath.split("/").slice(1);
var curFolder = fs;
while(path.length) {
curFolder[path[0]] = curFolder[path[0]] || {};
curFolder = curFolder[path.shift()];
}
}
}
}
fs.bin.mkdir("/foo/bar");
console.log(JSON.stringify(fs, function(key,val) {
if(key === 'mkdir') return undefined;
return val;
}, 2));
Output:
{
"bin": {},
"foo": {
"bar": {}
}
}
As others have mentioned, rather than building the JSON object by hand with strings, to avoid syntax errors (and frustration), building it through code then using JSON.stringify to get the final result would likely be simpler.

Categories

Resources