hi
can I display current date and time in Arabic format using flash CS6 and as3
var now:Date=new Date()
this["st_rep"+c]["date"].text=now.toDateString()
this["st_rep"+c]["time"].text=now.toTimeString().slice(0,8)
thank's in advance
this is what I do
var eng_num=["0","1","2","3","4","5","6","7","8","9"]
var ara_num=["۰","۱","۲","۳","٤","٥","٦","۷","۸","۹"]
function convert_arabic(str:String)
{
var new_str=""
for(var f=0;f<str.length;f++)
{
var temp=str.slice(f,f+1)
var xx:int=int(temp)
if(String(Number(temp)) == String(temp))
{
for(var d=0;d<=eng_num.length;d++)
{
if(temp == eng_num[d])
{
new_str+=ara_num[d]
}
}
}
else
{
new_str+=temp
}
}
return new_str
}
nice solution for the arabic numbers :). You can write a simpler version of the function like this:
function convert_arabic(str:String)
{
var eng_num = ["0","1","2","3","4","5","6","7","8","9"];
var ara_num = ["۰","۱","۲","۳","٤","٥","٦","۷","۸","۹"];
for(var f:int = 0; f < eng_num.length; f++)
str = str.replace(new RegExp(eng_num[f], "g"), ara_num[f]);
return str;
}
regards,
There is no magic way to do it, you have create a formatter function. Something like this:
var now:Date = new Date()
trace(formatDate(now.toDateString()));
function formatDate(dateStr:String)
{
var dateParts:Array = dateStr.split(" ");
var dayName:String = getDayName(dateParts[0]);
var monthName:String = getMonthName(dateParts[1]);
var day:String = dateParts[2];
var year:String = dateParts[3];
return year + " " + monthName + " " + day + " " + dayName;
}
function getMonthName(month:String):String
{
switch (month)
{
case "Jan": return "يناير";
case "Feb": return "فبراير";
case "Mar": return "مارس";
case "Apr": return "إبريل";
case "May": return "مايو";
case "Jun": return "يونيو";
case "Jul": return "يوليو";
case "Aug": return "أغسطس";
case "Sep": return "سبتمبر";
case "Oct": return "أكتوبر";
case "Nov": return "نوفمبر";
case "Dec": return "ديسمبر";
}
return null;
}
function getDayName(day:String):String
{
switch (day)
{
case "Sat": return "السبت";
case "Sun": return "الأحد";
case "Mon": return "الإثنين";
case "Tue": return "الثلاثاء";
case "Wed": return "الأربعاء";
case "Thu": return "الخميس";
case "Fri": return "الجمعة";
}
return null;
}
note that you cannot make the numbers appear in arabic from flash as to what I know. If you must show the numbers in arabic you can create a 10 frames movieclip in the library each frame holds 1 arabic digit image and create a formatter function that attaches clips from from the library according to each arabic digit.
Flash Player 10.1 added a DateTimeFormatter as part of the flash.globalization package. It should at least partially help you out.
import flash.globalization.DateTimeFormatter;
var d:Date = new Date();
// The locale for Jordan is "ar-JO"
var dtf:DateTimeFormatter = new DateTimeFormatter("ar-JO", DateTimeStyle.LONG, DateTimeStyle.LONG);
trace(dtf.format(d));
// Output on a PC running an English version of Windows:
// 11 آب, 2013 01:57:06 م
You can get right-to-left text if you use a TLF textfield. Note, though, that TLF has been removed from the current version of Flash Pro (Flash Pro CC 1.0), and it's not clear if/when there will be a replacement.
Related
Let's say we have a name set to "Ben Bright". I want to output to the user "BB", with the first characters of each word. I tried with the split() method, but I failed to do it with dart.
String getInitials(bank_account_name) {
List<String> names = bank_account_name.split(" ");
String initials;
for (var i = 0; i < names.length; i++) {
initials = '${names[i]}';
}
return initials;
}
Allow me to give a shorter solution than the other mentioned:
void main() {
print(getInitials('')); //
print(getInitials('Ben')); // B
print(getInitials('Ben ')); // B
print(getInitials('Ben Bright')); // BB
print(getInitials('Ben Bright Big')); // BB
}
String getInitials(String bank_account_name) => bank_account_name.isNotEmpty
? bank_account_name.trim().split(' ').map((l) => l[0]).take(2).join()
: '';
The take(2) part ensures we only take up to two letters.
EDIT (7th October 2021):
Or if we must be able to handle multiple spaces between the words we can do (thanks #StackUnderflow for notice):
void main() {
print(getInitials('')); //
print(getInitials('Ben')); // B
print(getInitials('Ben ')); // B
print(getInitials('Ben Bright')); // BB
print(getInitials('Ben Bright Big')); // BB
print(getInitials('Ben Bright Big')); // BB
}
String getInitials(String bankAccountName) => bankAccountName.isNotEmpty
? bankAccountName.trim().split(RegExp(' +')).map((s) => s[0]).take(2).join()
: '';
Notice that split takes a RegExp(' +') compared to the original solution.
Just a slight modification since you only need the first letters
String getInitials(bank_account_name) {
List<String> names = bank_account_name.split(" ");
String initials = "";
int numWords = 2;
if(numWords < names.length) {
numWords = names.length;
}
for(var i = 0; i < numWords; i++){
initials += '${names[i][0]}';
}
return initials;
}
Edit:
You can set the value of num_words to print the intials of those many words.
If the bank_account_name is a 0 letter word, then return an empty string
If the bank_account_name contains lesser words than num_words, print the initials of all the words in bank_account_name.
var string = 'William Henry Gates';
var output = getInitials(string: string, limitTo: 1); // W
var output = getInitials(string: string, limitTo: 2); // WH
var output = getInitials(string: string); // WHG
String getInitials({String string, int limitTo}) {
var buffer = StringBuffer();
var split = string.split(' ');
for (var i = 0 ; i < (limitTo ?? split.length); i ++) {
buffer.write(split[i][0]);
}
return buffer.toString();
}
A more general solution can be found below. It takes care of empty strings, single word strings and situations where anticipated word count is less than actual word count:
static String getInitials(String string, {int limitTo}) {
var buffer = StringBuffer();
var wordList = string.trim().split(' ');
if (string.isEmpty)
return string;
// Take first character if string is a single word
if (wordList.length <= 1)
return string.characters.first;
/// Fallback to actual word count if
/// expected word count is greater
if (limitTo != null && limitTo > wordList.length) {
for (var i = 0; i < wordList.length; i++) {
buffer.write(wordList[i][0]);
}
return buffer.toString();
}
// Handle all other cases
for (var i = 0; i < (limitTo ?? wordList.length); i++) {
buffer.write(wordList[i][0]);
}
return buffer.toString();
}
Edit:
I actually use this for CircleAvatars with no images in my projects.
I used CopsOnRoad solution but I was getting the following error.
RangeError (index): Invalid value: Only valid value is 0: 1
So I modified it to
String getInitials(String string, [int limitTo = 2]) {
if (string == null || string.isEmpty) {
return '';
}
var buffer = StringBuffer();
var split = string.split(' ');
//For one word
if (split.length == 1) {
return string.substring(0, 1);
}
for (var i = 0; i < (limitTo ?? split.length); i++) {
buffer.write(split[i][0]);
}
return buffer.toString();
}
Here are some tests in case you are interested
void main() {
group('getInitials', () {
test('should process one later word name correctly', () {
final result = getInitials('J');
expect(result, 'J');
});
test('should process one word name correctly', () {
final result = getInitials('John');
expect(result, 'J');
});
test('should process two word name correctly', () {
final result = getInitials('John Mamba');
expect(result, 'JM');
});
test('should process more than two word name correctly', () {
final result = getInitials('John Mamba Kanzu');
expect(result, 'JM');
});
test('should return empty string when name is null', () {
final result = getInitials(null);
expect(result, '');
});
test('should return empty string when name is empty', () {
final result = getInitials('');
expect(result, '');
});
});
}
String getInitials(full_name) {
List<String> names = full_name.split(" ");
print("org::: $full_name");
print("list ::: $names");
print("Substring ::: ${names[0].substring(0,1)}");
String initials = "";
int numWords = 2;
numWords = names.length;
for(var i = 0; i < numWords; i++)
{
initials += '${names[i].substring(0,1)}';
print("the initials are $initials");
}
return initials;
}
On Nov, 2022
Working solution using Regex:
String getInitials(String string) => string.isNotEmpty
? string.trim().split(RegExp(' +')).map((s) => s[0]).join()
: '' ;
I would like to simulate a keyboard backspace delete event from a string in Flutter (or Dart). Something like:
String str = "hello🇵🇬你们😀😀👨👩👦"
myBackspace(str) // will return "hello🇵🇬你们😀😀"
myBackspace(str) // will return "hello🇵🇬你们😀"
myBackspace(str) // will return "hello🇵🇬你们"
myBackspace(str) // will return "hello🇵🇬你"
myBackspace(str) // will return "hello🇵🇬"
myBackspace(str) // will return "hello"
myBackspace(str) // will return "hell"
Update
Dart team released a helper package that helps achieving this. String.characters.skipLast(1) should be able to do what you expect.
Old answer
First, let's get to some definitions. According to this page:
Bytes: 8-bit. The number of bytes that a Unicode string will take up in memory or storage depends on the encoding.
Code Units: The smallest bit combination that can be used to express a single unit in text encoding. For example 1 code unit in UTF-8 would be 1 byte, 2 bytes in UTF-16, 4 bytes in UTF-32.
Code Points [or rune]: Unicode character. A single integer value (from U+0000-U+10FFFF) on a Unicode space.
Grapheme clusters: A single character perceived by the user. 1 grapheme cluster consists of several code points.
When you remove the last char using substring, you're actually removing the last code unit. If you run print(newStr.codeUnits) and print(str.codeUnits), you'll see that the rune 128512 is equivalent to the joint of the code units 55357 and 56832, so 55357 is actually valid, but doesn't represent anything without the "help" of another code unit.
In fact, you don't want to use substring() when there's non-ASCII chars in your String (like emojis or arabic letters). It'll never work. What you have to do is remove the last grapheme cluster. Something as simple as that:
str.graphemeClusters.removeLast()
However, Dart doesn't support this yet. There are several issues around this point. Some of those:
https://github.com/dart-lang/language/issues/34
https://github.com/dart-lang/language/issues/49
This lack of support seams to result in some other of issues, like the one you mentioned and this one:
https://github.com/flutter/flutter/issues/31818
String formatText(String str) {
final RegExp regExp = RegExp(r'(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])');
if(str.contains(regExp)){
str = str.replaceAll(regExp,'');
}
return str; }
Ex: Go to https://dartpad.dev/ to test:
String str = "ThaiKV受け行くけどよね😞😞😍😰😒😜" => ThaiKV受け行くけどよね
This answer still has problem
Since dart does not provide the data type 'Grapheme Cluster', I try to use method channel to do this using kotlin:
Step 1: Create a new 'Flutter Plugin' project, name the project 'gmc01', 2 files will be created automatically, namely 'gmc01.dart' and 'main.dart'.
Step 2: replace the codes in gmc01.dart with the following:
import 'dart:async';
import 'package:flutter/services.dart';
class Gmc01 {
static const MethodChannel _channel =
const MethodChannel('gmc01');
static Future<String> removeLastGMC(String strOriginal) async {
final String version = await _channel.invokeMethod('removeLastGMC', strOriginal);
return version;
}
}
Step 3: Replace the codes in main.dart with the following:
import 'package:gmc01/gmc01.dart';
void main() async {
String strTemp = '12345678我们5🇵🇬你😀👨👩👦';
strTemp = await Gmc01.removeLastGMC(strTemp);
print(strTemp);
strTemp = await Gmc01.removeLastGMC(strTemp);
print(strTemp);
strTemp = await Gmc01.removeLastGMC(strTemp);
print(strTemp);
strTemp = await Gmc01.removeLastGMC(strTemp);
print(strTemp);
strTemp = await Gmc01.removeLastGMC(strTemp);
print(strTemp);
strTemp = await Gmc01.removeLastGMC(strTemp);
print(strTemp);
strTemp = await Gmc01.removeLastGMC(strTemp);
print(strTemp);
}
Step 4: Inside android/build.gradle, change the minSdkVersion from 16 to 24.
Step 5: Inside example/android/app/build.gradle, change the minSdkVersion from 16 to 24.
Step 6: Click File->Open, select gmc01->android, then click 'OK', the kotlin part of the plugin will be opened (In another Window).
Step 7: Replace the codes in Gmc01Plugin.kt with the following: (Replace the first line with your own package name)
package com.example.gmc01 // replace the left with your own package name
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import android.icu.text.BreakIterator
class Gmc01Plugin: MethodCallHandler {
companion object {
#JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), gmc01)
channel.setMethodCallHandler(Gmc01Plugin())
}
}
override fun onMethodCall(call: MethodCall, result: Result) {
var strArg: String
strArg = call.arguments.toString()
var boundary = BreakIterator.getWordInstance()
boundary.setText(strArg);
when (call.method) {
removeLastGMC -> {
result.success(removeLastGMC(boundary, strArg))
}
else -> {
result.notImplemented()
}
}
}
fun removeLastGMC(boundary: BreakIterator, source: String):String {
val end = boundary.last()
val start = boundary.previous()
return source.substring(0, start)
}
}
Step 8: Go back to the window of the plugin, and click 'Run'.
Here are the output in the console:
I/flutter (22855): 12345678我们5🇵🇬你😀
I/flutter (22855): 12345678我们5🇵🇬你
I/flutter (22855): 12345678我们5🇵🇬
I/flutter (22855): 12345678我们5
I/flutter (22855): 12345678我们
I/flutter (22855): 12345678
I/flutter (22855):
As you can see, the 'Family Emoji', 'Face Emoji' and 'Country Flag' emoji are removed correctly, but the Chinese 2 chars '我们' and the digits '12345678' are removed by using a single removeLastGMC, so still need to figure out how to distinguish Chinese Double Bytes characters / English Chars / Emojis.
BTW, I don't know how to do the Swift part, can someone help?
Its a bit unclear to what you want to check. I suggest you remove the -1 from the substring because it will break the emoji's code snip
void main() {
var str = "abc😀";
var newStr = str.substring(0, str.length); // i removed it here
print(newStr);
print(newStr.runes);
print(str.runes);
}
This will give the output of
abc😀
(97, 98, 99, 128512)
(97, 98, 99, 128512)
Tested in https://dartpad.dartlang.org/
The code is not working
The code is not working properly. I just put here for reference.
Trial 1
Problem: can not handle 🇵🇬 and 👨👩👦 properly.
String myBackspace(String str) {
Runes strRunes = str.runes;
str = String.fromCharCodes(strRunes, 0, strRunes.length - 1);
print(str);
return str;
}
Trial 2
Problem: can not handle connected emoji sequence 😀😀 and 👨👩👦 properly.
Based on the link
String myBackspace(String str) {
int i = 0;
while (str.length > 0) {
i++;
int removedCharCode = str.codeUnitAt(str.length - 1);
if (isWellFormattedUTF16(removedCharCode)) break;
str = str.substring(0, str.length - 1);
}
if (i == 1) str = str.substring(0, str.length - 1);
print(str);
return str;
}
bool isWellFormattedUTF16(int charCode) {
int surrogateLeadingStart = 0xD800;
int surrogateLeadingEnd = 0xDBFF;
int surrogateTrailingStart = 0xDC00;
int surrogateTrailingEnd = 0xDFFF;
if (!(charCode >= surrogateLeadingStart && charCode <= surrogateLeadingEnd) &&
!(charCode >= surrogateTrailingStart && charCode <= surrogateTrailingEnd)) return true;
return false;
}
if someone need simple solution to remove emojies from string try this.
String str = "hello🇵🇬你们😀😀👨👩👦"İ
final RegExp REGEX_EMOJI = RegExp(r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])');
if(str.contains(REGEX_EMOJI)){
str = str.replaceAll(REGEX_EMOJI,'');
}
With RegExp and replaceAll:
final regex = RegExp(
"(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-
\udfff]|\ud83e[\ud000-\udfff])");
final textReplace = String.replaceAll(regex, '');
You can do a method like this one
bool isValid(String prevString, String newString){
if (prevString == newString)
return true;
else return false;
}
then in your keyboard you validate with an onChange property
TextField(
onChanged: (text) {
isValid(varYouHad ,text); //validate
},
);
The focus moves to the next input field before the event is fired. Can anyone help me find the bug, or figure out how to find it myself?
The goal is to catch the keyup event, verify that it is tab or shift+tab, and then tab as though it were tabbing through a table. When the focus gets to the last input that is visible, the three rows (see fiddle for visual) should move together to reveal hidden inputs. Once to the end of the inputs in that row, the three rows will slide back down to the beginning again, kind of like a carriage return on a typewriter, or tabbing into a different row in a table.
Right now, the tab event is moving just the row that holds the focus, and it is moving it before my script even starts to run. I just need to know why this is happening so that I can research how to resolve it.
Any help you can offer is appreciated. Please let me know if you need more information.
P.S. Using jquery 1.9.1
Link to Fiddle
jQuery(document).ready(function ($) {
// bind listeners to time input fields
//$('.timeBlock').blur(validateHrs);
$('.timeBlock').keyup(function () {
var caller = $(this);
var obj = new LayoutObj(caller);
if (event.keyCode === 9) {
if (event.shiftKey) {
obj.dir = 'prev';
}
obj.navDates();
}
});
// bind listeners to prev/next buttons
$('.previous, .next').on('click', function () {
var str = $(this).attr('class');
var caller = $(this);
var obj = new LayoutObj(caller);
obj.src = 'pg';
if (str === 'previous') {
obj.dir = 'prev';
}
obj.navDates();
});
});
function LayoutObj(input) {
var today = new Date();
var thisMonth = today.getMonth();
var thisDate = today.getDate();
var dateStr = '';
var fullDates = $('.dateNum');
var splitDates = new Array();
this.currIndex = 0; //currIndex defaults to 0
this.todayIndex;
fullDates.each(function (index) {
splitDates[index] = $(this).text().split('/');
});
//traverse the list of dates in the pay period, compare values and stop when/if you find today
for (var i = 0; i < splitDates.length; i++) {
if (thisMonth === (parseInt(splitDates[i][0], 10) - 1) && thisDate === parseInt(splitDates[i][1], 10)) {
thisMonth += 1;
thisMonth += '';
thisDate += '';
if (thisMonth.length < 2) {
dateStr = "0" + thisMonth + "/";
}
else {
dateStr = thisMonth + "/";
}
if (thisDate.length < 2) {
dateStr += "0" + thisDate;
}
else {
dateStr += thisDate;
}
fullDates[i].parentNode.setAttribute('class', 'date today');
this.todayIndex = i;
break;
}
}
//grab all of the lists & the inputs
this.window = $('div.timeViewList');
this.allLists = $('.timeViewList ul');
this.inputs = $('.timeBlock');
//if input`isn't null, set currIndex to match index of caller
if (input !== null) {
this.currIndex = this.inputs.index(input);
}
//else if today is in the pay period, set currIndex to todayIndex
else if (this.todayIndex !== undefined) {
this.currIndex = this.todayIndex;
}
//(else default = 0)
//grab the offsets for the cell, parent, and lists.
this.winOffset = this.window.offset().left;
this.cellOffset = this.inputs.eq(this.currIndex).offset().left;
this.listOffset = this.inputs.offset().left;
//grab the width of a cell, the parent, and lists
this.cellWidth = this.inputs.outerWidth();
this.listWidth = this.inputs.last().offset().left + this.cellWidth - this.inputs.eq(0).offset().left;
this.winWidth = this.window.outerWidth();
//calculate the maximum (left) offset between the lists and the parents
this.offsetMax = (this.listWidth - this.winWidth);
//set default scroll direction as fwd, and default nav as tab
this.dir = 'next';
this.src = 'tab';
//grab the offsets for the cell, parent, and lists.
this.cellOffset = this.inputs.eq(this.currIndex).offset().left;
this.listOffset = this.inputs.eq(0).offset().left;
this.winOffset = this.allLists.parent().offset().left;
//calculate the maximum (left) offset between the lists and the parents
this.offsetMax = (this.listWidth - this.winWidth);
}
LayoutObj.prototype.focusDate = function () {
this.inputs.eq(this.currIndex).focus();
};
LayoutObj.prototype.slideLists = function (num) {
this.listOffset += num;
this.allLists.offset({ left: this.listOffset });
};
LayoutObj.prototype.navDates = function () {
if (!this.inWindow()) {
var slide = 0;
switch (this.src) {
case 'pg':
slide = this.winWidth - this.cellWidth;
break;
case 'tab':
slide = this.cellWidth + 1;
break;
default:
break;
}
if (this.dir === 'next') {
slide = -slide;
}
this.slideLists(slide);
}
this.focusDate();
};
LayoutObj.prototype.inWindow = function () {
//detects if cell intended for focus is visible in the parent div
if ((this.cellOffset > this.winOffset) && ((this.cellOffset + this.cellWidth) < (this.winOffset + this.winWidth))) {
return true;
}
else {
return false;
}
}
All it needed was 'keydown()' instead of 'keyup().'
I'm trying to write a test script using automation in xcode 4.5.
I have a UICollectionView and I want to click on some cell not currently visible.
Per documentation, I should expect cells to return all cells in the collection view, and visibleCells to return only the currently visible ones.
Instead what I'm seeing is that cells returns only the currently visible cells, and calling visibleCells stops the script on 'undefined' is not a function (evaluating 'collection.visibleCells()')
var target = UIATarget.localTarget();
var collection = target.frontMostApp().mainWindow().collectionViews()[0];
UIALogger.logMessage("Looking in collection: " + collection);
UIALogger.logMessage("Cells: " + collection.cells() + " length " + collection.cells().length);
UIALogger.logMessage("Visible cells: " + collection.visibleCells());
The code above returns the right UICollectionView, second log line prints:
Cells: [object UIAElementArray] length 12
although I have 100 items in the collection view, and third log line crashes script.
Is this a documentation/UIACollectionView bug?
Any ideas how can I tell the automation to scroll until it sees a cell with the name "My cell"?
I've tried using someCell.scrollToVisible, but I need to have the cell to do that, and I don't since I can't get it from cells.
EDIT:
As suggested by Jonathan I've implemented a scroll-till-found function.
it's a bit implementation specific, so you'll probably need to tweak isCellWithName.
I'm also looking to add a break in case we didn't find the needed cell in the while loop, if anyone has ideas, feel free to edit this.
function isCellWithName(cell, name) {
return (cell.staticTexts()[0].name() == name);
}
function getCellWithName(array, name) {
for (var i = 0; i < array.length; i++) {
if (isCellWithName(array[i], name)) {
return array[i];
}
}
return false;
}
function scrollToName(collection, name) {
var found = getCellWithName(collection.cells(), name);
while (found === false) {
collection.dragInsideWithOptions({startOffset:{x:0.2, y:0.99}, endOffset:{x:0.2, y:0},duration:1.0});
found = getCellWithName(collection.cells(), name);
}
return found;
}
The documentation is apparently incorrect. There is no visibleCells() method on UIACollectionView. I figured this out by looping over all the collection view elements properties and printing out their names:
var target = UIATarget.localTarget();
var window = target.frontMostApp().mainWindow();
var collectionView = window.collectionViews()[0];
for (var i in collectionView) {
UIALogger.logMessage(i);
}
Table view elements, on the other hand, do list all the cells with the cells() method. I'm wondering if they choose not to do this because of the much more complicated nature of collection views. It could be very expensive to actually fetch all the collection view cells, build their representations and frames, and return the elements if you had a lot of them. That's what UI Automation does when it asks table views for all the cells. They have to all be instantiated and calculated in order to get the element representations.
But, to answer your larger question, how to scroll to a specific cell. Can you consistently scroll it into view with a swipe gesture? It's not the most convenient way to do it and we're "spoiled" by the ability to scroll to non-visible elements with table views. But from a user behavior testing standpoint, swiping a certain amount is what the user would have to do anyway. Could the test be structured to reflect this and would it address your need?
I couldn't get the the #marmor dragInsideWithOptions() bit to work in a generic fashion. Instead, I'm using the collectionView's value() function to get an index of the current page vs. last page, as in "page 3 of 11". Then I use collectionView's scrollUp() and scrollDown() methods to walk through the pages until we find what we're after. I wrote an extension for TuneUp's uiautomation-ext.js that seem to do the trick, and more:
function animationDelay() {
UIATarget.localTarget().delay(.2);
}
extend(UIACollectionView.prototype, {
/**
* Apple's bug in UIACollectionView.cells() -- only returns *visible* cells
*/
pageCount: function() {
var pageStatus = this.value();
var words = pageStatus.split(" ");
var lastPage = words[3];
return lastPage;
},
currentPage: function() {
var pageStatus = this.value();
var words = pageStatus.split(" ");
var currentPage = words[1];
//var lastPage = words[3];
return currentPage;
},
scrollToTop: function() {
var current = this.currentPage();
while (current != 1) {
this.scrollUp();
animationDelay();
current = this.currentPage();
}
},
scrollToBottom: function() {
var current = this.currentPage();
var lastPage = this.pageCount();
while (current != lastPage) {
this.scrollDown();
animationDelay();
current = this.currentPage();
}
},
cellCount: function() {
this.scrollToTop();
var current = this.currentPage();
var lastPage = this.pageCount();
var cellCount = this.cells().length;
while (current != lastPage) {
this.scrollDown();
animationDelay();
current = this.currentPage();
cellCount += this.cells().length;
}
return cellCount;
},
currentPageCellNamed: function(name) {
var array = this.cells();
for (var i = 0; i < array.length; i++) {
var cell = array[i];
if (cell.name() == name) {
return cell;
}
}
return false;
},
cellNamed: function(name) {
// for performance, look on the current page first
var foundCell = this.currentPageCellNamed(name);
if (foundCell != false) {
return foundCell;
}
if (this.currentPage() != 1) {
// scroll up and check out the first page before we iterate
this.scrollToTop();
foundCell = this.currentPageCellNamed(name);
if (foundCell != false) {
return foundCell;
}
}
var current = this.currentPage();
var lastPage = this.pageCount();
while (current != lastPage) {
this.scrollDown();
animationDelay();
current = this.currentPage();
foundCell = this.currentPageCellNamed(name);
if (foundCell != false) {
return foundCell;
}
}
return false;
},
/**
* Asserts that this collection view has a cell with the name (accessibility identifier)
* matching the given +name+ argument.
*/
assertCellNamed: function(name) {
assertNotNull(this.cellNamed(name), "No collection cell found named '" + name + "'");
}
});
I have a Google Calendar for a school website I'm working on and am using the Google API to display the next five calendar events. One problem is that the time displays on a 24 hour clock instead of AM and PM, but that's not my main problem. The main problem is that while the events display the correct time on the website, when you click on the event to view it in the calendar event view, it will only display GMT time instead of Eastern Time. While logged into the Google account, the events display the right time zone, but whenever you view it while not logged in, it defaults to GMT.
I have tried changing it to another time zone and change it back, didn't fix it.
I also made sure all settings in both the calendar and the account were set to Eastern time zone, at least everywhere I could find it.
I've seen a lot of people with similar problems on Google sites using the ical or other feeds, but I haven't seen anyone with the problem using a code similar to mine.
The website is live: http://fletcheracademy.com. And here is the main javascript code that pulls it.
There's probably some details I'm missing, let me know if there's anything else you need to know. Thanks so much!
<script type="text/javascript">
google.load("gdata", "2.x");
function init() {
google.gdata.client.init(handleGDError);
loadDeveloperCalendar();
}
function loadDeveloperCalendar() {
loadCalendarByAddress('fletcheracademycalendar#gmail.com');
}
function padNumber(num) {
if (num <= 9) {
return "0" + num;
}
return num;
}
function loadCalendarByAddress(calendarAddress) {
var calendarUrl = 'https://www.google.com/calendar/feeds/' +
calendarAddress + '/public/full';
loadCalendar(calendarUrl);
}
function loadCalendar(calendarUrl) {
var service = new
google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
query.setOrderBy('starttime');
query.setSortOrder('ascending');
query.setFutureEvents(true);
query.setSingleEvents(true);
query.setMaxResults(5);
service.getEventsFeed(query, listEvents, handleGDError);
}
function handleGDError(e) {
document.getElementById('jsSourceFinal').setAttribute('style', 'display:none');
if (e instanceof Error) {
alert('Error at line ' + e.lineNumber + ' in ' + e.fileName + '\n' + 'Message: ' + e.message);
if (e.cause) {
var status = e.cause.status;
var statusText = e.cause.statusText;
alert('Root cause: HTTP error ' + status + ' with status text of: ' + statusText);
}
} else {
alert(e.toString());
}
}
function listEvents(feedRoot) {
var entries = feedRoot.feed.getEntries();
var eventDiv = document.getElementById('events');
if (eventDiv.childNodes.length > 0) {
eventDiv.removeChild(eventDiv.childNodes[0]);
}
var ul = document.createElement('ul');
//document.getElementById('calendarTitle').innerHTML =
// "Calendar: " + feedRoot.feed.title.$t;
var len = entries.length;
for (var i = 0; i < len; i++) {
var entry = entries[i];
var title = entry.getTitle().getText();
var startDateTime = null;
var startJSDate = null;
var times = entry.getTimes();
if (times.length > 0) {
startDateTime = times[0].getStartTime();
startJSDate = startDateTime.getDate();
}
var entryLinkHref = null;
if (entry.getHtmlLink() != null) {
entryLinkHref = entry.getHtmlLink().getHref();
}
var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
if (!startDateTime.isDateOnly()) {
dateString += " " + startJSDate.getHours() + ":" +
padNumber(startJSDate.getMinutes());
}
var li = document.createElement('li');
if (entryLinkHref != null) {
entryLink = document.createElement('a');
entryLink.setAttribute('href', entryLinkHref);
entryLink.appendChild(document.createTextNode(title));
li.appendChild(entryLink);
li.appendChild(document.createTextNode(' - ' + dateString));
} else {
li.appendChild(document.createTextNode(title + ' - ' + dateString));
}
ul.appendChild(li);
}
eventDiv.appendChild(ul);
}
google.setOnLoadCallback(init);
</script>
Try this!
Where you have:
var calendarUrl = 'https://www.google.com/calendar/feeds/' + calendarAddress + '/public/full';
you should add something like:
&ctz=Europe/Lisbon
Check here for the correct name of your timezone.