chrome extensions, trying to make minimize to tray button - javascript

I'm trying to use chrome app samples to make a chrome extensions that has a top custom top bar. I might have butcher the code but could someone help make it work?
https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/frameless-window
I can't make the minimize to tray button to work
function closeWindow() {
window.close();
}
function minimizeWindow() {
window.minimize();
}
function updateImageUrl(image_id, new_image_url) {
var image = document.getElementById(image_id);
if (image)
image.src = new_image_url;
}
function createImage(image_id, image_url) {
var image = document.createElement("img");
image.setAttribute("id", image_id);
image.src = image_url;
return image;
}
function createButton(button_id, button_name, normal_image_url,
hover_image_url, click_func) {
var button = document.createElement("div");
button.setAttribute("class", button_name);
var button_img = createImage(button_id, normal_image_url);
button.appendChild(button_img);
button.onmouseover = function() {
updateImageUrl(button_id, hover_image_url);
}
button.onmouseout = function() {
updateImageUrl(button_id, normal_image_url);
}
button.onclick = click_func;
return button;
}
function focusTitlebars(focus) {
var bg_color = focus ? "#3a3d3d" : "#000000";
var titlebar = document.getElementById("top-titlebar");
if (titlebar)
titlebar.style.backgroundColor = bg_color;
}
function addTitlebar(titlebar_name, titlebar_icon_url, titlebar_text) {
var titlebar = document.createElement("div");
var titlebar_name = "top-titlebar";
titlebar.setAttribute("id", titlebar_name);
titlebar.setAttribute("class", titlebar_name);
var icon = document.createElement("div");
icon.setAttribute("class", titlebar_name + "-icon");
icon.appendChild(createImage(titlebar_name + "icon", "16.png"));
titlebar.appendChild(icon);
var title = document.createElement("div");
title.setAttribute("class", titlebar_name + "-text");
title.innerText = document.title; // titlebar name
titlebar.appendChild(title);
var win = chrome.app.window.current();
var closeButton = createButton(titlebar_name + "-close-button",
titlebar_name + "-close-button",
"img/button_close.png",
"img/button_close_hover.png",
closeWindow);
titlebar.appendChild(closeButton);
// Create minimize button
var minimizeButton = createButton(titlebar_name + "-minimize-button",
titlebar_name + "-minimize-button",
"img/button_minimize.png",
"img/button_minimize_hover.png",
minimizeWindow);
titlebar.appendChild(minimizeButton);
//
var divider = document.createElement("div");
divider.setAttribute("class", titlebar_name + "-divider");
titlebar.appendChild(divider);
document.body.appendChild(titlebar);
}
function removeTitlebar(titlebar_name) {
var titlebar = document.getElementById(titlebar_name);
if (titlebar)
document.body.removeChild(titlebar);
}
function updateContentStyle() {
var content = document.getElementById("content");
if (!content)
return;
var left = 0;
var top = 0;
var width = window.outerWidth;
var height = window.outerHeight;
var titlebar = document.getElementById("top-titlebar");
if (titlebar) {
height -= titlebar.offsetHeight;
top += titlebar.offsetHeight;
}
if (titlebar) {
width -= titlebar.offsetWidth;
}
var contentStyle = "position: absolute; ";
contentStyle += "left: " + left + "px; ";
contentStyle += "top: " + top + "px; ";
contentStyle += "width: " + width + "px; ";
contentStyle += "height: " + height + "px; ";
content.setAttribute("style", contentStyle);
}

This will fix the problem
function minimizeWindow() {
var window = chrome.app.window.current();
window.minimize();
}

Related

Manipulating data point in chart.js external tooltip

I'm using Chart.js to display some financial data in a pie chart, along with external tooltips. The data in the tooltip is displayed currently like this:
"Invoiceable: 1,202.5"
What I want is to firstly round the number to 1,200, and then add a '£' sign before the data point so it reads:
"Invoiceable: £1,200"
I'm struggling to work out how to do this in this code below. Can anyone help?
tooltip: {
// Disable the on-canvas tooltip
enabled: false,
external: function(context) {
// Tooltip Element
let tooltipEl = document.getElementById('chartjs-tooltip');
// Create element on first render
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = '<table></table>';
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
const tooltipModel = context.tooltip;
if (tooltipModel.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltipModel.yAlign) {
tooltipEl.classList.add(tooltipModel.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltipModel.body) {
const titleLines = tooltipModel.title || [];
const bodyLines = tooltipModel.body.map(getBody);
let innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
innerHtml += '<tr><td><div class="tooltip">'+ body + '</div></td></tr>';
});
innerHtml += '</tbody>';
let tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
const position = context.chart.canvas.getBoundingClientRect();
const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);
// Display, position, and set styles for font
tooltipEl.style.opacity = .8;
tooltipEl.style.position = 'absolute';
tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
tooltipEl.style.font = bodyFont.string;
tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
tooltipEl.style.pointerEvents = 'none';
}
}
FTR - I copied the above code from chart.js, which made it work, but I don't presume to understand it for a second!
You can adjust the bodyLines.forEach loop to alter the value it shows like so:
bodyLines.forEach(function(body, i) {
let [label, value] = body[0].split(': ');
value = `£${value.split('.')[0]}`
innerHtml += '<tr><td><div class="tooltip">' + `${label}: ${value}` + '</div></td></tr>';
});
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: 'Invoicable',
data: [120000.5, 190000.7, 30000.2, 50000.3, 20000.9, 30000.1],
borderColor: 'pink',
backgroundColor: 'pink',
}]
},
options: {
locale: 'en-EN',
plugins: {
tooltip: {
// Disable the on-canvas tooltip
enabled: false,
external: function(context) {
// Tooltip Element
let tooltipEl = document.getElementById('chartjs-tooltip');
// Create element on first render
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = '<table></table>';
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
const tooltipModel = context.tooltip;
if (tooltipModel.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltipModel.yAlign) {
tooltipEl.classList.add(tooltipModel.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltipModel.body) {
const titleLines = tooltipModel.title || [];
const bodyLines = tooltipModel.body.map(getBody);
let innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
let [label, value] = body[0].split(': ');
value = `£${value.split('.')[0]}`
innerHtml += '<tr><td><div class="tooltip">' + `${label}: ${value}` + '</div></td></tr>';
});
innerHtml += '</tbody>';
let tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
const position = context.chart.canvas.getBoundingClientRect();
const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);
// Display, position, and set styles for font
tooltipEl.style.opacity = .8;
tooltipEl.style.position = 'absolute';
tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
tooltipEl.style.font = bodyFont.string;
tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
tooltipEl.style.pointerEvents = 'none';
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

Trying to make a marquee

I am currently generating the elements putting them into a container and I want that container to move from right to left of the marquee tag.
HTML:
<div class="news_wrapper">
<div class="news_start"></div>
<div class="news_end"></div>
<div id="marquee" class="news_text">
<!--<p>Consider a small donation btc: 114t1q7Fro4JCANagYMF55BynAGhvsk39z</p>-->
</div>
</div>
JavaScript:
function createElement(type, attributes, someElement) {
var element = document.createElement(type);
for (var key in attributes) {
if (key === "class") {
var cls = attributes[key];
for (var c in cls)
element.classList.add(cls[c]);
} else {
element[key] = attributes[key];
}
}
someElement.appendChild(element);
}
window.addEventListener('load', function () {
var news_marquee = document.getElementById("marquee"),
news_marquee_width,
news_volatility,
news_class,
news_name,
news_track,
news_track_width,
lcal_coinsss,
find_volatility;
add_news();
function move_news() {
news_track_width = news_track_width + 1;
console.log(news_track_width);
news_track.style.right = "-" + news_track_width + "px";
setInterval(move_news, 1000);
}
function add_news() {
lcal_coinsss = JSON.parse(localStorage.getItem('coinss'));
find_volatility = findVolatility(lcal_coinsss);
var newElement = createElement("div", {
"id": "news_track",
"class": ["news_track"]
}, news_marquee);
news_track = document.getElementById("news_track");
for (var i in find_volatility) {
news_volatility = find_volatility[i][1];
if (news_volatility >= 1) {
news_class = "positive_number_text";
} else if (news_volatility <= -1) {
news_class = "negative_number_text";
}
var newElement = createElement("p", {
"id": "news_name" + find_volatility[i][0],
"class": ["news_name"]
}, news_track);
news_name = document.getElementById("news_name" + find_volatility[i][0]);
news_name.textContent = find_volatility[i][0];
var newElement = createElement("span", {
"id": "news_volatility" + find_volatility[i][0],
"class": [news_class]
}, news_track);
news_volatility = document.getElementById("news_volatility" + find_volatility[i][0]);
news_volatility.textContent = find_volatility[i][1];
}
news_marquee_width = news_marquee.offsetWidth;
news_track_width = news_track.offsetWidth;
news_track.style.right = "-" + news_track_width + "px";
move_news();
// console.log(news_marquee_width);
// console.log(news_track_width);
}
I am generating the elements, and they are in a wrapper inside the marquee but I am not able to move it as I want to, when I run the move_news it will add right CSS expotentional.
Basically I want the generated div with content to move in a marquee style.
If anyone has any suggestions towards the whole script please let me know.

Fabricjs - How to detect canvas on mouse move?

In my fabricjs application, I had created dynamic canvases(variable's also dynamic). Here, I need to detect particular canvas while mouse move on canvas.
Sample code,
var i = 0, canvasArray = [];
$(this).find('canvas').each(function() {
i++;
var DynamicCanvas = 'canvas_'+i;
canvasArray[DynamicCanvas] = new fabric.Canvas('canvas_'+i,{
width : '200',
height : '200'
});
});
after this, I have 4 different canvases. Last added canvas has been activated. But i need to add object on any canvas.
So that i have to activate canvas using mouse move event. How can i achieve it.? Please help me on this.
Mullainathan,
Here some quick solution using jQuery:
var canvasStr = '';
var canvasArray = [];
var fabricCanvasArray = [];
var htmlStr = '';
var canvas = null;
//generate canavases
for (var i = 0; i < 4; i++){
canvasArray.push('c' + i);
htmlStr += '<canvas id="c' + i + '" width="200" height="200"></canvas>'
}
//append canvasses to the body
$('body').append(htmlStr);
//to the fabricjs parent div elements assign id's and generate string for jQuery with div id's
for (var i in canvasArray){
fabricCanvasArray[i] = new fabric.Canvas(canvasArray[i], {
isDrawingMode: true
});
$('#' + canvasArray[i]).parent().attr('id', ('div' + canvasArray[i]));
canvasStr += '#div' + canvasArray[i];
if (i < canvasArray.length - 1){
canvasStr += ',';
}
}
//jQuery event for mouse over each div element of the fabric canvas
$(canvasStr).mouseover(function(){
for (var i in fabricCanvasArray){
if (fabricCanvasArray[i].lowerCanvasEl.id == $(this).children(':first').attr('id')){
canvas = fabricCanvasArray[i];
canvas.freeDrawingBrush.width = 10;
var r = 255 - i*50;
var g = i * 50;
var b = 200 - i * 40;
canvas.freeDrawingBrush.color = 'rgb(' + r + ',' + g + ',' + b + ')';
canvas.on('mouse:up', function() {
//do your stuff
// canvas.renderAll();
});
break;
}
}
});
Also, you can run fiddle

How to calculate content height by using pure javascript

I have used this code for defining "mainContent div height"
but it alerts undefined!
window.onload = function () {
alert(mainContent.height);
}
function viewPort() {
var pageWrapper = document.getElementById('pageWrapper').offsetHeight;
pageFooter = document.getElementById('pageFooter').offsetHeight;
pageHeader = document.getElementById('pageHeader').offsetHeight;
differenceInHeight = pageWrapper - (pageHeader + pageFooter);
mainContent = document.getElementById('mainContent').style.height = differenceInHeight + 'px';
};

Need help in displaying selection handles on rectangle using javascript

I am trying to add something to my code so as to select the image after drawing ( the selection handler should appear in the corners and in the middle of edge) and then drag or increase/decrease the height and width?
My sample code is in the fiddle , in this I am drawing a rectangle using the mouse event handlers. I want to select the rectangle and modify/alter it using the selection handlers instead of drawing it again.
Click the button ROI, metrics and then you can draw it using the mouse events.
http://jsfiddle.net/AhdJr/53/
var oImageBuffer = document.createElement('img');
var oCanvas=document.getElementById("SetupImageCanvas");
var o2DContext=oCanvas.getContext("2d");
var oRect = {};
var oROI = {};
var oMetrics ={};
var oLayers = new Array();
var bDragging = false;
var bSetROI = false;
var bSetLayers = false;
InitMouseEvents();
var oSelect = document.getElementById("ImageList");
oSelect.onchange=function() {
changeCanvasImage(oSelect[oSelect.selectedIndex].value);
}
// Canvas event handlers (listeners).
function InitMouseEvents() {
oCanvas.addEventListener('mousedown', MouseDownEvent, false);
oCanvas.addEventListener('mouseup', MouseUpEvent, false);
oCanvas.addEventListener('mousemove', MouseMoveEvent, false);
oCanvas.addEventListener('mouseout', MouseOutEvent, false);
}
function MouseDownEvent(e) {
oRect.startX = e.pageX - this.offsetLeft;
oRect.startY = e.pageY - this.offsetTop;
bDragging = true;
}
function MouseUpEvent() {
bDragging = false;
}
function MouseOutEvent() {
document.getElementById("MouseCoords").innerHTML="";
}
function MouseMoveEvent(e) {
if (bDragging) {
oRect.w = (e.pageX - this.offsetLeft) - oRect.startX;
oRect.h = (e.pageY - this.offsetTop) - oRect.startY;
oCanvas.getContext('2d').clearRect(0,0,oCanvas.width, oCanvas.height);
var oROI = document.getElementById("btnROI");
if (oROI.checked) {
SetROI();
}
var oLayer = document.getElementById("btnLAYER");
if (oLayer.checked) {
SetLayer();
}
var oMetrics = document.getElementById("btnMetrics");
if (oMetrics.checked) {
SetMetrics();
}
}
if (bSetROI) {
DrawROI();
}
if (bSetLayers) {
DrawLayers();
}
if(bSetMetrics){
DrawMetrics();
}
// Display the current mouse coordinates.
ShowCoordinates(e);
}
function ShowCoordinates(e) {
x=e.clientX;
y=e.clientY;
document.getElementById("MouseCoords").innerHTML="(" + x + "," + y + ") " + document.getElementById('txtPatchCount').value;
}
// Interactively draw ROI rectangle(s) on the canvas.
function SetROI() {
bSetROI = true;
oROI.startX = oRect.startX;
oROI.startY = oRect.startY;
oROI.w = oRect.w;
oROI.h = oRect.h;
}
function DrawROI() {
o2DContext.lineWidth=1.5;
o2DContext.strokeStyle = '#0F0';
o2DContext.strokeRect(oROI.startX, oROI.startY, oROI.w, oROI.h);
var iPatches = document.getElementById('txtPatchCount').value;
o2DContext.beginPath();
var iTop = oROI.startY;
var iBottom = oROI.startY + oROI.h;
var iLeft = oROI.startX;
var iX = iLeft;
for (var iPatch=1; iPatch<iPatches; ++iPatch) {
iX = iLeft + iPatch*oROI.w/iPatches;
o2DContext.moveTo(iX, iTop);
o2DContext.lineTo(iX, iBottom);
}
o2DContext.lineWidth=0.25;
o2DContext.stroke();
}
function SetMetrics() {
bSetMetrics = true;
oMetrics.startX = oRect.startX;
oMetrics.startY = oRect.startY;
oMetrics.w = oRect.w;
oMetrics.h = oRect.h;
}
function DrawMetrics(){
o2DContext.strokeStyle = 'black';
o2DContext.strokeRect(oMetrics.startX, oMetrics.startY, oMetrics.w, oMetrics.h);
o2DContext.beginPath();
var iTop = oMetrics.startY;
var iBottom = oMetrics.startY + oMetrics.h;
var iLeft = oMetrics.startX;
var iX = iLeft;
o2DContext.moveTo(iX, iTop);
o2DContext.lineTo(iX, iBottom);
o2DContext.stroke();
}
// Interactively draw layer boundaries on the canvas.
function SetLayer() {
bSetLayers = true;
oLayers.length = 0;
oLayers.push(oRect.startY);
oLayers.push(oRect.startY + oRect.h);
}
function DrawLayers() {
o2DContext.lineWidth=0.25;
o2DContext.strokeStyle = '#F00';
o2DContext.beginPath();
var iY = oLayers[0];
var iLeft = 0;
var iRight = oCanvas.width;
for (var iLayer=0; iLayer<oLayers.length; ++iLayer) {
iY = oLayers[iLayer];
o2DContext.moveTo(iLeft, iY);
o2DContext.lineTo(iRight, iY);
o2DContext.stroke();
}
}
The below blog is doing the same thing but I am not sure how to add this functionality in my code.
http://simonsarris.com/blog/225-canvas-selecting-resizing-shape
Please guide me how to add the same in mine.
Really appreciate the help.
try the following link.
It is doing somewhat you want to achieve.
http://simonsarris.com/blog/225-canvas-selecting-resizing-shape

Categories

Resources