chartjs tooltip label is adding quotes at improper position while showing - chart.js

I have created a group bar chart using chartJs.
While showing tooltip on bar, i want to show some part of tooltip string in double quotes ("").
I applied below code:
tooltips: {
displayColors: false,
mode: 'label',
callbacks: {
title: function() {},
label: function(tooltipItem, data) {
var tooltipLabel1 = 'Series '+ '"'+data['datasets'][0]['label']+'" '+
'Point ' + '"'+tooltipItem.label.split(" ")[1] + " " + tooltipItem.label.split(" ")[0]+'"';
var tooltipLabel2 = 'Value: ' + tooltipItem.value;
console.log([tooltipLabel1, tooltipLabel2]); // screenshot attached for this output
return [tooltipLabel1, tooltipLabel3];
}
}
},
It working fine but it is showing one of double quote at start and end double quote is removing.
Attached screenshot for this, what exactly it is showing on mouse-hover as well as in screenshot of console.
As well as, when I write console for this, because of json string, it add output in ""
What I can do? really clueless now.

Related

ChartJS 4 migration: access other datasets from tooltip callback

I'm migrating from ChartJS 2.9.3 to 4.2.1 (current). By following the 3.x and 4.x migration guides, I've sorted most things out, but I've come across a problem that I don't see a solution for.
One of my charts is a stacked bar chart. There are two datasets for it:
let chartData = {
// other stuff...
datasets: [
{ label: "Has thing", data: [200, 250, etc] },
{ label: "Does not has thing", data: [10, 4, etc] },
]
}
In my tooltips, I was accessing both datasets to create a custom tooltip with the percent representation of each part of each stack. For instance, the tooltips for the first stack might say: "Has thing: 200 (95.2%)" and "Does not has thing: 10 (4.8%)". My callback function looked like this:
// other stuff
callbacks: {
label: function(tooltipItem, data) {
let dataset = data.datasets[tooltipItem.datasetIndex];
let count_with = data.datasets[0].data[tooltipItem.index]
let count_without = data.datasets[1].data[tooltipItem.index]
let total = count_with + count_without
let this_dataset_count = dataset.data[tooltipItem.index]
let this_dataset_perc = (this_dataset_count / total * 100).toFixed(1)
let label = dataset.label + ": "
label += this_dataset_count + " (" + this_dataset_perc + "%)"
return label;
}
}
Looking at the 3.x migration guide, it appears they removed the data parameter from the tooltip callback, opting instead to add the item's dataset directly to the tooltipItem. Unfortunately, they don't seem to specify how I can access other datasets.
Has this functionality simply been removed completely, or is there a different way to access it?
As #kikon pointed out, data is accessible via context.chart.data. For some reason, that doesn't show up for me when I console.dir() the context object so I was just completely overlooking it.
Anyway, for anyone this might help in the future, here's the working version:
callbacks: {
label: function(context) {
const datasets = context.chart.data.datasets
const countWith = datasets[0].data[context.dataIndex]
const countWithout = datasets[1].data[context.dataIndex]
const perc = (context.raw / (countWith + countWithout) * 100).toFixed(1)
return `${context.dataset.label}: ${context.formattedValue} (${perc}%)`
}
}

How to change color of text following a specific symbol in text field and text editor? SwiftUI

I have this function which when called in a view will, take the inputted String, and output the same string, but with words following the # symbol changed in colour:
func textWithSymbols(_ text: String, color: Color) -> Text {
let words = text.split(separator: " ")
var output: Text = Text("")
for word in words {
if word.hasPrefix("#") { // Pick out # in words
output = output + Text(" ") + Text(String(word))
.foregroundColor(color) // Add custom styling here
} else {
output = output + Text(" ") + Text(String(word))
}
}
return output
}
I would call it like:
var txt = "What do you think #test"
textWithSymbols(txt, color: .red)
The result would be the same text, but #test would be highlighted in red.
How would I apply this same functionality to both a text field and text editor where text is constantly being updated?
I've used the .onChange modifier before for stuff like counting lines and replacing text, so maybe that might be a start?

ChartJS Tooltip - Change Data Format Displayed

I've created a horizontal floating bar chart using ChartJS. The data I am passing in is formatted as:
[
{
rowName: 'Project 1',
startDate: '2021-03-15',
endDate: '2021-04-20',
}
]
Where my x axis shows a month/year and my y axis shows the rowName. I've added chartjs-adapater-date-fns but in order to get the floating bars to work, I've had to convert the startDate and endDate into new dates and then use the .getTime() function to retrieve a number for the data the chart expects. E.g. [new Date(startDate).getTime(), new Date(endDate).getTime()].
On my tooltip, it shows the label as rowName which is what I'm wanting, however the data value shows as the two number values being passed in.
I'm wanting to show the tooltip in the following format:
Project 1
Start Date: 05/03/2021
End Date: 20/04/2021
What is the best way of doing this?
Note: I have consoled the context and found that data.raw provides me with 2021-05-03,2021-04-20 if that is of any use?
Instead of new date pass your input date , Tooltip will show with formatted date value.
var barOption = {
tooltips: {
callbacks: {
label: function(t, d) {
this.date=new Date();
let formated_date = this.datepipe.transform(this.date, 'dd/MM/yyy');
return formated_date;
},
},
},
}

Can I printf as console.warn with emscripten?

Is it possible to display a console warning, instead of a console log, from the C/C++?
So far printf("Message") will print on the regular console.log on the JS side, is it possible to print as warning like console.warn?
In generated html file, standard output is mapped to console.log().
For example
var Module = {
preRun: [],
postRun: [],
print: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
console.warn(text);
},
printErr: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
console.error(text);
},
https://emscripten.org/docs/api_reference/module.html?highlight=stdout#Module.print

Export value with Linebreaks into single cell in Excel with jQuery Datatables 2016

I'm trying to retain linebreaks made with <br> in an HTML table when exporting it to excel with DataTables. I followed their guide to replace certain things with Regex here: DataTables find and replace during export.
I was able to replace things no problem. But I fail to replace the <br> with newlines that make content in the same cell retain their linebreaks.
This is my JS:
$( document ).ready(function() {
var fixNewLine = {
exportOptions: {
format: {
body: function ( data, column, row ) {
// Strip $ from salary column to make it numeric
return column === 5 ?
// THIS WORKS: data.replace(/test/ig, "blablabla"):
data.replace( /<br\s*\/?>/ig, '"'+"\r\n"+'"' ) :
data;
}
}
}
};
$('#table2excel').DataTable({
dom: 'Bfrtip',
buttons:[
$.extend( true, {}, fixNewLine, {
extend: 'copyHtml5'
} ),
$.extend( true, {}, fixNewLine, {
extend: 'excelHtml5'
} ),
$.extend( true, {}, fixNewLine, {
extend: 'pdfHtml5'
} )
]
});
});
The problem lies in this line:
data.replace( /<br\s*\/?>/ig, '"'+"\r\n"+'"' ) :
It gets saved in excel with only a pair of " " instead of the actual line break.
Note that this also doesn't work:
data.replace( /<br\s*\/?>/ig, "\r\n"):
Any advice?
There is a similar thread here: Export value with Linebreaks into single cell in Excel. jQuery Datatables
But it's outdated as it's a year old and there have been updates to DataTables and "TableTools" has been replaced by "Buttons".
The correct answer is:
data.replace( /<br\s*\/?>/ig, "\n" ) :
However, you need to press the "wrap text" button when opening the excel.
If someone knows a way to have it wrapped automatically, please let me know.
The replace function is built in to javascript. Maybe you'd like to remove the quotations?
data.replace( /<br\s*\/?>/ig, "\r\n")
Works for me in a javascript interpreter.
Its possible that the caller of your formatting function removes newlines and replaces them with spaces
This works for me with auto wrap text in Windows Excel 2016
data.replace( /<br\s*\/?>/ig, "\r") // \r, not \n
And customize buttons
$('#myTable').DataTable( {
buttons: [
{
extend: 'excelHtml5',
customize: function( xlsx ) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
// set cell style: Wrapped text
$('row c', sheet).attr( 's', '55' );
}
}
]
});
More info about button customization: https://datatables.net/reference/button/excelHtml5