Function in Appcelerator causing issues when called quickly - ios

I'm having a few issues with the last couple of pieces on my iOS app built with Appcelerator Titanium.
The app sample below shows one of my windows which allows the user to tap a view (which contains a word), which flips around to show the same word in a different language. The user can then tap the same view again and it animates back to the original position showing the original word.
When the user wants to move onto another word, they simple swipe on the view and it brings in the next word.
Here are the issues i'm experiencing;
If a user swipes super fast through loads of words, then taps to flip, it crashes.
If a user taps the view to flip the view around sometimes the second word flashes up before the animation takes place, it should only be seen as the view comes around into view.
and
3) The user can opt to drop the word, which when tapped performs a database update and then reloads the function and brings a new word in. Great for the first time you use it, but on the 2nd, 3rd, 4th time, the alertbox pops up multiple times rather than once.
Now, I suspect I'm doing something wrong here, but I can't work it out, i've moved code around to make sure labels aren't displaying before they should, but it keeps happening.
Can anyone shed any light on 1 or all of my points? I'm about to lose my mind!
I'm using Titanium 3.20 for iOS
Many thanks
Simon
var win = Titanium.UI.currentWindow;
var selectedlanguage = Ti.App.Properties.getString('langSelect');
// detect height
if (Titanium.Platform.displayCaps.platformHeight == 480) {
var MVTOP = 115;
var tapTOP = 83;
var swipeTOP = 275;
} else {
var MVTOP = 165;
var tapTOP = 133;
var swipeTOP = 325;
}
var masterView = Ti.UI.createView({
backgroundColor: '#FFF',
top: MVTOP,
width: 300,
height: 140,
opacity: 0.7
});
var state = true;
win.add(masterView);
var front = Ti.UI.createView({
backgroundColor: '#FFF',
top: 0,
left: 0,
width: 300,
height: 140,
opacity: 1.0,
touchEnabled: false
});
var back = Titanium.UI.createView({
backgroundColor: '#FFF',
top: 0,
left: 0,
width: 300,
height: 140,
opacity: 1.0,
touchEnabled: false
});
if (win.section == 'word_expressions') {
var label1 = Ti.UI.createLabel({
//text: verb_german,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 20
},
top: 50
});
var label2 = Ti.UI.createLabel({
//text: verb_english,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 20
},
top: 50
});
} else {
var label1 = Ti.UI.createLabel({
//text: verb_german,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 30
},
top: 50
});
var label2 = Ti.UI.createLabel({
//text: verb_english,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 30
},
top: 50
});
}
var dropButton = Ti.UI.createButton({
width: 120,
height: 41,
right: 15,
bottom: 15,
title: 'drop word',
backgroundColor: '#fd0100',
color: '#FFF',
font: {
fontSize: 15
},
opacity: 1.0
});
win.add(dropButton);
function loadWords() {
// get the section to query for the database
var wordSection = win.section;
// get a random pair of words
var db = Ti.Database.open('germanV6');
var rows = db.execute('SELECT * FROM Words WHERE ' + wordSection + ' = 1 AND word_dropped = 0 ORDER BY RANDOM() LIMIT 1');
var x = 0;
while (rows.isValidRow()) {
if (selectedlanguage == 'en') {
var word_1 = rows.fieldByName('word_english');
var word_2 = rows.fieldByName('word_german');
} else if (selectedlanguage == 'de') {
var word_2 = rows.fieldByName('word_english');
var word_1 = rows.fieldByName('word_german');
}
var word_id = rows.fieldByName('word_id');
rows.next();
}
// close database
rows.close();
var state = true;
label1.text = word_1;
front.add(label1);
masterView.add(front);
label2.text = word_2;
back.add(label2);
masterView.addEventListener('click', function (e) {
switch (state) {
case true:
Ti.API.info('true');
masterView.animate({
view: back,
transition: Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT
});
break;
case false:
Ti.API.info('false');
label1.text = word_1;
masterView.animate({
view: front,
transition: Ti.UI.iPhone.AnimationStyle.FLIP_FROM_RIGHT
});
break;
}
state = !state;
});
var eventListener = function () {
// update the DB to tell it the word has been dropped
var dbDelete = Ti.Database.open('germanV6');
var rowsDelete = dbDelete.execute('UPDATE Words SET word_dropped=1 WHERE word_id=' + word_id);
// pop an alert to notify the user the word has been dropped
var alertDialog = Titanium.UI.createAlertDialog({
title: 'Word Dropped',
message: 'This word has been dropped!' + word_id,
buttonNames: ['OK']
});
// show the message
alertDialog.show();
// load in a new word
//loadWords();
alertDialog.addEventListener('click', function (j) {
loadWords();
});
};
}
// fire the function and load our words into play
loadWords();
var tapLabel = Ti.UI.createLabel({
width: 200,
top: tapTOP,
text: 'tap to flip',
textAlign: 'center',
color: '#FFF',
font: {
fontSize: 15
}
});
var swipeLabel = Ti.UI.createLabel({
width: 320,
top: swipeTOP,
text: 'swipe for next word',
textAlign: 'center',
color: '#FFF',
font: {
fontSize: 15
}
});
win.add(tapLabel);
win.add(swipeLabel);
var grammarButton = Ti.UI.createButton({
width: 120,
height: 41,
left: 15,
bottom: 15,
title: 'verb tables',
backgroundColor: '#ffff01',
color: '#000',
font: {
fontSize: 15
},
opacity: 1.0
});
win.add(grammarButton);
swipeLabel.addEventListener('swipe', function (e) {
// reload the new word
loadWords();
});
masterView.addEventListener('swipe', function (e) {
// reload the new word
loadWords();
});
grammarButton.addEventListener('click', function (e) {
var newWin = Titanium.UI.createWindow({
url: 'verb_table.js',
backgroundImage: '/images/background_random.jpg',
backgroundColor: '#FFF',
barColor: '#000',
translucent: true,
color: '#FFF',
navTintColor: '#FFF',
titleControl: Ti.UI.createLabel({
text: 'Verb Table',
color: '#FFF'
}),
statusBarStyle: Titanium.UI.iPhone.StatusBar.LIGHT_CONTENT,
backButtonTitle: ''
});
newWin.nav = win.nav;
win.nav.openWindow(newWin, {
animated: true
});
});

loadWords() adds an event listener to masterView every time it is called. Probably the source of the crash. Do the Ti.API.info calls build up over time of using the app? I'd expect you should see it popping out 1 then 2 then 3... as it runs along.
Is there missing code? The eventListener function is defined, but I can't find where it is called. This function then has another listener that then calls loadWords again adding more listeners. the name of the function eventListener was difficult to look for because all the addEventListener references come up in a search because they match. I'd change the name of that function to something more distinct. It might be getting called in there, but I gave up looking for it.
There is something up with this code. I would expect that the var label1 and var label2 aren't the ones you are adding to the view later on, but I would expect them to go out of scope when they leave your blocks {}. I would move the var label1 and var label2 outside this if-else and just have label1 = Ti.UI... and the label2 = Ti.UI.. in there.
var label1;
var label2;
if (win.section == 'word_expressions') {
label1 = Ti.UI.createLabel({ // FIX
//text: verb_german,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 20
},
top: 50
});
label2 = Ti.UI.createLabel({ // FIX
//text: verb_english,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 20
},
top: 50
});
} else {
label1 = Ti.UI.createLabel({ // FIX
//text: verb_german,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 30
},
top: 50
});
label2 = Ti.UI.createLabel({ // FIX
//text: verb_english,
text: '',
textAlign: 'center',
color: '#000',
font: {
fontSize: 30
},
top: 50
});
}
front.add(label1);
back.add(label2);
Variable Scrope
http://msdn.microsoft.com/en-us/library/bzt2dkta(v=vs.94).aspx
I would say you need to rethink the loadWords function. It is perhaps doing way too much and the source of all the issues. The masterView.addEventListener should be moved out. The alertDialog should be setup a different way as well. Perhaps moving that code to generate the alert outside of the omni function loadWords.
The database is opened repeatedly inside loadWords, but never closed. You did close the row, but forgot the db.
front.add and back.add aren't necessary in the loadWords function, you should have these after the If-Else statement where you are defining them. Keep the code in there that updates, their .text properties.
Looking closer at the label definitions you are defining them exactly the same aside from the font size. I would fix that to only change the font inside the IF-ELSE.
Fix the place where you detect height as well. Move all the var [variable names] out of the block and define them once. In the IF-ELSE then assign them the correct values.

Related

Keep 2 columns next to each other in PDFMake?

I want to have a text s.calculatedQuantity and next to it an icon. But i want them to be always next to each other and not be separated. Sometimes when s.setDescription is long i have a bad result like in the image below. And i dont know why there is sometimes that space between the icon and the text s.calculatedQuantity. Can someone explain to me that ?
.
I Have my code like this :
function generateSetDescription(s, picto) {
return {
columns: [
{
text: `${s.setDescription} - `,
fillColor: '#000',
color: '#FFF'
},
{
text: `${s.calculatedQuantity}`,
fillColor: '#000',
color: '#FFF'
},
{
image: icon,
width: 10,
height: 10,
fillColor: '#000',
},
]
}
}
The problem you're having seems to be caused by too long words (not text) normal text seems to wrap correctly when a blank space is found.
My suggestion is to programmatically break your 'very long words' adding a - in between.
something like this should work in your case
const text = veryLongTextWithLongWords;
const wrappedText = text.split(' ').map(word => {
if(word.length > 80){
return `${word.substr(0, 40)}-${word.substr(41)}
}
return word;
})
const columns = [
{ text: wrappedText }
]
You can test it out here
http://pdfmake.org/playground.html

JSPDF-autotable: Set Dynamic Font Size based on number of columns

I have a need to print a large table with 20+ columns. Is there a way to achieve this without distorting the view.
I have tried setting font size based on the number of columns of the table but unable to achieve that:
doc.autoTable({
styles: {
cellPadding: 0.5,
overflow: 'visible',
cellWidth: 'wrap'
},
columnStyles: {
columnWidth: 'auto'
},
margin: {
left: 5,
right: 5
},
tableLineWidth: 0.5,
head: headers as any,
body: body,
didDrawCell: (data) => {
if (this.length > 5) { // Number of columns
doc.autoTable({
styles: {
fontSize: 1
}
});
}
},
didDrawPage: (data) => {
console.log(data);
}
});
Or is there any other better way to achieve that because currently whatever I try my view is distorted if I show all the columns and if I wrap the columnWidth and cellWidth then only contained element within specified width are shown.
For now I am able to do it by calculating fontSize upFront and passing it as a value in styles object
exportAsPDF(data: Array<any>, fileName: string) {
const headers: Array<Array<string>> = this.setPDFHeader(data);
const fontSize: number = this.calculateFontSize(headers[0].length);
const body: Array<Array<string>> = this.setPDFBody(data);
const doc = new jsPDF();
doc.autoTable({
styles: {
cellPadding: 0.5,
fontSize: fontSize
},
headStyles: {
fillColor: '#3f51b5',
textColor: '#fff',
halign: 'center'
},
bodyStyles: {
halign: 'center'
},
margin: {
left: 5,
right: 5
},
tableLineWidth: 1,
head: headers as any,
body: body
});
doc.save(fileName);
}
setPDFHeader(data: Array<any>): Array<Array<string>> {
return [
Object.keys(data[data.length - 1]).map(
(item) => `${item.charAt(0).toUpperCase()}${item.substr(1, item.length)}`
)
];
}
setPDFBody(data: Array<any>): Array<Array<string>> {
return data.map((item) => {
const keys = Object.keys(item);
const values = [];
keys.forEach((key) => {
values.push(item[key]);
});
return values;
});
}
calculateFontSize(count: number): number {
return count ? tableWidth / count : count;
}

Highchart dynamically draw Legend marker and trigger mouseover event

I have series legends as scrollbar as demo-ed in this fiddle
http://jsfiddle.net/BlackLabel/kb4gu5rn/
How can I draw series legend marker ("circle"/"square"/"diamond" etc..) instead of line
var $line = $('<div>')
.css({
width: 16,
position: 'absolute',
left: -20,
top: 8,
borderTop: '2px solid ' + (series.visible ? series.color :
options.itemHiddenStyle.color)
})
.appendTo($legendItem);
Also upon hover in this legendItemList I would like to trigger the mouseOver event on the series.. To highlight the series(or data points) in the chart for easy co-visualization
I added this handler, but it doesnt work
$legendItem.hover(function () {
series.onMouseOver();
});
Thanks for your help
You can use Highcharts.SVGRenderer class to add a specific legend marker symbol.
To highlight the series use setState('hover):
var chart = Highcharts.chart({...},
function(chart) {
var options = chart.options.legend,
legend = chart.legend;
/**
* What happens when the user clicks the legend item
*/
function clickItem(series, $legendItem, symbolLine, symbolSVG) {
series.setVisible();
$legendItem.css(
options[series.visible ? 'itemStyle' : 'itemHiddenStyle']
);
symbolLine.attr({
stroke: series.visible ? series.color : options.itemHiddenStyle.color
});
symbolSVG.attr({
fill: series.visible ? series.color : options.itemHiddenStyle.color
});
}
// Create the legend box
var $legend = $('<div>')
.css({
width: 110,
maxHeight: 210,
padding: 10,
position: 'absolute',
overflow: 'auto',
right: 10,
top: 40,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
borderStyle: 'solid',
borderRadius: options.borderRadius
})
.appendTo(chart.container);
$.each(chart.series, function(i, series) {
// crete the legend item
var $legendItem = $('<div>')
.css({
position: 'relative',
marginLeft: 20
})
.css(options[series.visible ? 'itemStyle' : 'itemHiddenStyle'])
.html(series.name)
.appendTo($legend);
// create the line with each series color
var symbolEl = $('<div>');
var renderer = new Highcharts.Renderer(
symbolEl[0],
16,
10
);
var symbolLine = renderer
.path([
'M',
0,
5,
'L',
16,
5
])
.attr({
'stroke-width': 2,
stroke: series.color
})
.add();
var symbolSVG = renderer.symbol(
series.symbol,
3,
0,
10,
10,
Highcharts.merge(series.options.marker, {
width: 10,
height: 10
})
).attr({
fill: series.color
})
.add();
symbolEl.css({
position: 'absolute',
left: -20,
top: 2
}).appendTo($legendItem);
// click handler
$legendItem.hover(function() {
chart.series.forEach(function(s) {
if (s !== series) {
s.setState('inactive');
} else {
series.setState('hover');
}
});
}, function() {
chart.series.forEach(function(s) {
s.setState('normal');
});
});
$legendItem.click(function() {
clickItem(series, $legendItem, symbolLine, symbolSVG);
});
});
});
Live demo: http://jsfiddle.net/BlackLabel/mfvh9ubq/
API Reference:
https://api.highcharts.com/class-reference/Highcharts.Series#setState
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#symbol

Precise Difference between Konva.TextPath and Konva.Text classes?

Can anyone elaborate the precise difference between using Konva.TextPath and Konva.Text classes?I am using Konva.js library in my project and I have searched this issue everywhere but there isn't any clear explanation regarding this.
Hope someone can help me out.Thanks!
Konva.Text is simple text on a line.
Konva.Textpath is more complex, for example it can follow a curve.
Run the snippet.
var stage = new Konva.Stage({
container: 'container',
width: 400,
height: 150
});
var layer = new Konva.Layer();
stage.add(layer);
var kerningPairs = {
'A': {
' ': -0.05517578125,
'T': -0.07421875,
'V': -0.07421875,
},
'V': {
',': -0.091796875,
":": -0.037109375,
";": -0.037109375,
"A": -0.07421875,
}
}
var textpath = new Konva.TextPath({
x: 100,
y: 20,
fill: '#333',
fontSize: '24',
fontFamily: 'Arial',
text: 'Textpath - literally text on a path.',
data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50',
getKerning: function(leftChar, rightChar) {
return kerningPairs.hasOwnProperty(leftChar) ? pairs[leftChar][rightChar] || 0 : 0
}
});
layer.add(textpath)
var text = new Konva.Text({
x: 0,
y: 5,
text: 'Konva.Text = simple text.',
fontSize: 30,
fontFamily: 'Calibri',
fill: 'green'
});
layer.add(text);
stage.draw()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<div id='container'></div>

how to add extra labels at load event in highcharts

Code is as below
chart: {
type: "funnel",
marginBottom: 25,
backgroundColor: "transparent",
events: {
load: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
chart.options.labels.items.push({
html: "less confident" + i,
style: { left: 550, top: 50 }
});
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
"text-anchor": "middle"
});
});
}
}
},
I see that you're trying to add a label for every point. Highcharts has build in functionality for this called data labels: https://api.highcharts.com/highcharts/series.line.dataLabels
Another approach is to use SVGRenderer.label: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#label

Resources