This commit is contained in:
Nikolay Diyanov 2015-01-19 19:41:28 +02:00
Коммит 51176af649
248 изменённых файлов: 26526 добавлений и 0 удалений

3
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,3 @@
*/bin
*/obj
*.user-settings.xml

Просмотреть файл

@ -0,0 +1,18 @@
# Windows files
*/**/Thumbs.db
# Mac OS files
*/**/.DS_Store
*/**/__MACOSX/**/*
# Visual Studio files
bin/**/*
obj/**/*
# Source control files
.gitignore
.git/**/*
# AppBuilder files
.abignore
.ab/**/*

Просмотреть файл

@ -0,0 +1,31 @@
{
"ProjectName": "Photo Album Native",
"ProjectGuid": "1517cf9c-0320-458e-b862-f60679add9f8",
"projectVersion": 1,
"AppIdentifier": "com.telerik.PhotoAlbumNative",
"DisplayName": "Photo Album Native",
"Author": "",
"Description": "Photo Album Native",
"BundleVersion": "1.0",
"AndroidVersionCode": "1",
"iOSDeviceFamily": [
"1",
"2"
],
"iOSBackgroundMode": [],
"ProjectTypeGuids": "{F0A65104-D4F4-4012-B799-F612D75820F6}",
"AndroidPermissions": [
"android.permission.ACCESS_COARSE_LOCATION",
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.ACCESS_LOCATION_EXTRA_COMMANDS",
"android.permission.ACCESS_MOCK_LOCATION"
],
"DeviceOrientations": [
"Portrait",
"Landscape"
],
"AndroidHardwareAcceleration": "false",
"iOSStatusBarStyle": "Default",
"Framework": "NativeScript",
"FrameworkVersion": "0.4.2"
}

Двоичные данные
Photo Album Native/App_Resources/Android/drawable-hdpi/icon.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 5.7 KiB

Двоичные данные
Photo Album Native/App_Resources/Android/drawable-ldpi/icon.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 2.6 KiB

Двоичные данные
Photo Album Native/App_Resources/Android/drawable-mdpi/icon.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.5 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.1 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-568h@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 8.8 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-667h.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.6 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-736h.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 5.6 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-Landscape-667h.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.8 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-Landscape-736h.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 6.9 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-Landscape.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 9.1 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-Landscape@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 26 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-Portrait.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 9.2 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default-Portrait@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 26 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 2.3 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Default@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 8.2 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Icon-40@3x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.2 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Icon-60@3x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 7.6 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Icon-Small-50.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.5 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Icon-Small-50@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 8.7 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Icon-Small.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 1.7 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/Icon-Small@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.4 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-40.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 2.6 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-40@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 6.5 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-60.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.4 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-60@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 11 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-72.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 5.7 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-72@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 13 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-76.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 6.0 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon-76@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 14 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 4.2 KiB

Двоичные данные
Photo Album Native/App_Resources/iOS/icon@2x.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 9.8 KiB

Просмотреть файл

@ -0,0 +1,3 @@
var application = require("application");
application.mainModule = "app/main";
application.start();

1
Photo Album Native/app/bootstrap.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
require("./");

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,5 @@
Button {
background-color: gray;
font-size: 20;
color: #3BB9FF;
}

Просмотреть файл

@ -0,0 +1,117 @@
//var pageModule = require("ui/page");
var modelModule = require("./view-model");
var model = new modelModule.PhotoAlbumModel();
//var buttonModule = require("ui/button");
//var gridModule = require("ui/panels/grid-panel");
//var listViewModule = require("ui/list-view");
//var enums = require("ui/enums");
//var imageModule = require("ui/image");
function onPageLoaded(args) {
var page = args.object;
page.bindingContext = model;
}
// function listViewItemLoading(args) {
// var image = args.view._children[0];
// image.source = args.object.items.getItem(args.index);
// }
function buttonClick(args) {
model.tapAction();
}
exports.buttonClick = buttonClick;
//exports.listViewItemLoading = listViewItemLoading;
exports.onPageLoaded = onPageLoaded;
// function createPage() {
// var model = new modelModule.PhotoAlbumModel();
// var button = new buttonModule.Button();
// // everlive.Files.create({
// // Filename: Math.random().toString(36).substring(2, 15) + ".jpg",
// // ContentType: "image/jpeg",
// // base64: model.items.getItem(0)
// // })
// var listView = new listViewModule.ListView();
// listView.on("itemLoading", function (args) {
// var imageGrid = args.view;
// var image;
// if (!imageGrid) {
// imageGrid = new gridModule.GridPanel();
// image = new imageModule.Image();
// //image = new labelModule.Label();
// image.stretch = enums.Stretch.aspectFill;
// imageGrid.addChild(image);
// args.view = imageGrid;
// } else {
// image = imageGrid._children[0];
// }
// image.source = args.object.items.getItem(args.index);
// });
// listView.bind({
// sourceProperty: "items",
// targetProperty: "items",
// twoWay: true
// }, model);
// button.bind({
// sourceProperty: "message",
// targetProperty: "text"
// }, model);
// button.on("click", function () {
// model.tapAction();
// });
// var gridPanel = new gridModule.GridPanel();
// gridPanel.addChild(listView);
// gridPanel.addChild(button);
// // Specify in which column button should be placed.
// gridModule.GridPanel.setColumn(listView, 0);
// gridModule.GridPanel.setColumn(button, 0);
// // Specify in which row button should be placed.
// gridModule.GridPanel.setRow(listView, 0);
// gridModule.GridPanel.setRow(button, 1);
// // Create GridLength object with star size (take remaining space)
// var starGridLength = new gridModule.GridLength(1, gridModule.GridUnitType.star);
// // Create GridLength object with auto size (size to content)
// var autoGridLength = gridModule.GridLength.auto;
// // Create RowDefiniton object and set its height to auto width.
// var firstRowDefinition = new gridModule.RowDefinition();
// firstRowDefinition.height = starGridLength;
// // Create RowDefiniton object and set its height to star width.
// var secondRowDefinition = new gridModule.RowDefinition();
// secondRowDefinition.height = autoGridLength;
// // Add rowDefiniton objects to gridPanel.
// gridPanel.addRowDefinition(firstRowDefinition);
// gridPanel.addRowDefinition(secondRowDefinition);
// // Create and return the page.
// var mainPage = new pageModule.Page();
// //mainPage.content = gridPanel;
// mainPage.css = "button { font-size: 20; color: #3BB9FF; background-color: gray }";
// return mainPage;
// }
// exports.createPage = createPage;

Просмотреть файл

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Page loaded="onPageLoaded">
<GridPanel>
<GridPanel.rowDefinitions>
<RowDefinition height="*" />
<RowDefinition height="auto" />
</GridPanel.rowDefinitions>
<ListView items="{{ photoItems }}" row="0">
<ListView.itemTemplate>
<GridPanel>
<Image source="{{ photoItemImage }}" row="0"/>
</GridPanel>
</ListView.itemTemplate>
</ListView>
<Button text="{{ message }}" click="buttonClick" row="1"/>
</GridPanel>
</Page>

Просмотреть файл

@ -0,0 +1,6 @@
{
"name": "tns-samples-photo-album-native",
"main": "app.js",
"version": "0.5.0",
"description": "Nativescript Photo Album Application"
}

Двоичные данные
Photo Album Native/app/res/01.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 118 KiB

Двоичные данные
Photo Album Native/app/res/02.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 121 KiB

Двоичные данные
Photo Album Native/app/res/03.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 93 KiB

Двоичные данные
Photo Album Native/app/res/04.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 142 KiB

Двоичные данные
Photo Album Native/app/res/05.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 156 KiB

Двоичные данные
Photo Album Native/app/res/06.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 115 KiB

Двоичные данные
Photo Album Native/app/res/07.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 107 KiB

Двоичные данные
Photo Album Native/app/res/08.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 129 KiB

Просмотреть файл

@ -0,0 +1,112 @@
var observable = require("data/observable");
var imageSourceModule = require("image-source");
var fileSystemModule = require("file-system");
var observableArrayModule = require("data/observable-array");
var backendServices = require('./everlive.all');
var everlive = new backendServices("YOUR KEY");
var __extends = this.__extends || function (d, b) {
for (var p in b)
if (b.hasOwnProperty(p)) d[p] = b[p];
function __() {
this.constructor = d;
}
__.prototype = b.prototype;
d.prototype = new __();
};
var array = new observableArrayModule.ObservableArray();
var directory = "/res/";
function imageFromSource(data) {
return imageSourceModule.fromFile(fileSystemModule.path.join(__dirname, directory + data));
};
var item1 = {
photoItemImage: imageFromSource("01.jpg")
};
var item2 = {
photoItemImage: imageFromSource("02.jpg")
};
var item3 = {
photoItemImage: imageFromSource("03.jpg")
};
var item4 = {
photoItemImage: imageFromSource("04.jpg")
};
var item5 = {
photoItemImage: imageFromSource("05.jpg")
};
var item6 = {
photoItemImage: imageFromSource("06.jpg")
};
array.push([item1, item2, item3, item4, item5, item6]);
var item7 = {
photoItemImage: imageFromSource("07.jpg")
};
var item8 = {
photoItemImage: imageFromSource("08.jpg")
};
var PhotoAlbumModel = (function (_super) {
__extends(PhotoAlbumModel, _super);
function PhotoAlbumModel() {
_super.call(this);
this.set("message", "Add new images");
}
Object.defineProperty(PhotoAlbumModel.prototype, "photoItems", {
get: function () {
return array;
},
enumerable: true,
configurable: true
});
PhotoAlbumModel.prototype.tapAction = function () {
array.push(item7);
array.push(item8);
for (i = 0; i < array.length; i++) {
var file = {
"Filename": Math.random().toString(36).substring(2, 15) + ".jpg",
"ContentType": "image/png",
"base64": array.getItem(i).photoItemImage.toBase64String(1, 100)
};
everlive.Files.create(file,
function (data) {
},
function (error) {
});
}
//var locationModule = require("location");
// locationModule.getLocation({ desiredAccuracy: 3, maximumAge: 20000, minimumUpdateTime: 5000, updateDistance: 0 })
// locationModule.getLocation({ desiredAccuracy: 3, maximumAge: 20000, minimumUpdateTime: 5000, updateDistance: 0}).then(function(location) {
// this.set("message", "Images added. Total images: " + location.longitude + " ");
// }, function(error){
// this.set("message", "Imges added. Total images: " + error.message);
// });
//var locationModule = require("location/location-manager");
//this.set("message", locationModule.LocationManager.isEnabled() + "");
//this.set("message", "Images added. Total images: " + array.length);
};
return PhotoAlbumModel;
})(observable.Observable);
exports.PhotoAlbumModel = PhotoAlbumModel;

Просмотреть файл

@ -0,0 +1,9 @@
require("globals");
exports.onUncaughtError = undefined;
exports.onLaunch = undefined;
exports.onSuspend = undefined;
exports.onResume = undefined;
exports.onExit = undefined;
exports.onLowMemory = undefined;
exports.android = undefined;
exports.ios = undefined;

Просмотреть файл

@ -0,0 +1,128 @@
var appModule = require("application/application-common");
var frame = require("ui/frame");
var types = require("utils/types");
require("utils/module-merge").merge(appModule, exports);
var callbacks = android.app.Application.ActivityLifecycleCallbacks;
exports.mainModule;
var initEvents = function () {
var androidApp = exports.android;
var lifecycleCallbacks = new callbacks({
onActivityCreated: function (activity, bundle) {
if (!androidApp.startActivity) {
androidApp.startActivity = activity;
if (androidApp.onActivityCreated) {
androidApp.onActivityCreated(activity, bundle);
}
}
androidApp.currentContext = activity;
},
onActivityDestroyed: function (activity) {
if (activity === androidApp.foregroundActivity) {
androidApp.foregroundActivity = undefined;
}
if (activity === androidApp.currentContext) {
androidApp.currentContext = undefined;
}
if (activity === androidApp.startActivity) {
if (exports.onExit) {
exports.onExit();
}
}
if (androidApp.onActivityDestroyed) {
androidApp.onActivityDestroyed(activity);
}
gc();
},
onActivityPaused: function (activity) {
if (activity === androidApp.foregroundActivity) {
if (exports.onSuspend) {
exports.onSuspend();
}
}
if (androidApp.onActivityPaused) {
androidApp.onActivityPaused(activity);
}
},
onActivityResumed: function (activity) {
if (activity === androidApp.foregroundActivity) {
if (exports.onResume) {
exports.onResume();
}
}
if (androidApp.onActivityResumed) {
androidApp.onActivityResumed(activity);
}
},
onActivitySaveInstanceState: function (activity, bundle) {
if (androidApp.onSaveActivityState) {
androidApp.onSaveActivityState(activity, bundle);
}
},
onActivityStarted: function (activity) {
androidApp.foregroundActivity = activity;
if (androidApp.onActivityStarted) {
androidApp.onActivityStarted(activity);
}
},
onActivityStopped: function (activity) {
if (androidApp.onActivityStopped) {
androidApp.onActivityStopped(activity);
}
}
});
return lifecycleCallbacks;
};
app.init({
getActivity: function (intent) {
return exports.android.getActivity(intent);
},
onCreate: function () {
var androidApp = new AndroidApplication(this);
exports.android = androidApp;
androidApp.init();
}
});
var AndroidApplication = (function () {
function AndroidApplication(nativeApp) {
this.nativeApp = nativeApp;
this.packageName = nativeApp.getPackageName();
this.context = nativeApp.getApplicationContext();
}
AndroidApplication.prototype.getActivity = function (intent) {
if (intent && intent.Action === android.content.Intent.ACTION_MAIN) {
if (exports.onLaunch) {
exports.onLaunch(intent);
}
}
var topFrame = frame.topmost();
if (!topFrame) {
if (exports.mainModule) {
topFrame = new frame.Frame();
topFrame.navigate(exports.mainModule);
}
else {
throw new Error("A Frame must be used to navigate to a Page.");
}
}
return topFrame.android.onActivityRequested(intent);
};
AndroidApplication.prototype.init = function () {
this._eventsToken = initEvents();
this.nativeApp.registerActivityLifecycleCallbacks(this._eventsToken);
this.context = this.nativeApp.getApplicationContext();
};
return AndroidApplication;
})();
global.__onUncaughtError = function (error) {
if (!types.isFunction(exports.onUncaughtError)) {
return;
}
var nsError = {
message: error.message,
name: error.name,
nativeError: error.nativeException
};
exports.onUncaughtError(nsError);
};
exports.start = function () {
};

Просмотреть файл

@ -0,0 +1,139 @@
var appModule = require("application/application-common");
var frame = require("ui/frame");
var geometry = require("utils/geometry");
var utils = require("utils/utils");
var types = require("utils/types");
require("utils/module-merge").merge(appModule, exports);
exports.mainModule;
var RootWindow = (function () {
function RootWindow() {
var WindowClass = UIWindow.extend({
layoutSubviews: function () {
this.rootWindow.layoutSubviews();
}
});
this._uiWindow = new WindowClass(UIScreen.mainScreen().bounds);
this._uiWindow.autoresizesSubviews = false;
this._uiWindow.autoresizingMask = UIViewAutoresizing.UIViewAutoresizingNone;
this._uiWindow.rootWindow = this;
}
Object.defineProperty(RootWindow.prototype, "uiWindow", {
get: function () {
return this._uiWindow;
},
enumerable: true,
configurable: true
});
RootWindow.prototype.layoutSubviews = function () {
if (!this._frame) {
return;
}
var statusFrame = UIApplication.sharedApplication().statusBarFrame;
var statusBarHeight = 0;
try {
statusBarHeight = Math.min(statusFrame.size.width, statusFrame.size.height);
}
catch (ex) {
console.log("exception: " + ex);
}
var isLandscape = utils.ios.isLandscape();
var iOSMajorVersion = utils.ios.MajorVersion;
if (isLandscape && iOSMajorVersion > 7) {
statusBarHeight = 0;
}
var deviceFrame = UIScreen.mainScreen().bounds;
var size = deviceFrame.size;
var width = size.width;
var height = size.height;
if (iOSMajorVersion < 8 && isLandscape) {
width = size.height;
height = size.width;
}
var origin = deviceFrame.origin;
var bounds = new geometry.Rect(origin.x, origin.y + statusBarHeight, width, height - statusBarHeight);
this._frame.measure(bounds.size);
this._frame.arrange(bounds);
this._frame._updateLayout();
};
return RootWindow;
})();
var iOSApplication = (function () {
function iOSApplication() {
this.nativeApp = UIApplication.sharedApplication();
}
iOSApplication.prototype.init = function () {
UIResponder.extend({
applicationDidFinishLaunchingWithOptions: function () {
var rootWindow = new RootWindow();
var window = rootWindow.uiWindow;
this.window = window;
this.window.backgroundColor = UIColor.whiteColor();
if (exports.onLaunch) {
exports.onLaunch();
}
var topFrame = frame.topmost();
if (!topFrame) {
if (exports.mainModule) {
topFrame = new frame.Frame();
topFrame.navigate(exports.mainModule);
}
else {
return;
}
}
rootWindow._frame = topFrame;
this.window.rootViewController = topFrame.ios.controller;
this.window.makeKeyAndVisible();
return true;
},
applicationDidBecomeActive: function (application) {
if (exports.onResume) {
exports.onResume();
}
},
applicationWillResignActive: function (application) {
},
applicationDidEnterBackground: function (application) {
if (exports.onSuspend) {
exports.onSuspend();
}
},
applicationWillEnterForeground: function (application) {
},
applicationWillTerminate: function (application) {
if (exports.onExit) {
exports.onExit();
}
},
applicationDidReceiveMemoryWarning: function (application) {
if (exports.onLowMemory) {
exports.onLowMemory();
}
},
applicationOpenURLSourceApplicationAnnotation: function (application, url, annotation) {
var dictionary = new NSMutableDictionary();
dictionary.setObjectForKey(url, "TLKApplicationOpenURL");
dictionary.setObjectForKey(application, "TLKApplication");
NSNotificationCenter.defaultCenter().postNotificationNameObjectUserInfo("com.telerik.TLKApplicationOpenURL", null, dictionary);
}
}, {
name: "TNSAppDelegate",
protocols: [UIApplicationDelegate]
});
};
return iOSApplication;
})();
var app = new iOSApplication();
exports.ios = app;
app.init();
exports.start = function () {
try {
UIApplicationMain(0, null, null, "TNSAppDelegate");
}
catch (error) {
if (!types.isFunction(exports.onUncaughtError)) {
return;
}
exports.onUncaughtError(error);
}
};

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "application",
"main" : "application.js" }

Просмотреть файл

@ -0,0 +1,140 @@
var types = require("utils/types");
var knownColors = require("color/known-colors");
var AMP = "#";
var Color = (function () {
function Color() {
if (arguments.length === 1) {
var arg = arguments[0];
if (types.isString(arg)) {
if (knownColors.isKnownName(arg)) {
this._hex = knownColors.getKnownColor(arg);
this._name = arg;
}
else {
this._hex = arg;
}
this._argb = this._argbFromString(this._hex);
}
else if (types.isNumber(arg)) {
this._argb = arg;
}
else {
throw new Error("Expected 1 or 4 constructor parameters.");
}
this._parseComponents();
if (!this._hex) {
this._hex = this._buildHex();
}
}
else if (arguments.length === 4) {
this._a = arguments[0];
this._r = arguments[1];
this._g = arguments[2];
this._b = arguments[3];
this._buildArgb();
this._hex = this._buildHex();
}
else {
throw new Error("Expected 1 or 4 constructor parameters.");
}
}
Object.defineProperty(Color.prototype, "a", {
get: function () {
return this._a;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "r", {
get: function () {
return this._r;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "g", {
get: function () {
return this._g;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "b", {
get: function () {
return this._b;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "argb", {
get: function () {
return this._argb;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "hex", {
get: function () {
return this._hex;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "name", {
get: function () {
return this._name;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "ios", {
get: function () {
return undefined;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "android", {
get: function () {
return undefined;
},
enumerable: true,
configurable: true
});
Color.prototype._argbFromString = function (hex) {
return undefined;
};
Color.prototype.equals = function (value) {
return this.argb === value.argb;
};
Color.equals = function (value1, value2) {
if (!value1 || !value2) {
return false;
}
return value1.equals(value2);
};
Color.prototype._buildHex = function () {
return AMP + this._componentToHex(this._a) + this._componentToHex(this._r) + this._componentToHex(this._g) + this._componentToHex(this._b);
};
Color.prototype._componentToHex = function (component) {
var hex = component.toString(16);
if (hex.length === 1) {
hex = "0" + hex;
}
return hex;
};
Color.prototype._parseComponents = function () {
if (!this._argb) {
throw new Error("Missing the ARGB numeric value");
}
this._a = (this._argb >> 24) & 255;
this._r = (this._argb >> 16) & 255;
this._g = (this._argb >> 8) & 255;
this._b = this._argb & 255;
};
Color.prototype._buildArgb = function () {
this._argb = (this._a << 24) | (this._r << 16) | (this._g << 8) | this._b;
};
return Color;
})();
exports.Color = Color;

Просмотреть файл

@ -0,0 +1,25 @@
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var common = require("color/color-common");
var Color = (function (_super) {
__extends(Color, _super);
function Color() {
_super.apply(this, arguments);
}
Object.defineProperty(Color.prototype, "android", {
get: function () {
return this.argb;
},
enumerable: true,
configurable: true
});
Color.prototype._argbFromString = function (hex) {
return android.graphics.Color.parseColor(hex);
};
return Color;
})(common.Color);
exports.Color = Color;

Просмотреть файл

@ -0,0 +1,36 @@
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var common = require("color/color-common");
var AMP = "#";
var Color = (function (_super) {
__extends(Color, _super);
function Color() {
_super.apply(this, arguments);
}
Object.defineProperty(Color.prototype, "ios", {
get: function () {
if (!this._ios) {
this._ios = UIColor.alloc().initWithRedGreenBlueAlpha(this.r / 255, this.g / 255, this.b / 255, this.a / 255);
}
return this._ios;
},
enumerable: true,
configurable: true
});
Color.prototype._argbFromString = function (hex) {
if (hex.charAt(0) === AMP) {
hex = hex.substr(1);
}
var intVal = parseInt(hex, 16);
if (hex.length === 6) {
intVal |= 255 << 24;
}
return intVal;
};
return Color;
})(common.Color);
exports.Color = Color;

Просмотреть файл

@ -0,0 +1,165 @@
exports.AliceBlue = "#F0F8FF";
exports.AntiqueWhite = "#FAEBD7";
exports.Aqua = "#00FFFF";
exports.Aquamarine = "#7FFFD4";
exports.Azure = "#F0FFFF";
exports.Beige = "#F5F5DC";
exports.Bisque = "#FFE4C4";
exports.Black = "#000000";
exports.BlanchedAlmond = "#FFEBCD";
exports.Blue = "#0000FF";
exports.BlueViolet = "#8A2BE2";
exports.Brown = "#A52A2A";
exports.BurlyWood = "#DEB887";
exports.CadetBlue = "#5F9EA0";
exports.Chartreuse = "#7FFF00";
exports.Chocolate = "#D2691E";
exports.Coral = "#FF7F50";
exports.CornflowerBlue = "#6495ED";
exports.Cornsilk = "#FFF8DC";
exports.Crimson = "#DC143C";
exports.Cyan = "#00FFFF";
exports.DarkBlue = "#00008B";
exports.DarkCyan = "#008B8B";
exports.DarkGoldenRod = "#B8860B";
exports.DarkGray = "#A9A9A9";
exports.DarkGreen = "#006400";
exports.DarkKhaki = "#BDB76B";
exports.DarkMagenta = "#8B008B";
exports.DarkOliveGreen = "#556B2F";
exports.DarkOrange = "#FF8C00";
exports.DarkOrchid = "#9932CC";
exports.DarkRed = "#8B0000";
exports.DarkSalmon = "#E9967A";
exports.DarkSeaGreen = "#8FBC8F";
exports.DarkSlateBlue = "#483D8B";
exports.DarkSlateGray = "#2F4F4F";
exports.DarkTurquoise = "#00CED1";
exports.DarkViolet = "#9400D3";
exports.DeepPink = "#FF1493";
exports.DeepSkyBlue = "#00BFFF";
exports.DimGray = "#696969";
exports.DodgerBlue = "#1E90FF";
exports.FireBrick = "#B22222";
exports.FloralWhite = "#FFFAF0";
exports.ForestGreen = "#228B22";
exports.Fuchsia = "#FF00FF";
exports.Gainsboro = "#DCDCDC";
exports.GhostWhite = "#F8F8FF";
exports.Gold = "#FFD700";
exports.GoldenRod = "#DAA520";
exports.Gray = "#808080";
exports.Green = "#008000";
exports.GreenYellow = "#ADFF2F";
exports.HoneyDew = "#F0FFF0";
exports.HotPink = "#FF69B4";
exports.IndianRed = "#CD5C5C";
exports.Indigo = "#4B0082";
exports.Ivory = "#FFFFF0";
exports.Khaki = "#F0E68C";
exports.Lavender = "#E6E6FA";
exports.LavenderBlush = "#FFF0F5";
exports.LawnGreen = "#7CFC00";
exports.LemonChiffon = "#FFFACD";
exports.LightBlue = "#ADD8E6";
exports.LightCoral = "#F08080";
exports.LightCyan = "#E0FFFF";
exports.LightGoldenRodYellow = "#FAFAD2";
exports.LightGray = "#D3D3D3";
exports.LightGreen = "#90EE90";
exports.LightPink = "#FFB6C1";
exports.LightSalmon = "#FFA07A";
exports.LightSeaGreen = "#20B2AA";
exports.LightSkyBlue = "#87CEFA";
exports.LightSlateGray = "#778899";
exports.LightSteelBlue = "#B0C4DE";
exports.LightYellow = "#FFFFE0";
exports.Lime = "#00FF00";
exports.LimeGreen = "#32CD32";
exports.Linen = "#FAF0E6";
exports.Magenta = "#FF00FF";
exports.Maroon = "#800000";
exports.MediumAquaMarine = "#66CDAA";
exports.MediumBlue = "#0000CD";
exports.MediumOrchid = "#BA55D3";
exports.MediumPurple = "#9370DB";
exports.MediumSeaGreen = "#3CB371";
exports.MediumSlateBlue = "#7B68EE";
exports.MediumSpringGreen = "#00FA9A";
exports.MediumTurquoise = "#48D1CC";
exports.MediumVioletRed = "#C71585";
exports.MidnightBlue = "#191970";
exports.MintCream = "#F5FFFA";
exports.MistyRose = "#FFE4E1";
exports.Moccasin = "#FFE4B5";
exports.NavajoWhite = "#FFDEAD";
exports.Navy = "#000080";
exports.OldLace = "#FDF5E6";
exports.Olive = "#808000";
exports.OliveDrab = "#6B8E23";
exports.Orange = "#FFA500";
exports.OrangeRed = "#FF4500";
exports.Orchid = "#DA70D6";
exports.PaleGoldenRod = "#EEE8AA";
exports.PaleGreen = "#98FB98";
exports.PaleTurquoise = "#AFEEEE";
exports.PaleVioletRed = "#DB7093";
exports.PapayaWhip = "#FFEFD5";
exports.PeachPuff = "#FFDAB9";
exports.Peru = "#CD853F";
exports.Pink = "#FFC0CB";
exports.Plum = "#DDA0DD";
exports.PowderBlue = "#B0E0E6";
exports.Purple = "#800080";
exports.Red = "#FF0000";
exports.RosyBrown = "#BC8F8F";
exports.RoyalBlue = "#4169E1";
exports.SaddleBrown = "#8B4513";
exports.Salmon = "#FA8072";
exports.SandyBrown = "#F4A460";
exports.SeaGreen = "#2E8B57";
exports.SeaShell = "#FFF5EE";
exports.Sienna = "#A0522D";
exports.Silver = "#C0C0C0";
exports.SkyBlue = "#87CEEB";
exports.SlateBlue = "#6A5ACD";
exports.SlateGray = "#708090";
exports.Snow = "#FFFAFA";
exports.SpringGreen = "#00FF7F";
exports.SteelBlue = "#4682B4";
exports.Tan = "#D2B48C";
exports.Teal = "#008080";
exports.Thistle = "#D8BFD8";
exports.Tomato = "#FF6347";
exports.Turquoise = "#40E0D0";
exports.Violet = "#EE82EE";
exports.Wheat = "#F5DEB3";
exports.White = "#FFFFFF";
exports.WhiteSmoke = "#F5F5F5";
exports.Yellow = "#FFFF00";
exports.YellowGreen = "#9ACD32";
var _allColors = {};
(function () {
var name;
var underscore = "_";
for (var p in exports) {
name = p;
if (name.charAt(0) !== underscore) {
_allColors[name.toLowerCase()] = exports[p];
}
}
})();
function isKnownName(name) {
if (!name) {
return undefined;
}
return name.toLowerCase() in _allColors;
}
exports.isKnownName = isKnownName;
function getKnownColor(name) {
if (!name) {
return undefined;
}
return _allColors[name.toLowerCase()];
}
exports.getKnownColor = getKnownColor;

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "color",
"main" : "color.js" }

Просмотреть файл

@ -0,0 +1,16 @@
var TAG = 'JS';
exports.helper_log = function (message) {
android.util.Log.v(TAG, message);
};
exports.info = function (message) {
android.util.Log.i(TAG, message);
};
exports.error = function (message) {
android.util.Log.e(TAG, message);
};
exports.warn = function (message) {
android.util.Log.w(TAG, message);
};
exports.timeMillis = function () {
return java.lang.System.nanoTime() / 1000000;
};

Просмотреть файл

@ -0,0 +1,17 @@
function nslog(prefix, message) {
}
exports.helper_log = function (message) {
nslog('log', message);
};
exports.info = function (message) {
nslog('info', message);
};
exports.error = function (message) {
nslog('error', message);
};
exports.warn = function (message) {
nslog('warning', message);
};
exports.timeMillis = function () {
return CACurrentMediaTime() * 1000;
};

Просмотреть файл

@ -0,0 +1,266 @@
var helperModule = require("console/console-native");
var Console = (function () {
function Console() {
this.dir = this.dump;
this._timers = {};
}
Console.prototype.sprintf = function (message) {
var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
var a = arguments;
var i = 0;
var format = a[i++];
var pad = function (str, len, chr, leftJustify) {
if (!chr) {
chr = ' ';
}
var padding = (str.length >= len) ? '' : new Array(1 + len - str.length >>> 0).join(chr);
return leftJustify ? str + padding : padding + str;
};
var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
var diff = minWidth - value.length;
if (diff > 0) {
if (leftJustify || !zeroPad) {
value = pad(value, minWidth, customPadChar, leftJustify);
}
else {
value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
}
}
return value;
};
var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
var number = value >>> 0;
prefix = prefix && number && {
'2': '0b',
'8': '0',
'16': '0x'
}[base] || '';
value = prefix + pad(number.toString(base), precision || 0, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad);
};
var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
if (precision != null) {
value = value.slice(0, precision);
}
return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
};
var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
var number, prefix, method, textTransform, value;
if (substring === '%%') {
return '%';
}
var leftJustify = false;
var positivePrefix = '';
var zeroPad = false;
var prefixBaseX = false;
var customPadChar = ' ';
var flagsl = flags.length;
for (var j = 0; flags && j < flagsl; j++) {
switch (flags.charAt(j)) {
case ' ':
positivePrefix = ' ';
break;
case '+':
positivePrefix = '+';
break;
case '-':
leftJustify = true;
break;
case "'":
customPadChar = flags.charAt(j + 1);
break;
case '0':
zeroPad = true;
customPadChar = '0';
break;
case '#':
prefixBaseX = true;
break;
}
}
if (!minWidth) {
minWidth = 0;
}
else if (minWidth === '*') {
minWidth = +a[i++];
}
else if (minWidth.charAt(0) === '*') {
minWidth = +a[minWidth.slice(1, -1)];
}
else {
minWidth = +minWidth;
}
if (minWidth < 0) {
minWidth = -minWidth;
leftJustify = true;
}
if (!isFinite(minWidth)) {
throw new Error('sprintf: (minimum-)width must be finite');
}
if (!precision) {
precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type === 'd') ? 0 : undefined;
}
else if (precision === '*') {
precision = +a[i++];
}
else if (precision.charAt(0) === '*') {
precision = +a[precision.slice(1, -1)];
}
else {
precision = +precision;
}
value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
switch (type) {
case 's':
return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
case 'c':
return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
case 'b':
return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
case 'o':
return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
case 'x':
return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
case 'X':
return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
case 'u':
return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
case 'i':
case 'd':
number = +value || 0;
number = Math.round(number - number % 1);
prefix = number < 0 ? '-' : positivePrefix;
value = prefix + pad(String(Math.abs(number)), precision, '0', false);
return justify(value, prefix, leftJustify, minWidth, zeroPad);
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
number = +value;
prefix = number < 0 ? '-' : positivePrefix;
method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
value = prefix + Math.abs(number)[method](precision);
return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
default:
return substring;
}
};
return format.replace(regex, doFormat);
};
Console.prototype.formatParams = function (message) {
if (arguments.length <= 1) {
return message ? message : '';
}
var res = this.sprintf.apply(this, arguments);
if (res === message) {
var args = Array.prototype.slice.call(arguments);
return args.join(' ');
}
return res;
};
Console.prototype.time = function (reportName) {
var name = reportName ? '__' + reportName : '__internal_console_time__';
if (('undefined' === typeof (this._timers[name])) || (this._timers.hasOwnProperty(name))) {
this._timers[name] = helperModule.timeMillis();
}
else {
this.warn('invalid name for timer console.time(' + reportName + ')');
}
};
Console.prototype.timeEnd = function (reportName) {
var name = reportName ? '__' + reportName : '__internal_console_time__';
if (this._timers.hasOwnProperty(name)) {
var val = this._timers[name];
if (val) {
var time = helperModule.timeMillis();
this.info('console.time(' + reportName + '): %.6f ms', (time - val));
this._timers[name] = undefined;
}
else {
this.warn('undefined console.time(' + reportName + ')');
}
}
};
Console.prototype.assert = function (test, message) {
var formatParams = [];
for (var _i = 2; _i < arguments.length; _i++) {
formatParams[_i - 2] = arguments[_i];
}
if (!test) {
Array.prototype.shift.apply(arguments);
helperModule.error(this.formatParams.apply(this, arguments));
}
};
Console.prototype.info = function (message) {
var formatParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
formatParams[_i - 1] = arguments[_i];
}
helperModule.info(this.formatParams.apply(this, arguments));
};
Console.prototype.warn = function (message) {
var formatParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
formatParams[_i - 1] = arguments[_i];
}
helperModule.warn(this.formatParams.apply(this, arguments));
};
Console.prototype.error = function (message) {
var formatParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
formatParams[_i - 1] = arguments[_i];
}
helperModule.error(this.formatParams.apply(this, arguments));
};
Console.prototype.log = function (message) {
var formatParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
formatParams[_i - 1] = arguments[_i];
}
helperModule.helper_log(this.formatParams.apply(this, arguments));
};
Console.prototype.trace = function () {
var callstack = [];
var currentFunction = arguments.callee.caller;
while (currentFunction) {
var fn = currentFunction.toString();
var fname = fn.substring(fn.indexOf('function') + 8, fn.indexOf('{')).trim() || 'anonymous';
if ('()' === fname) {
fname = 'anonymous';
}
callstack.push(fname);
currentFunction = currentFunction.caller;
this.log(callstack.join('\n'));
}
};
Console.prototype.dump = function (obj) {
if (null == obj) {
this.log("=== dump(): object is 'null' ===");
return;
}
if ("undefined" === typeof obj) {
this.log("=== dump(): object is 'undefined' ===");
return;
}
var result = ['=== dump(): dumping members ==='];
result.push(JSON.stringify(obj, null, 4));
result.push('=== dump(): dumping function names ===');
for (var id in obj) {
try {
if (typeof (obj[id]) === 'function') {
result.push(id + '()');
}
}
catch (err) {
result.push(id + ': inaccessible');
}
}
result.push('=== dump(): finished ===');
this.log(result.join('\n'));
};
return Console;
})();
exports.Console = Console;

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "console",
"main" : "console.js" }

Просмотреть файл

@ -0,0 +1,187 @@
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var observable = require("data/observable");
var ChangeType = (function () {
function ChangeType() {
}
ChangeType.Add = "add";
ChangeType.Delete = "delete";
ChangeType.Update = "update";
ChangeType.Splice = "splice";
return ChangeType;
})();
exports.ChangeType = ChangeType;
var CHANGE = "change";
var knownEvents;
(function (knownEvents) {
knownEvents.change = CHANGE;
})(knownEvents = exports.knownEvents || (exports.knownEvents = {}));
var ObservableArray = (function (_super) {
__extends(ObservableArray, _super);
function ObservableArray() {
_super.call(this);
if (arguments.length === 1 && Array.isArray(arguments[0])) {
this._array = arguments[0].slice();
}
else {
this._array = Array.apply(null, arguments);
}
this._addArgs = {
eventName: CHANGE,
object: this,
action: ChangeType.Add,
index: null,
removed: new Array(),
addedCount: 1
};
this._deleteArgs = {
eventName: CHANGE,
object: this,
action: ChangeType.Delete,
index: null,
removed: null,
addedCount: 0
};
}
ObservableArray.prototype.getItem = function (index) {
return this._array[index];
};
ObservableArray.prototype.setItem = function (index, value) {
this._array[index] = value;
this.notify({
eventName: CHANGE,
object: this,
action: ChangeType.Update,
index: index,
removed: new Array(1),
addedCount: 1
});
};
Object.defineProperty(ObservableArray.prototype, "length", {
get: function () {
return this._array.length;
},
enumerable: true,
configurable: true
});
ObservableArray.prototype.toString = function () {
return this._array.toString();
};
ObservableArray.prototype.toLocaleString = function () {
return this._array.toLocaleString();
};
ObservableArray.prototype.concat = function () {
this._addArgs.index = this._array.length;
var result = this._array.concat.apply(this._array, arguments);
this._addArgs.addedCount = result.length - this._array.length;
this.notify(this._addArgs);
return result;
};
ObservableArray.prototype.join = function (separator) {
return this._array.join(separator);
};
ObservableArray.prototype.pop = function () {
this._deleteArgs.index = this._array.length - 1;
var result = this._array.pop();
this._deleteArgs.removed = [result];
this.notify(this._deleteArgs);
return result;
};
ObservableArray.prototype.push = function () {
this._addArgs.index = this._array.length;
if (arguments.length === 1 && Array.isArray(arguments[0])) {
var source = arguments[0];
for (var i = 0, l = source.length; i < l; i++) {
this._array.push(source[i]);
}
}
else {
this._array.push.apply(this._array, arguments);
}
this._addArgs.addedCount = this._array.length - this._addArgs.index;
this.notify(this._addArgs);
return this._array.length;
};
ObservableArray.prototype.reverse = function () {
return this._array.reverse();
};
ObservableArray.prototype.shift = function () {
var result = this._array.shift();
this._deleteArgs.index = 0;
this._deleteArgs.removed = [result];
this.notify(this._deleteArgs);
return result;
};
ObservableArray.prototype.slice = function (start, end) {
return this._array.slice(start, end);
};
ObservableArray.prototype.sort = function (compareFn) {
return this._array.sort(compareFn);
};
ObservableArray.prototype.splice = function (start, deleteCount) {
var length = this._array.length;
var result = this._array.splice.apply(this._array, arguments);
this.notify({
eventName: CHANGE,
object: this,
action: ChangeType.Splice,
index: start,
removed: result,
addedCount: this._array.length > length ? this._array.length - length : 0
});
return result;
};
ObservableArray.prototype.unshift = function () {
var length = this._array.length;
var result = this._array.unshift.apply(this._array, arguments);
this._addArgs.index = 0;
this._addArgs.addedCount = result - length;
this.notify(this._addArgs);
return result;
};
ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
var index = fromIndex ? fromIndex : 0;
for (var i = index, l = this._array.length; i < l; i++) {
if (this._array[i] === searchElement) {
return i;
}
}
return -1;
};
ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
var index = fromIndex ? fromIndex : this._array.length - 1;
for (var i = index; i >= 0; i--) {
if (this._array[i] === searchElement) {
return i;
}
}
return -1;
};
ObservableArray.prototype.every = function (callbackfn, thisArg) {
return this._array.every(callbackfn, thisArg);
};
ObservableArray.prototype.some = function (callbackfn, thisArg) {
return this._array.some(callbackfn, thisArg);
};
ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
this._array.forEach(callbackfn, thisArg);
};
ObservableArray.prototype.map = function (callbackfn, thisArg) {
return this._array.map(callbackfn, thisArg);
};
ObservableArray.prototype.filter = function (callbackfn, thisArg) {
return this._array.filter(callbackfn, thisArg);
};
ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
return this._array.reduce(callbackfn, initialValue);
};
ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
return this._array.reduceRight(callbackfn, initialValue);
};
return ObservableArray;
})(observable.Observable);
exports.ObservableArray = ObservableArray;

Просмотреть файл

@ -0,0 +1,4 @@
{
"name" : "observable-array",
"main" : "observable-array.js"
}

Просмотреть файл

@ -0,0 +1,137 @@
var types = require("utils/types");
var knownEvents;
(function (knownEvents) {
knownEvents.propertyChange = "propertyChange";
})(knownEvents = exports.knownEvents || (exports.knownEvents = {}));
var Observable = (function () {
function Observable() {
this._observers = {};
}
Object.defineProperty(Observable.prototype, "typeName", {
get: function () {
return types.getClass(this);
},
enumerable: true,
configurable: true
});
Observable.prototype.on = function (eventNames, callback, thisArg) {
this.addEventListener(eventNames, callback);
};
Observable.prototype.off = function (eventNames, callback) {
this.removeEventListener(eventNames, callback);
};
Observable.prototype.addEventListener = function (eventNames, callback, thisArg) {
types.verifyCallback(callback);
var events = eventNames.split(",");
for (var i = 0, l = events.length; i < l; i++) {
var event = events[i].trim();
var list = this._getEventList(event, true);
list.push({
callback: callback,
thisArg: thisArg
});
}
};
Observable.prototype.removeEventListener = function (eventNames, callback, thisArg) {
var events = eventNames.split(",");
for (var i = 0, l = events.length; i < l; i++) {
var event = events[i].trim();
if (callback) {
var list = this._getEventList(event, false);
if (list) {
var index = this._indexOfListener(list, callback, thisArg);
if (index >= 0) {
list.splice(index, 1);
}
if (list.length === 0) {
delete this._observers[event];
}
}
}
else {
this._observers[event] = undefined;
delete this._observers[event];
}
}
};
Observable.prototype.set = function (name, value) {
if (this[name] === value) {
return;
}
var data = this._createPropertyChangeData(name, value);
this._setCore(data);
this.notify(data);
};
Observable.prototype.get = function (name) {
return this[name];
};
Observable.prototype._setCore = function (data) {
this[data.propertyName] = data.value;
};
Observable.prototype.notify = function (data) {
var observers = this._getEventList(data.eventName);
if (!observers) {
return;
}
var i;
var entry;
for (i = 0; i < observers.length; i++) {
entry = observers[i];
if (entry.thisArg) {
entry.callback.apply(entry.thisArg, [data]);
}
else {
entry.callback(data);
}
}
};
Observable.prototype.hasListeners = function (eventName) {
return eventName in this._observers;
};
Observable.prototype._createPropertyChangeData = function (name, value) {
return {
eventName: knownEvents.propertyChange,
propertyName: name,
object: this,
value: value
};
};
Observable.prototype._emit = function (eventNames) {
var events = eventNames.split(",");
for (var i = 0, l = events.length; i < l; i++) {
var event = events[i].trim();
this.notify({ eventName: event, object: this });
}
};
Observable.prototype._getEventList = function (eventName, createIfNeeded) {
if (!eventName) {
throw new TypeError("EventName must be valid string.");
}
var list = this._observers[eventName];
if (!list && createIfNeeded) {
list = [];
this._observers[eventName] = list;
}
return list;
};
Observable.prototype._indexOfListener = function (list, callback, thisArg) {
var i;
var entry;
for (i = 0; i < list.length; i++) {
entry = list[i];
if (thisArg) {
if (entry.callback === callback && entry.thisArg === thisArg) {
return i;
}
}
else {
if (entry.callback === callback) {
return i;
}
}
}
return -1;
};
return Observable;
})();
exports.Observable = Observable;

Просмотреть файл

@ -0,0 +1,4 @@
{
"name" : "observable",
"main" : "observable.js"
}

Просмотреть файл

@ -0,0 +1,4 @@
{
"name" : "virtual-array",
"main" : "virtual-array.js"
}

Просмотреть файл

@ -0,0 +1,149 @@
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var observable = require("data/observable");
var types = require("utils/types");
var CHANGE = "change", UPDATE = "update", DELETE = "delete", ADD = "add";
var knownEvents;
(function (knownEvents) {
knownEvents.itemsLoading = "itemsLoading";
knownEvents.change = "change";
})(knownEvents = exports.knownEvents || (exports.knownEvents = {}));
var ChangeType = (function () {
function ChangeType() {
}
ChangeType.Add = "add";
ChangeType.Delete = "delete";
ChangeType.Update = "update";
ChangeType.Splice = "splice";
return ChangeType;
})();
exports.ChangeType = ChangeType;
var VirtualArray = (function (_super) {
__extends(VirtualArray, _super);
function VirtualArray(length) {
if (length === void 0) { length = 0; }
_super.call(this);
this._length = length;
this._cache = {};
this._requestedIndexes = [];
this._loadedIndexes = [];
}
Object.defineProperty(VirtualArray.prototype, "length", {
get: function () {
return this._length;
},
set: function (value) {
if (this._length !== value) {
var index = this._length;
var count = value - this._length;
this._length = value;
this.notify({
eventName: CHANGE,
object: this,
action: count > 0 ? ADD : DELETE,
index: index,
removed: new Array(count < 0 ? Math.abs(count) : 0),
addedCount: count > 0 ? count : 0
});
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(VirtualArray.prototype, "loadSize", {
get: function () {
return this._loadSize;
},
set: function (value) {
this._loadSize = value;
},
enumerable: true,
configurable: true
});
VirtualArray.prototype.getItem = function (index) {
var item = this._cache[index];
if (types.isUndefined(item)) {
if (index >= 0 && index < this.length && this._requestedIndexes.indexOf(index) < 0 && this._loadedIndexes.indexOf(index) < 0) {
this.requestItems(index);
}
}
return item;
};
VirtualArray.prototype.setItem = function (index, value) {
if (this._cache[index] !== value) {
this.load(index, [value]);
}
};
VirtualArray.prototype.load = function (index, items) {
var i;
for (i = 0; i < items.length; i++) {
var itemIndex = index + i;
this._cache[itemIndex] = items[i];
this._requestedIndexes.splice(this._requestedIndexes.indexOf(itemIndex), 1);
if (this._loadedIndexes.indexOf(itemIndex) < 0) {
this._loadedIndexes.push(itemIndex);
}
}
if (this._requestedIndexes.length > 0) {
for (i = 0; i < this.loadSize - items.length; i++) {
this._requestedIndexes.splice(this._requestedIndexes.indexOf(index + i), 1);
}
}
this.notify({
eventName: CHANGE,
object: this,
action: UPDATE,
index: index,
removed: new Array(items.length),
addedCount: items.length
});
};
VirtualArray.prototype.requestItems = function (index) {
var indexesToLoad = [];
var pageIndex = this._loadSize > 0 ? this._loadSize * Math.floor(index / this._loadSize) : index;
var count = 0;
var start = -1;
for (var i = 0; i < this.loadSize; i++) {
var itemIndex = pageIndex + i;
if (itemIndex >= this._length) {
break;
}
if (this._loadedIndexes.indexOf(itemIndex) < 0) {
if (start < 0) {
start = itemIndex;
}
indexesToLoad.push(itemIndex);
if (this._requestedIndexes.indexOf(itemIndex) < 0) {
this._requestedIndexes.push(itemIndex);
}
count++;
}
else {
if (count > 0) {
this.notify({
eventName: knownEvents.itemsLoading,
object: this,
index: start,
count: count
});
}
start = -1;
count = 0;
}
}
if (start >= 0 && count > 0) {
this.notify({
eventName: knownEvents.itemsLoading,
object: this,
index: start,
count: count
});
}
};
return VirtualArray;
})(observable.Observable);
exports.VirtualArray = VirtualArray;

Просмотреть файл

@ -0,0 +1,361 @@
var appModule = require("application");
var textModule = require("text");
var types = require("utils/types");
var FileSystemAccess = (function () {
function FileSystemAccess() {
this._pathSeparator = java.io.File.separator.toString();
}
FileSystemAccess.prototype.getLastModified = function (path) {
var javaFile = new java.io.File(path);
return new Date(javaFile.lastModified());
};
FileSystemAccess.prototype.getParent = function (path, onError) {
try {
var javaFile = new java.io.File(path);
var parent = javaFile.getParentFile();
return { path: parent.getAbsolutePath(), name: parent.getName() };
}
catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
};
FileSystemAccess.prototype.getFile = function (path, onError) {
return this.ensureFile(new java.io.File(path), false, onError);
};
FileSystemAccess.prototype.getFolder = function (path, onError) {
var javaFile = new java.io.File(path);
var dirInfo = this.ensureFile(javaFile, true, onError);
if (!dirInfo) {
return undefined;
}
return { path: dirInfo.path, name: dirInfo.name };
};
FileSystemAccess.prototype.eachEntity = function (path, onEntity, onError) {
if (!onEntity) {
return;
}
this.enumEntities(path, onEntity, onError);
};
FileSystemAccess.prototype.getEntities = function (path, onSuccess, onError) {
if (!onSuccess) {
return;
}
var fileInfos = new Array();
var onEntity = function (entity) {
fileInfos.push(entity);
return true;
};
var errorOccurred;
var localError = function (error) {
if (onError) {
onError(error);
}
errorOccurred = true;
};
this.enumEntities(path, onEntity, localError);
if (!errorOccurred) {
onSuccess(fileInfos);
}
};
FileSystemAccess.prototype.fileExists = function (path) {
var file = new java.io.File(path);
return file.exists();
};
FileSystemAccess.prototype.folderExists = function (path) {
var file = new java.io.File(path);
var exists = file.exists();
var dir = file.isDirectory();
return exists && dir;
};
FileSystemAccess.prototype.deleteFile = function (path, onSuccess, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.isFile()) {
if (onError) {
onError({ message: "The specified parameter is not a File entity." });
}
return;
}
if (!javaFile.delete()) {
if (onError) {
onError({ message: "File deletion failed" });
}
}
else if (onSuccess) {
onSuccess();
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.deleteFolder = function (path, isKnown, onSuccess, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError({ message: "The specified parameter is not a Folder entity." });
}
return;
}
this.deleteFolderContent(javaFile);
if (!isKnown) {
if (javaFile.delete()) {
if (onSuccess) {
onSuccess();
}
}
else {
if (onError) {
onError({ message: "Folder deletion failed." });
}
}
}
else {
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.emptyFolder = function (path, onSuccess, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError({ message: "The specified parameter is not a Folder entity." });
}
return;
}
this.deleteFolderContent(javaFile);
if (onSuccess) {
onSuccess();
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.rename = function (path, newPath, onSuccess, onError) {
var javaFile = new java.io.File(path);
if (!javaFile.exists()) {
if (onError) {
onError(new Error("The file to rename does not exist"));
}
return;
}
var newFile = new java.io.File(newPath);
if (newFile.exists()) {
if (onError) {
onError(new Error("A file with the same name already exists."));
}
return;
}
if (!javaFile.renameTo(newFile)) {
if (onError) {
onError(new Error("Failed to rename file '" + path + "' to '" + newPath + "'"));
}
return;
}
if (onSuccess) {
onSuccess();
}
};
FileSystemAccess.prototype.getDocumentsFolderPath = function () {
var context = appModule.android.context;
var dir = context.getFilesDir();
return dir.getAbsolutePath();
};
FileSystemAccess.prototype.getTempFolderPath = function () {
var context = appModule.android.context;
var dir = context.getCacheDir();
return dir.getAbsolutePath();
};
FileSystemAccess.prototype.readText = function (path, onSuccess, onError, encoding) {
try {
var javaFile = new java.io.File(path);
var stream = new java.io.FileInputStream(javaFile);
var actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
var reader = new java.io.InputStreamReader(stream, actualEncoding);
var bufferedReader = new java.io.BufferedReader(reader);
var line = undefined;
var result = "";
while (true) {
line = bufferedReader.readLine();
if (types.isUndefined(line)) {
break;
}
if (result.length > 0) {
result += "\n";
}
result += line;
}
if (actualEncoding === textModule.encoding.UTF_8) {
result = FileSystemAccess._removeUtf8Bom(result);
}
bufferedReader.close();
if (onSuccess) {
onSuccess(result);
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess._removeUtf8Bom = function (s) {
if (s.charCodeAt(0) === 0xFEFF) {
s = s.slice(1);
}
return s;
};
FileSystemAccess.prototype.writeText = function (path, content, onSuccess, onError, encoding) {
try {
var javaFile = new java.io.File(path);
var stream = new java.io.FileOutputStream(javaFile);
var actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
var writer = new java.io.OutputStreamWriter(stream, actualEncoding);
writer.write(content);
writer.close();
if (onSuccess) {
onSuccess();
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.deleteFolderContent = function (file) {
var filesList = file.listFiles();
var i, childFile, success = false;
for (i = 0; i < filesList.length; i++) {
childFile = filesList[i];
if (childFile.getCanonicalFile().isDirectory()) {
success = this.deleteFolderContent(childFile);
if (!success) {
break;
}
}
success = childFile.delete();
}
return success;
};
FileSystemAccess.prototype.ensureFile = function (javaFile, isFolder, onError) {
try {
if (!javaFile.exists()) {
var created;
if (isFolder) {
created = javaFile.mkdirs();
}
else {
created = javaFile.createNewFile();
}
if (!created) {
if (onError) {
onError("Failed to create new java File for path " + javaFile.getAbsolutePath());
}
return undefined;
}
else {
javaFile.setReadable(true);
javaFile.setWritable(true);
}
}
var path = javaFile.getAbsolutePath();
return { path: path, name: javaFile.getName(), extension: this.getFileExtension(path) };
}
catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
};
FileSystemAccess.prototype.getFileExtension = function (path) {
var dotIndex = path.lastIndexOf(".");
if (dotIndex && dotIndex >= 0 && dotIndex < path.length) {
return path.substring(dotIndex);
}
return "";
};
FileSystemAccess.prototype.enumEntities = function (path, callback, onError) {
try {
var javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError("There is no folder existing at path " + path);
}
return;
}
var filesList = javaFile.listFiles();
var length = filesList.length;
var i;
var info;
var retVal;
for (i = 0; i < length; i++) {
javaFile = filesList[i];
info = {
path: javaFile.getAbsolutePath(),
name: javaFile.getName()
};
if (javaFile.isFile()) {
info.extension = this.getFileExtension(info.path);
}
retVal = callback(info);
if (retVal === false) {
break;
}
}
}
catch (exception) {
if (onError) {
onError(exception);
}
}
};
FileSystemAccess.prototype.getPathSeparator = function () {
return this._pathSeparator;
};
FileSystemAccess.prototype.normalizePath = function (path) {
var file = new java.io.File(path);
return file.getAbsolutePath();
};
FileSystemAccess.prototype.joinPath = function (left, right) {
var file1 = new java.io.File(left);
var file2 = new java.io.File(file1, right);
return file2.getAbsolutePath();
};
FileSystemAccess.prototype.joinPaths = function (paths) {
if (!paths || paths.length === 0) {
return "";
}
if (paths.length === 1) {
return paths[0];
}
var i, result = paths[0];
for (i = 1; i < paths.length; i++) {
result = this.joinPath(result, paths[i]);
}
return this.normalizePath(result);
};
return FileSystemAccess;
})();
exports.FileSystemAccess = FileSystemAccess;

Просмотреть файл

@ -0,0 +1,291 @@
var utilsModule = require("utils/utils");
var textModule = require("text");
var FileSystemAccess = (function () {
function FileSystemAccess() {
this.keyModificationTime = "NSFileModificationDate";
this.documentDir = 9;
this.cachesDir = 13;
this.userDomain = 1;
}
FileSystemAccess.prototype.getLastModified = function (path) {
var fileManager = NSFileManager.defaultManager();
var attributes = fileManager.attributesOfItemAtPathError(path, null);
if (attributes) {
var date = attributes.objectForKey(this.keyModificationTime);
var interval = date.timeIntervalSince1970();
return new Date(interval * 1000);
}
else {
return new Date();
}
};
FileSystemAccess.prototype.getParent = function (path, onError) {
try {
var fileManager = NSFileManager.defaultManager();
var nsString = NSString.alloc().initWithString(path);
var parentPath = nsString.stringByDeletingLastPathComponent;
var name = fileManager.displayNameAtPath(parentPath);
return {
path: parentPath.toString(),
name: name
};
}
catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
};
FileSystemAccess.prototype.getFile = function (path, onError) {
try {
var fileManager = NSFileManager.defaultManager();
var exists = fileManager.fileExistsAtPath(path);
if (!exists) {
if (!fileManager.createFileAtPathContentsAttributes(path, null, null)) {
if (onError) {
onError(new Error("Failed to create folder at path '" + path + "'"));
}
return undefined;
}
}
var fileName = fileManager.displayNameAtPath(path);
return {
path: path,
name: fileName,
extension: this.getFileExtension(path)
};
}
catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
};
FileSystemAccess.prototype.getFolder = function (path, onError) {
try {
var fileManager = NSFileManager.defaultManager();
var exists = this.folderExists(path);
if (!exists) {
if (!fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(path, true, null, null)) {
if (onError) {
onError(new Error("Failed to create folder at path '" + path + "'"));
}
return undefined;
}
}
var dirName = fileManager.displayNameAtPath(path);
return {
path: path,
name: dirName
};
}
catch (ex) {
if (onError) {
onError(new Error("Failed to create folder at path '" + path + "'"));
}
return undefined;
}
};
FileSystemAccess.prototype.eachEntity = function (path, onEntity, onError) {
if (!onEntity) {
return;
}
this.enumEntities(path, onEntity, onError);
};
FileSystemAccess.prototype.getEntities = function (path, onSuccess, onError) {
if (!onSuccess) {
return;
}
var fileInfos = new Array();
var onEntity = function (entity) {
fileInfos.push(entity);
return true;
};
var errorOccurred;
var localError = function (error) {
if (onError) {
onError(error);
}
errorOccurred = true;
};
this.enumEntities(path, onEntity, localError);
if (!errorOccurred) {
onSuccess(fileInfos);
}
};
FileSystemAccess.prototype.fileExists = function (path) {
var fileManager = NSFileManager.defaultManager();
return fileManager.fileExistsAtPath(path);
};
FileSystemAccess.prototype.folderExists = function (path) {
var fileManager = NSFileManager.defaultManager();
var outVal = new interop.Reference();
var exists = fileManager.fileExistsAtPathIsDirectory(path, outVal);
return exists && outVal.value > 0;
};
FileSystemAccess.prototype.concatPath = function (left, right) {
var nsArray = utilsModule.ios.collections.jsArrayToNSArray([left, right]);
var nsString = NSString.pathWithComponents(nsArray);
return nsString.toString();
};
FileSystemAccess.prototype.deleteFile = function (path, onSuccess, onError) {
this.deleteEntity(path, onSuccess, onError);
};
FileSystemAccess.prototype.deleteFolder = function (path, isKnown, onSuccess, onError) {
this.deleteEntity(path, onSuccess, onError);
};
FileSystemAccess.prototype.emptyFolder = function (path, onSuccess, onError) {
var fileManager = NSFileManager.defaultManager();
var filesEnum = function (files) {
var i;
for (i = 0; i < files.length; i++) {
if (!fileManager.removeItemAtPathError(files[i].path, null)) {
if (onError) {
onError(new Error("Failed to empty folder '" + path + "'"));
}
return;
}
}
if (onSuccess) {
onSuccess();
}
};
this.getEntities(path, filesEnum, onError);
};
FileSystemAccess.prototype.rename = function (path, newPath, onSuccess, onError) {
var fileManager = NSFileManager.defaultManager();
if (!fileManager.moveItemAtPathToPathError(path, newPath, null)) {
if (onError) {
onError(new Error("Failed to rename '" + path + "' to '" + newPath + "'"));
}
}
else if (onSuccess) {
onSuccess();
}
};
FileSystemAccess.prototype.getDocumentsFolderPath = function () {
return this.getKnownPath(this.documentDir);
};
FileSystemAccess.prototype.getTempFolderPath = function () {
return this.getKnownPath(this.cachesDir);
};
FileSystemAccess.prototype.readText = function (path, onSuccess, onError, encoding) {
var actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
var nsString = NSString.stringWithContentsOfFileEncodingError(path, actualEncoding, null);
if (!nsString) {
if (onError) {
onError(new Error("Failed to read file at path '" + path + "'"));
}
}
else if (onSuccess) {
onSuccess(nsString.toString());
}
};
FileSystemAccess.prototype.writeText = function (path, content, onSuccess, onError, encoding) {
var nsString = NSString.alloc().initWithString(content);
var actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
if (!nsString.writeToFileAtomicallyEncodingError(path, false, actualEncoding, null)) {
if (onError) {
onError(new Error("Failed to write to file '" + path + "'"));
}
}
else if (onSuccess) {
onSuccess();
}
};
FileSystemAccess.prototype.getKnownPath = function (folderType) {
var fileManager = NSFileManager.defaultManager();
var paths = fileManager.URLsForDirectoryInDomains(folderType, this.userDomain);
var url = paths.objectAtIndex(0);
return url.path;
};
FileSystemAccess.prototype.getFileExtension = function (path) {
var dotIndex = path.lastIndexOf(".");
if (dotIndex && dotIndex >= 0 && dotIndex < path.length) {
return path.substring(dotIndex);
}
return "";
};
FileSystemAccess.prototype.deleteEntity = function (path, onSuccess, onError) {
var fileManager = NSFileManager.defaultManager();
if (!fileManager.removeItemAtPathError(path, null)) {
if (onError) {
onError(new Error("Failed to delete file at path '" + path + "'"));
}
}
else {
if (onSuccess) {
onSuccess();
}
}
};
FileSystemAccess.prototype.enumEntities = function (path, callback, onError) {
try {
var fileManager = NSFileManager.defaultManager();
var files = fileManager.contentsOfDirectoryAtPathError(path, null);
if (!files) {
if (onError) {
onError(new Error("Failed to enum files for forlder '" + path + "'"));
}
return;
}
var file;
var i;
var info;
var retVal;
for (i = 0; i < files.count; i++) {
file = files.objectAtIndex(i);
info = {
path: this.concatPath(path, file),
name: file
};
if (!this.folderExists(file)) {
info.extension = this.getFileExtension(info.path);
}
retVal = callback(info);
if (retVal === false) {
break;
}
}
}
catch (ex) {
if (onError) {
onError(ex);
}
}
};
FileSystemAccess.prototype.getPathSeparator = function () {
return "/";
};
FileSystemAccess.prototype.normalizePath = function (path) {
var nsString = NSString.stringWithString(path);
var normalized = nsString.stringByStandardizingPath;
return normalized;
};
FileSystemAccess.prototype.joinPath = function (left, right) {
var nsString = NSString.stringWithString(left);
return nsString.stringByAppendingPathComponent(right);
};
FileSystemAccess.prototype.joinPaths = function (paths) {
if (!paths || paths.length === 0) {
return "";
}
var nsArray = NSMutableArray.alloc().initWithCapacity(paths.length);
var i;
for (i = 0; i < paths.length; i++) {
nsArray.addObject(paths[i]);
}
var nsString = NSString.stringWithString(NSString.pathWithComponents(nsArray));
return nsString.stringByStandardizingPath;
};
return FileSystemAccess;
})();
exports.FileSystemAccess = FileSystemAccess;

Просмотреть файл

@ -0,0 +1,370 @@
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var file_access_module = require("file-system/file-system-access");
var fileAccess;
var getFileAccess = function () {
if (!fileAccess) {
fileAccess = new file_access_module.FileSystemAccess();
}
return fileAccess;
};
var nameProperty = "_name";
var pathProperty = "_path";
var isKnownProperty = "_isKnown";
var fileLockedProperty = "_locked";
var extensionProperty = "_extension";
var lastModifiedProperty = "_lastModified";
var createFile = function (info) {
var file = new File();
file[pathProperty] = info.path;
file[nameProperty] = info.name;
file[extensionProperty] = info.extension;
return file;
};
var createFolder = function (info) {
var documents = knownFolders.documents();
if (info.path === documents.path) {
return documents;
}
var temp = knownFolders.temp();
if (info.path === temp.path) {
return temp;
}
var folder = new Folder();
folder[pathProperty] = info.path;
folder[nameProperty] = info.name;
return folder;
};
var FileSystemEntity = (function () {
function FileSystemEntity() {
}
Object.defineProperty(FileSystemEntity.prototype, "parent", {
get: function () {
var onError = function (error) {
throw error;
};
var folderInfo = getFileAccess().getParent(this.path, onError);
if (!folderInfo) {
return undefined;
}
return createFolder(folderInfo);
},
enumerable: true,
configurable: true
});
FileSystemEntity.prototype.remove = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var fileAccess = getFileAccess();
var localSucces = function () {
resolve();
};
var localError = function (error) {
reject(error);
};
if (_this instanceof File) {
fileAccess.deleteFile(_this.path, localSucces, localError);
}
else if (_this instanceof Folder) {
fileAccess.deleteFolder(_this.path, _this[isKnownProperty], localSucces, localError);
}
});
};
FileSystemEntity.prototype.rename = function (newName) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this instanceof Folder) {
if (_this[isKnownProperty]) {
reject(new Error("Cannot rename known folder."));
}
}
var parentFolder = _this.parent;
if (!parentFolder) {
reject(new Error("No parent folder."));
}
var fileAccess = getFileAccess();
var path = parentFolder.path;
var newPath = fileAccess.joinPath(path, newName);
var localSucceess = function () {
_this[pathProperty] = newPath;
_this[nameProperty] = newName;
if (_this instanceof File) {
_this[extensionProperty] = fileAccess.getFileExtension(newPath);
}
resolve();
};
var localError = function (error) {
reject(error);
};
fileAccess.rename(_this.path, newPath, localSucceess, localError);
});
};
Object.defineProperty(FileSystemEntity.prototype, "name", {
get: function () {
return this[nameProperty];
},
enumerable: true,
configurable: true
});
Object.defineProperty(FileSystemEntity.prototype, "path", {
get: function () {
return this[pathProperty];
},
enumerable: true,
configurable: true
});
Object.defineProperty(FileSystemEntity.prototype, "lastModified", {
get: function () {
var value = this[lastModifiedProperty];
if (!this[lastModifiedProperty]) {
value = this[lastModifiedProperty] = getFileAccess().getLastModified(this.path);
}
return value;
},
enumerable: true,
configurable: true
});
return FileSystemEntity;
})();
exports.FileSystemEntity = FileSystemEntity;
var File = (function (_super) {
__extends(File, _super);
function File() {
_super.apply(this, arguments);
}
File.fromPath = function (path) {
var onError = function (error) {
throw error;
};
var fileInfo = getFileAccess().getFile(path, onError);
if (!fileInfo) {
return undefined;
}
return createFile(fileInfo);
};
File.exists = function (path) {
return getFileAccess().fileExists(path);
};
Object.defineProperty(File.prototype, "extension", {
get: function () {
return this[extensionProperty];
},
enumerable: true,
configurable: true
});
Object.defineProperty(File.prototype, "isLocked", {
get: function () {
return this[fileLockedProperty];
},
enumerable: true,
configurable: true
});
File.prototype.readText = function (encoding) {
var _this = this;
this.checkAccess();
return new Promise(function (resolve, reject) {
_this[fileLockedProperty] = true;
var localSuccess = function (content) {
_this[fileLockedProperty] = false;
resolve(content);
};
var localError = function (error) {
_this[fileLockedProperty] = false;
reject(error);
};
getFileAccess().readText(_this.path, localSuccess, localError, encoding);
});
};
File.prototype.writeText = function (content, encoding) {
var _this = this;
this.checkAccess();
return new Promise(function (resolve, reject) {
_this[fileLockedProperty] = true;
var that = _this;
var localSuccess = function () {
that[fileLockedProperty] = false;
resolve();
};
var localError = function (error) {
that[fileLockedProperty] = false;
reject(error);
};
getFileAccess().writeText(_this.path, content, localSuccess, localError, encoding);
});
};
File.prototype.checkAccess = function () {
if (this.isLocked) {
throw new Error("Cannot access a locked file.");
}
};
return File;
})(FileSystemEntity);
exports.File = File;
var Folder = (function (_super) {
__extends(Folder, _super);
function Folder() {
_super.apply(this, arguments);
}
Folder.fromPath = function (path) {
var onError = function (error) {
throw error;
};
var folderInfo = getFileAccess().getFolder(path, onError);
if (!folderInfo) {
return undefined;
}
return createFolder(folderInfo);
};
Folder.exists = function (path) {
return getFileAccess().folderExists(path);
};
Folder.prototype.contains = function (name) {
var fileAccess = getFileAccess();
var path = fileAccess.joinPath(this.path, name);
if (fileAccess.fileExists(path)) {
return true;
}
return fileAccess.folderExists(path);
};
Folder.prototype.clear = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var onSuccess = function () {
resolve();
};
var onError = function (error) {
reject(error);
};
getFileAccess().emptyFolder(_this.path, onSuccess, onError);
});
};
Object.defineProperty(Folder.prototype, "isKnown", {
get: function () {
return this[isKnownProperty];
},
enumerable: true,
configurable: true
});
Folder.prototype.getFile = function (name) {
var fileAccess = getFileAccess();
var path = fileAccess.joinPath(this.path, name);
var onError = function (error) {
throw error;
};
var fileInfo = fileAccess.getFile(path, onError);
if (!fileInfo) {
return undefined;
}
return createFile(fileInfo);
};
Folder.prototype.getFolder = function (name) {
var fileAccess = getFileAccess();
var path = fileAccess.joinPath(this.path, name);
var onError = function (error) {
throw error;
};
var folderInfo = fileAccess.getFolder(path, onError);
if (!folderInfo) {
return undefined;
}
return createFolder(folderInfo);
};
Folder.prototype.getEntities = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var onSuccess = function (fileInfos) {
var entities = new Array();
var i;
for (i = 0; i < fileInfos.length; i++) {
if (fileInfos[i].extension) {
entities.push(createFile(fileInfos[i]));
}
else {
entities.push(createFolder(fileInfos[i]));
}
}
resolve(entities);
};
var onError = function (error) {
throw error;
};
getFileAccess().getEntities(_this.path, onSuccess, onError);
});
};
Folder.prototype.eachEntity = function (onEntity) {
if (!onEntity) {
return;
}
var onSuccess = function (fileInfo) {
var entity;
if (fileInfo.extension) {
entity = createFile(fileInfo);
}
else {
entity = createFolder(fileInfo);
}
return onEntity(entity);
};
var onError = function (error) {
throw error;
};
getFileAccess().eachEntity(this.path, onSuccess, onError);
};
return Folder;
})(FileSystemEntity);
exports.Folder = Folder;
var knownFolders;
(function (knownFolders) {
var _documents;
var _temp;
var _app;
knownFolders.documents = function () {
if (!_documents) {
var path = getFileAccess().getDocumentsFolderPath();
_documents = new Folder();
_documents[pathProperty] = path;
_documents[isKnownProperty] = true;
}
return _documents;
};
knownFolders.temp = function () {
if (!_temp) {
var path = getFileAccess().getTempFolderPath();
_temp = new Folder();
_temp[pathProperty] = path;
_temp[isKnownProperty] = true;
}
return _temp;
};
knownFolders.currentApp = function () {
if (!_app) {
var currentDir = __dirname;
var path = currentDir.substring(0, currentDir.indexOf("/tns_modules"));
_app = new Folder();
_app[pathProperty] = path;
_app[isKnownProperty] = true;
}
return _app;
};
})(knownFolders = exports.knownFolders || (exports.knownFolders = {}));
var path;
(function (_path) {
function normalize(path) {
return getFileAccess().normalizePath(path);
}
_path.normalize = normalize;
function join() {
var paths = [];
for (var _i = 0; _i < arguments.length; _i++) {
paths[_i - 0] = arguments[_i];
}
var fileAccess = getFileAccess();
return fileAccess.joinPaths(paths);
}
_path.join = join;
_path.separator = getFileAccess().getPathSeparator();
})(path = exports.path || (exports.path = {}));

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "file-system",
"main" : "file-system.js" }

Просмотреть файл

@ -0,0 +1,65 @@
var fpsNative = require("fps-meter/fps-native");
var callbacks = {}, idCounter = 0, _minFps = 1000, framesRendered = 0, frameStartTime = 0;
function doFrame(currentTimeMillis) {
var fps = 0;
if (frameStartTime > 0) {
var timeSpan = (currentTimeMillis - frameStartTime);
framesRendered++;
if (timeSpan > 1000) {
fps = framesRendered * 1000 / timeSpan;
if (fps < _minFps) {
_minFps = fps;
}
notify(fps);
frameStartTime = currentTimeMillis;
framesRendered = 0;
}
}
else {
frameStartTime = currentTimeMillis;
}
}
var native = new fpsNative.FPSCallback(doFrame);
function reset() {
_minFps = 1000;
frameStartTime = 0;
framesRendered = 0;
}
exports.reset = reset;
function running() {
return native.running;
}
exports.running = running;
function minFps() {
return _minFps;
}
exports.minFps = minFps;
function start() {
native.start();
}
exports.start = start;
function stop() {
native.stop();
reset();
}
exports.stop = stop;
function addCallback(callback) {
var id = idCounter;
callbacks[id] = callback;
idCounter++;
return id;
}
exports.addCallback = addCallback;
function removeCallback(id) {
if (id in callbacks) {
delete callbacks[id];
}
}
exports.removeCallback = removeCallback;
function notify(fps) {
var callback;
for (var id in callbacks) {
callback = callbacks[id];
callback(fps, _minFps);
}
}

Просмотреть файл

@ -0,0 +1,35 @@
var FPSCallback = (function () {
function FPSCallback(onFrame) {
var _this = this;
this.running = false;
this.onFrame = onFrame;
this.impl = new android.view.Choreographer.FrameCallback({
doFrame: function (nanos) {
_this.handleFrame(nanos);
}
});
}
FPSCallback.prototype.start = function () {
if (this.running) {
return;
}
android.view.Choreographer.getInstance().postFrameCallback(this.impl);
this.running = true;
};
FPSCallback.prototype.stop = function () {
if (!this.running) {
return;
}
android.view.Choreographer.getInstance().removeFrameCallback(this.impl);
this.running = false;
};
FPSCallback.prototype.handleFrame = function (nanos) {
if (!this.running) {
return;
}
this.onFrame(nanos / 1000000);
android.view.Choreographer.getInstance().postFrameCallback(this.impl);
};
return FPSCallback;
})();
exports.FPSCallback = FPSCallback;

Просмотреть файл

@ -0,0 +1,41 @@
var FrameHandlerClass = NSObject.extend({
handleFrame: function (sender) {
this["_owner"].handleFrame(sender);
}
}, {
exposedMethods: {
"handleFrame": "v@"
}
});
var FPSCallback = (function () {
function FPSCallback(onFrame) {
this.onFrame = onFrame;
this.impl = FrameHandlerClass.alloc();
this.impl["_owner"] = this;
this.displayLink = CADisplayLink.displayLinkWithTargetSelector(this.impl, "handleFrame");
this.displayLink.paused = true;
this.displayLink.addToRunLoopForMode(NSRunLoop.currentRunLoop(), NSDefaultRunLoopMode);
}
FPSCallback.prototype.start = function () {
if (this.running) {
return;
}
this.running = true;
this.displayLink.paused = false;
};
FPSCallback.prototype.stop = function () {
if (!this.running) {
return;
}
this.displayLink.paused = true;
this.running = false;
};
FPSCallback.prototype.handleFrame = function (sender) {
if (!this.running) {
return;
}
this.onFrame(sender.timestamp * 1000);
};
return FPSCallback;
})();
exports.FPSCallback = FPSCallback;

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "fps-meter",
"main" : "fps-meter.js" }

Просмотреть файл

@ -0,0 +1,10 @@
var types = require("utils/types");
var timer = require("timer");
var consoleModule = require("console");
global.setTimeout = timer.setTimeout;
global.clearTimeout = timer.clearTimeout;
global.setInterval = timer.setInterval;
global.clearInterval = timer.clearInterval;
if (types.isUndefined(global.NSObject)) {
global.console = new consoleModule.Console();
}

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "globals",
"main" : "globals.js" }

Просмотреть файл

@ -0,0 +1,85 @@
var imageSource = require("image-source");
var types = require("utils/types");
function request(options) {
return new Promise(function (resolve, reject) {
try {
var request = new com.koushikdutta.async.http.AsyncHttpRequest(java.net.URI.create(options.url), options.method);
if (options.headers) {
for (var key in options.headers) {
request.addHeader(key, options.headers[key]);
}
}
if (types.isNumber(options.timeout)) {
request.setTimeout(options.timeout);
}
if (types.isString(options.content)) {
var stringBody = com.koushikdutta.async.http.body.StringBody.extend({
getContentType: function () {
return null;
}
});
request.setBody(new stringBody(options.content));
}
else if (types.isDefined(options.content)) {
request.setBody(new com.koushikdutta.async.http.body.StreamBody(new java.io.ByteArrayInputStream(options.content), options.content.length));
}
var callback = new com.koushikdutta.async.http.callback.HttpConnectCallback({
onConnectCompleted: function (error, response) {
if (error) {
reject(new Error(error.toString()));
}
else {
var headers = {};
var rawHeaders = response.getHeaders().headers;
for (var i = 0, l = rawHeaders.length(); i < l; i++) {
var key = rawHeaders.getFieldName(i);
headers[key] = rawHeaders.getValue(i);
}
var outputStream = new java.io.ByteArrayOutputStream();
var dataCallback = new com.koushikdutta.async.callback.DataCallback({
onDataAvailable: function (emitter, byteBufferList) {
var bb = byteBufferList.getAll();
outputStream.write(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining());
}
});
response.setDataCallback(dataCallback);
var endCallback = new com.koushikdutta.async.callback.CompletedCallback({
onCompleted: function (error) {
resolve({
content: {
raw: outputStream,
toString: function () {
return outputStream.toString();
},
toJSON: function () {
return JSON.parse(outputStream.toString());
},
toImage: function () {
return new Promise(function (resolveImage, rejectImage) {
try {
var stream = new java.io.ByteArrayInputStream(outputStream.toByteArray());
resolveImage(imageSource.fromNativeSource(android.graphics.BitmapFactory.decodeStream(stream)));
}
catch (e) {
rejectImage(e);
}
});
}
},
statusCode: rawHeaders.getResponseCode(),
headers: headers
});
}
});
response.setEndCallback(endCallback);
}
}
});
com.koushikdutta.async.http.AsyncHttpClient.getDefaultInstance().execute(request, callback);
}
catch (ex) {
reject(ex);
}
});
}
exports.request = request;

Просмотреть файл

@ -0,0 +1,71 @@
var imageSource = require("image-source");
var types = require("utils/types");
var GET = "GET";
var USER_AGENT_HEADER = "User-Agent";
var USER_AGENT = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25";
function request(options) {
return new Promise(function (resolve, reject) {
try {
var sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration();
var queue = NSOperationQueue.mainQueue();
var session = NSURLSession.sessionWithConfigurationDelegateDelegateQueue(sessionConfig, null, queue);
var urlRequest = NSMutableURLRequest.requestWithURL(NSURL.URLWithString(options.url));
urlRequest.HTTPMethod = types.isDefined(options.method) ? options.method : GET;
urlRequest.setValueForHTTPHeaderField(USER_AGENT, USER_AGENT_HEADER);
if (options.headers) {
for (var header in options.headers) {
urlRequest.setValueForHTTPHeaderField(options.headers[header], header);
}
}
if (types.isNumber(options.timeout)) {
urlRequest.timeoutInterval = options.timeout * 1000;
}
if (types.isString(options.content)) {
urlRequest.HTTPBody = NSString.alloc().initWithString(options.content).dataUsingEncoding(4);
}
else if (types.isDefined(options.content)) {
urlRequest.HTTPBody = options.content;
}
var dataTask = session.dataTaskWithRequestCompletionHandler(urlRequest, function (data, response, error) {
if (error) {
reject(new Error(error.localizedDescription));
}
else {
var headers = {};
var headerFields = response.allHeaderFields;
var keys = headerFields.allKeys;
for (var i = 0, l = keys.count; i < l; i++) {
var key = keys.objectAtIndex(i);
headers[key] = headerFields.valueForKey(key);
}
resolve({
content: {
raw: data,
toString: function () {
return NSDataToString(data);
},
toJSON: function () {
return JSON.parse(NSDataToString(data));
},
toImage: function () {
return new Promise(function (resolveImage, reject) {
resolveImage(imageSource.fromData(data));
});
}
},
statusCode: response.statusCode,
headers: headers
});
}
});
dataTask.resume();
}
catch (ex) {
reject(ex);
}
});
}
exports.request = request;
function NSDataToString(data) {
return NSString.alloc().initWithDataEncoding(data, 4).toString();
}

Просмотреть файл

@ -0,0 +1,22 @@
var httpRequest = require("http/http-request");
require("utils/module-merge").merge(httpRequest, exports);
function getString(arg) {
return new Promise(function (resolve, reject) {
httpRequest.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg).then(function (r) { return resolve(r.content.toString()); }, function (e) { return reject(e); });
});
}
exports.getString = getString;
function getJSON(arg) {
return new Promise(function (resolve, reject) {
httpRequest.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg).then(function (r) { return resolve(r.content.toJSON()); }, function (e) { return reject(e); });
});
}
exports.getJSON = getJSON;
function getImage(arg) {
return new Promise(function (resolve, reject) {
httpRequest.request(typeof arg === "string" ? { url: arg, method: "GET" } : arg).then(function (r) {
r.content.toImage().then(function (source) { return resolve(source); });
}, function (e) { return reject(e); });
});
}
exports.getImage = getImage;

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "http",
"main" : "http.js" }

Просмотреть файл

@ -0,0 +1,56 @@
var appModule = require("application");
function fromResource(name) {
var androidApp = appModule.android;
var res = androidApp.context.getResources();
if (res) {
var identifier = res.getIdentifier(name, 'drawable', androidApp.packageName);
if (0 < identifier) {
return android.graphics.BitmapFactory.decodeResource(res, identifier);
}
}
return null;
}
exports.fromResource = fromResource;
function fromFile(path) {
return android.graphics.BitmapFactory.decodeFile(path, null);
}
exports.fromFile = fromFile;
function fromData(data) {
return android.graphics.BitmapFactory.decodeStream(data);
}
exports.fromData = fromData;
function saveToFile(instance, path, format, quality) {
if (quality === void 0) { quality = 100; }
if (!instance) {
return false;
}
var targetFormat = getTargetFromat(format);
var outputStream = new java.io.BufferedOutputStream(new java.io.FileOutputStream(path));
var res = instance.compress(targetFormat, quality, outputStream);
outputStream.close();
return res;
}
exports.saveToFile = saveToFile;
function toBase64String(instance, format, quality) {
if (quality === void 0) { quality = 100; }
if (!instance) {
return null;
;
}
var targetFormat = getTargetFromat(format);
var outputStream = new java.io.ByteArrayOutputStream();
var base64Stream = new android.util.Base64OutputStream(outputStream, android.util.Base64.NO_WRAP);
instance.compress(targetFormat, quality, base64Stream);
base64Stream.close();
outputStream.close();
return outputStream.toString();
}
exports.toBase64String = toBase64String;
function getTargetFromat(format) {
switch (format) {
case 1:
return android.graphics.Bitmap.CompressFormat.JPEG;
default:
return android.graphics.Bitmap.CompressFormat.PNG;
}
}

Просмотреть файл

@ -0,0 +1,44 @@
exports.fromResource = function (name) {
return UIImage.imageNamed(name);
};
exports.fromFile = function (path) {
return UIImage.imageWithContentsOfFile(path);
};
exports.fromData = function (data) {
return UIImage.imageWithData(data);
};
exports.saveToFile = function (instance, path, format, quality) {
var res = false;
if (!instance) {
return res;
}
var data = getImageData(instance, format, quality);
if (data) {
res = data.writeToFileAtomically(path, true);
}
return res;
};
function toBase64String(instance, format, quality) {
var res = null;
if (!instance) {
return res;
}
var data = getImageData(instance, format, quality);
if (data) {
res = data.base64Encoding();
}
return res;
}
exports.toBase64String = toBase64String;
function getImageData(instance, format, quality) {
var data = null;
switch (format) {
case 0:
data = UIImagePNGRepresentation(instance);
break;
case 1:
data = UIImageJPEGRepresentation(instance, ('undefined' === typeof quality) ? 1.0 : quality);
break;
}
return data;
}

Просмотреть файл

@ -0,0 +1,107 @@
var native = require("image-source/image-source-native");
var utils = require("utils/utils");
var http = require("http");
(function (ImageFormat) {
ImageFormat[ImageFormat["PNG"] = 0] = "PNG";
ImageFormat[ImageFormat["JPEG"] = 1] = "JPEG";
})(exports.ImageFormat || (exports.ImageFormat = {}));
var ImageFormat = exports.ImageFormat;
var ImageSource = (function () {
function ImageSource() {
this.setNativeInstance(null);
}
ImageSource.prototype.loadFromResource = function (name) {
var nativeInstance = native.fromResource(name);
this.setNativeInstance(nativeInstance);
return nativeInstance != null;
};
ImageSource.prototype.loadFromFile = function (path) {
var nativeInstance = native.fromFile(path);
this.setNativeInstance(nativeInstance);
return (nativeInstance != null);
};
ImageSource.prototype.loadFromData = function (data) {
var nativeInstance = native.fromData(data);
this.setNativeInstance(nativeInstance);
return (nativeInstance != null);
};
ImageSource.prototype.setNativeSource = function (source) {
this.setNativeInstance(source);
return source != null;
};
ImageSource.prototype.saveToFile = function (path, format, quality) {
return native.saveToFile(this.getNativeInstance(), path, format, quality);
};
ImageSource.prototype.toBase64String = function (format, quality) {
return native.toBase64String(this.getNativeInstance(), format, quality);
};
Object.defineProperty(ImageSource.prototype, "height", {
get: function () {
if (this.android) {
return this.android.getHeight();
}
if (this.ios) {
return this.ios.size.height;
}
return NaN;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageSource.prototype, "width", {
get: function () {
if (this.android) {
return this.android.getWidth();
}
if (this.ios) {
return this.ios.size.width;
}
return NaN;
},
enumerable: true,
configurable: true
});
ImageSource.prototype.setNativeInstance = function (instance) {
if (utils.targetPlatform() === utils.platform.android) {
this.android = instance;
}
else if (utils.targetPlatform() === utils.platform.ios) {
this.ios = instance;
}
};
ImageSource.prototype.getNativeInstance = function () {
if (this.android) {
return this.android;
}
if (this.ios) {
return this.ios;
}
return undefined;
};
return ImageSource;
})();
exports.ImageSource = ImageSource;
function fromResource(name) {
var image = new ImageSource();
return image.loadFromResource(name) ? image : null;
}
exports.fromResource = fromResource;
function fromFile(path) {
var image = new ImageSource();
return image.loadFromFile(path) ? image : null;
}
exports.fromFile = fromFile;
function fromData(data) {
var image = new ImageSource();
return image.loadFromData(data) ? image : null;
}
exports.fromData = fromData;
function fromNativeSource(source) {
var image = new ImageSource();
return image.setNativeSource(source) ? image : null;
}
exports.fromNativeSource = fromNativeSource;
function fromUrl(url) {
return http.getImage(url);
}
exports.fromUrl = fromUrl;

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "image-source",
"main" : "image-source.js" }

Просмотреть файл

@ -0,0 +1,708 @@
/*
new function() {
var parser = new EasySAXParser();
parser.ns('rss', { // or false
rss: 'http://purl.org/rss/1.0/',
atom: 'http://www.w3.org/2005/Atom',
xhtml: 'http://www.w3.org/1999/xhtml',
media: 'http://search.yahoo.com/mrss/'
});
parser.on('error', function(msg) {
//console.log(msg)
});
parser.on('startNode', function(elem, attr, uq, tagend, getStrNode) {
attr();
return;
if (tagend) {
console.log(' '+str)
} else {
console.log('+ '+str)
};
});
parser.on('endNode', function(elem, uq, tagstart, str) {
return;
if (!tagstart) console.log('- ' + str)
});
parser.on('textNode', function(s, uq) {
uq(s);
return
console.log(' '+s)
});
parser.on('cdata', function(data) {
});
parser.on('comment', function(text) {
//console.log('--'+text+'--')
});
//parser.on('question', function() {}); // <? ... ?>
//parser.on('attention', function() {}); // <!XXXXX zzzz="eeee">
console.time('easysax');
for(var z=1000;z--;) {
parser.parse(xml)
};
console.timeEnd('easysax');
};
*/
// << ------------------------------------------------------------------------ >> //
if (typeof exports === 'object' /*&& this == exports*/) {
module.exports.EasySAXParser = EasySAXParser;
};
function EasySAXParser() {
'use strict';
if (!this) return null;
function nullFunc() {};
var onTextNode = nullFunc, onStartNode = nullFunc, onEndNode = nullFunc, onCDATA = nullFunc, onError = nullFunc, onComment, onQuestion, onAttention;
var is_onComment, is_onQuestion, is_onAttention;
var isNamespace = false, useNS , default_xmlns, xmlns
, nsmatrix = {xmlns: xmlns}
, hasSurmiseNS = false
;
this.on = function(name, cb) {
if (typeof cb !== 'function') {
if (cb !== null) return;
};
switch(name) {
case 'error': onError = cb || nullFunc; break;
case 'startNode': onStartNode = cb || nullFunc; break;
case 'endNode': onEndNode = cb || nullFunc; break;
case 'textNode': onTextNode = cb || nullFunc; break;
case 'cdata': onCDATA = cb || nullFunc; break;
case 'comment': onComment = cb; is_onComment = !!cb; break;
case 'question': onQuestion = cb; is_onQuestion = !!cb; break; // <? .... ?>
case 'attention': onAttention = cb; is_onAttention = !!cb; break; // <!XXXXX zzzz="eeee">
};
};
this.ns = function(root, ns) {
if (!root || typeof root !== 'string' || !ns) {
return;
};
var u, x = {}, ok, v, i;
for(i in ns) {
v = ns[i];
if (typeof v === 'string') {
if (root === v) ok = true;
x[i] = v;
};
};
if (ok) {
isNamespace = true;
default_xmlns = root;
useNS = x;
};
};
this.parse = function(xml) {
if (typeof xml !== 'string') {
return;
};
if (isNamespace) {
nsmatrix = {xmlns: default_xmlns};
parse(xml);
nsmatrix = false;
} else {
parse(xml);
};
attr_res = true;
};
// -----------------------------------------------------
var xharsQuot={constructor: false, hasOwnProperty: false, isPrototypeOf: false, propertyIsEnumerable: false, toLocaleString: false, toString: false, valueOf: false
, quot: '"'
, QUOT: '"'
, amp: '&'
, AMP: '&'
, nbsp: '\u00A0'
, apos: '\''
, lt: '<'
, LT: '<'
, gt: '>'
, GT: '>'
, copy: '\u00A9'
, laquo: '\u00AB'
, raquo: '\u00BB'
, reg: '\u00AE'
, deg: '\u00B0'
, plusmn: '\u00B1'
, sup2: '\u00B2'
, sup3: '\u00B3'
, micro: '\u00B5'
, para: '\u00B6'
};
function rpEntities(s, d, x, z) {
if (z) {
return xharsQuot[z] || '\x01';
};
if (d) {
return String.fromCharCode(d);
};
return String.fromCharCode(parseInt(x, 16));
};
function unEntities(s, i) {
s = String(s);
if (s.length > 3 && s.indexOf('&') !== -1) {
if (s.indexOf('&gt;') !== -1) s = s.replace(/&gt;/g, '>');
if (s.indexOf('&lt;') !== -1) s = s.replace(/&lt;/g, '<');
if (s.indexOf('&quot;') !== -1) s = s.replace(/&quot;/g, '"');
if (s.indexOf('&') !== -1) {
s = s.replace(/&#(\d+);|&#x([0123456789abcdef]+);|&(\w+);/ig, rpEntities);
};
};
return s;
};
var attr_string = ''; // строка атрибутов
var attr_posstart = 0; //
var attr_res; // закешированный результат разбора атрибутов , null - разбор не проводился, object - хеш атрибутов, true - нет атрибутов, false - невалидный xml
/*
парсит атрибуты по требованию. Важно! - функция не генерирует исключения.
если была ошибка разбора возврашается false
если атрибутов нет и разбор удачен то возврашается true
если есть атрибуты то возврашается обьект(хеш)
*/
var RGX_ATTR_NAME = /[^\w:-]+/g;
function getAttrs() {
if (attr_res !== null) {
return attr_res;
};
/*
if (xxtest !== u && attr_string.indexOf(xxtest) === -1) {
/ *
// для ускорения
if (getAttrs('html').type == 'html') {
...
};
* /
return true;
};
*/
var u
, res = {}
, s = attr_string
, i = attr_posstart
, l = s.length
, attr_list = hasSurmiseNS ? [] : false
, name, value = ''
, ok = false
, j, w, nn, n
, hasNewMatrix
, alias, newalias
;
aa:
for(; i < l; i++) {
w = s.charCodeAt(i);
if (w===32 || (w<14 && w > 8) ) { // \f\n\r\t\v
continue
};
if (w < 65 || w >122 || (w>90 && w<97) ) { // ожидаем символ
//console.log('error attr 1')
return attr_res = false; // error. invalid char
};
for(j = i + 1; j < l; j++) { // проверяем все символы имени атрибута
w = s.charCodeAt(j);
if (w > 96 && w < 123 || w > 64 && w < 91 || w > 47 && w < 59 || w === 45 || w === 95 || w === 46 /* https://github.com/telerik/xPlatCore/issues/179 */) {
continue;
};
if (w !== 61) { // "=" == 61
//console.log('error 2');
return attr_res = false; // error. invalid char
};
break;
};
name = s.substring(i, j);
ok = true;
if (name === 'xmlns:xmlns') {
//console.log('error 6')
return attr_res = false; // error. invalid name
};
w = s.charCodeAt(j+1);
if (w === 34) { // '"'
j = s.indexOf('"', i = j+2 );
} else {
if (w === 39) {
j = s.indexOf('\'', i = j+2 );
} else { // "'"
//console.log('error 3')
return attr_res = false; // error. invalid char
};
};
if (j === -1) {
//console.log('error 4')
return attr_res = false; // error. invalid char
};
if (j+1 < l) {
w = s.charCodeAt(j+1);
if (w > 32 || w < 9 || (w<32 && w>13)) {
// error. invalid char
//console.log('error 5')
return attr_res = false;
};
};
value = s.substring(i, j);
i = j + 1; // след. семвол уже проверен потому проверять нужно следуюший
if (isNamespace) { //
if (hasSurmiseNS) {
// есть подозрение что в атрибутах присутствует xmlns
if (newalias = name === 'xmlns' ? 'xmlns' : name.charCodeAt(0) === 120 && name.substr(0, 6) === 'xmlns:' && name.substr(6) ) {
alias = useNS[unEntities(value)];
if (alias) {
if (nsmatrix[newalias] !== alias) {
if (!hasNewMatrix) {
hasNewMatrix = true;
nn = {}; for (n in nsmatrix) nn[n] = nsmatrix[n];
nsmatrix = nn;
};
nsmatrix[newalias] = alias;
};
} else {
if (nsmatrix[newalias]) {
if (!hasNewMatrix) {
hasNewMatrix = true;
nn = {}; for (n in nsmatrix) nn[n] = nsmatrix[n];
nsmatrix = nn;
};
nsmatrix[newalias] = false;
};
};
res[name] = value;
continue;
};
attr_list.push(name, value);
continue;
};
w = name.length;
while(--w) {
if (name.charCodeAt(w) === 58) { // ':'
if (w = nsmatrix[name.substring(0, w)] ) {
res[w + name.substr(w)] = value;
};
continue aa;
// 'xml:base' ???
};
};
};
res[name] = value;
};
if (!ok) {
return attr_res = true; // атрибутов нет, ошибок тоже нет
};
if (hasSurmiseNS) {
bb:
for (i = 0, l = attr_list.length; i < l; i++) {
name = attr_list[i++];
w = name.length;
while(--w) { // name.indexOf(':')
if (name.charCodeAt(w) === 58) { // ':'
if (w = nsmatrix[name.substring(0, w)]) {
res[w + name.substr(w)] = attr_list[i];
};
continue bb;
break;
};
};
res[name] = attr_list[i];
};
};
return attr_res = res;
};
// xml - string
function parse(xml) {
var u
, xml = String(xml)
, nodestack = []
, stacknsmatrix = []
//, string_node
, elem
, tagend = false
, tagstart = false
, j = 0, i = 0
, x, y, q, w
, xmlns
, stopIndex = 0
, stop // используется при разборе "namespace" . если встретился неизвестное пространство то события не генерируются
, _nsmatrix
, ok
;
function getStringNode() {
return xml.substring(i, j+1)
};
while(j !== -1) {
stop = stopIndex > 0;
if (xml.charCodeAt(j) === 60) { // "<"
i = j;
} else {
i = xml.indexOf('<', j);
};
if (i === -1) { // конец разбора
if (nodestack.length) {
onError('end file');
return;
};
return;
};
if (j !== i && !stop) {
ok = onTextNode(xml.substring(j, i), unEntities);
if (ok === false) return;
};
w = xml.charCodeAt(i+1);
if (w === 33) { // "!"
w = xml.charCodeAt(i+2);
if (w === 91 && xml.substr(i+3, 6) === 'CDATA[') { // 91 == "["
j = xml.indexOf(']]>', i);
if (j === -1) {
onError('cdata');
return;
};
//x = xml.substring(i+9, j);
if (!stop) {
ok = onCDATA(xml.substring(i+9, j), false);
if (ok === false) return;
};
j += 3;
continue;
};
if (w === 45 && xml.charCodeAt(i+3) === 45) { // 45 == "-"
j = xml.indexOf('-->', i);
if (j === -1) {
onError('expected -->');
return;
};
if (is_onComment && !stop) {
ok = onComment(xml.substring(i+4, j), unEntities);
if (ok === false) return;
};
j += 3;
continue;
};
j = xml.indexOf('>', i+1);
if (j === -1) {
onError('expected ">"');
return;
};
if (is_onAttention && !stop) {
ok = onAttention(xml.substring(i, j+1), unEntities);
if (ok === false) return;
};
j += 1;
continue;
} else {
if (w === 63) { // "?"
j = xml.indexOf('?>', i);
if (j === -1) { // error
onError('...?>');
return;
};
if (is_onQuestion) {
ok = onQuestion(xml.substring(i, j+2));
if (ok === false) return;
};
j += 2;
continue;
};
};
j = xml.indexOf('>', i+1);
if (j == -1) { // error
onError('...>');
return;
};
attr_res = true; // атрибутов нет
//if (xml.charCodeAt(i+1) === 47) { // </...
if (w === 47) { // </...
tagstart = false;
tagend = true;
// проверяем что должен быть закрыт тотже тег что и открывался
x = elem = nodestack.pop();
q = i + 2 + x.length;
//console.log()
if (xml.substring(i+2, q) !== x) {
onError('close tagname');
return;
};
// проверим что в закрываюшем теге нет лишнего
for(; q < j; q++) {
w = xml.charCodeAt(q);
if (w===32 || (w > 8 && w<14) ) { // \f\n\r\t\v пробел
continue;
};
onError('close tag');
return;
};
} else {
if (xml.charCodeAt(j-1) === 47) { // .../>
x = elem = xml.substring(i+1, j-1);
tagstart = true;
tagend = true;
} else {
x = elem = xml.substring(i+1, j);
tagstart = true;
tagend = false;
};
if ( !(w > 96 && w < 123 || w > 64 && w <91) ) {
onError('first char nodeName');
return;
};
for(q = 1, y = x.length; q < y; q++) {
w = x.charCodeAt(q);
if (w > 96 && w < 123 || w > 64 && w < 91 || w > 47 && w < 59 || w === 45 || w === 95 || w === 46 /* https://github.com/telerik/xPlatCore/issues/179 */) {
continue;
};
if (w===32 || (w<14 && w > 8)) { // \f\n\r\t\v пробел
elem = x.substring(0, q)
attr_res = null; // возможно есть атирибуты
break;
};
onError('invalid nodeName');
return;
};
if (!tagend) {
nodestack.push(elem);
};
};
if (isNamespace) {
if (stop) {
if (tagend) {
if (!tagstart) {
if (--stopIndex === 0) {
nsmatrix = stacknsmatrix.pop();
};
};
} else {
stopIndex += 1;
};
j += 1;
continue;
};
_nsmatrix = nsmatrix;
if (!tagend) {
stacknsmatrix.push(nsmatrix);
if (attr_res !== true) {
if (hasSurmiseNS = x.indexOf('xmlns', q) !== -1) {
attr_string = x;
attr_posstart = q;
getAttrs();
hasSurmiseNS = false;
};
};
};
w = elem.indexOf(':');
if (w !== -1) {
xmlns = nsmatrix[elem.substring(0, w)];
elem = elem.substr(w+1);
} else {
xmlns = nsmatrix.xmlns;
};
if (!xmlns) {
if (tagend) {
if (tagstart) {
nsmatrix = _nsmatrix;
} else {
nsmatrix = stacknsmatrix.pop();
};
} else {
stopIndex = 1; // первый элемент для которого не определено пространство имен
attr_res = true;
};
j += 1;
continue;
};
elem = xmlns + ':' + elem;
};
//string_node = xml.substring(i, j+1); // текст ноды как есть
if (tagstart) { // is_onStartNode
attr_string = x;
attr_posstart = q;
ok = onStartNode(elem, getAttrs, unEntities, tagend
, getStringNode
);
if (ok === false) {
return;
};
attr_res = true;
};
if (tagend) {
ok = onEndNode(elem, unEntities, tagstart
, getStringNode
);
if (ok === false) {
return;
};
if (isNamespace) {
if (tagstart) {
nsmatrix = _nsmatrix;
} else {
nsmatrix = stacknsmatrix.pop();
};
};
};
j += 1;
};
};
};

Просмотреть файл

@ -0,0 +1,38 @@
{
"name": "easysax",
"description": "pure javascript xml parser",
"keywords": [
"xml",
"sax",
"parser",
"pure"
],
"version": "0.1.14",
"main": "easysax.js",
"bugs": {
"url": "https://github.com/vflash/easysax/issues"
},
"author": {
"name": "Vopilovskiy Konstantin",
"email": "flash.vkv@gmail.com",
"url": "http://vflash.ru"
},
"files": [
"easysax.js",
"LICENSE",
"README.md"
],
"repository": {
"type": "git",
"url": "https://github.com/vflash/easysax"
},
"readme": "EASYSAX - pure javascript sax-style parser for xml\r\n==================================================\r\nПростой и быстрый SAX парсер XML файлов.\r\nРеализован по принципу парсить только то что нужно и как можно быстрее.\r\nПарсер не потоковый, и не расчитан на гиганские файлы. Весь XML должен быть в памяти.\r\nВстроенный уникальный механизм работы с пространсвами имен.\r\n\r\n\r\nПарсер был написан для RSS ридера http://zzreader.com\r\nНа конец 2012 года остается самым быстрым SAX парсером под NODE.JS\r\n\r\n\r\n\r\nBENCHMARK\r\n---------------------------------------------------\r\n\r\n**benchmark/test.js, parse file #1**\r\n```\r\nsax-js: 12671ms\r\nlibxmljs: 11311ms\r\nexpat: 6118ms\r\nexpat buffer: 5278ms\r\neasysax : 1739ms // namespace--on, attr()--on , entity_decode--on\r\neasysax: 1035ms // namespace--off, attr()--on , entity_decode--on\r\neasysax: 740ms // namespace--off, attr()--off , entity_decode--off\r\n```\r\n\r\n\r\n**benchmark/test.js, parse file #2 (много атрибутов)**\r\n```\r\nsax-js: 84060ms\r\nlibxmljs: 48919ms\r\nexpat: 39444ms\r\nexpat buffer: 35375ms\r\neasysax: 14655ms // namespace--on, attr()--on , entity_decode--on\r\neasysax: 9874ms // namespace--off, attr()--on , entity_decode--on\r\neasysax: 3531ms // namespace--off, attr()--off , entity_decode--on\r\neasysax: 2954ms // namespace--off, attr()--off , entity_decode--off\r\n```\r\n\r\n\r\n**demo/example.js, parse file #2**\r\n```\r\n1,000 pages for: 13335ms - attr()--all\r\n1,000 pages for: 7300ms - attr()--on_request\r\n```\n",
"readmeFilename": "README.md",
"homepage": "https://github.com/vflash/easysax",
"_id": "easysax@0.1.14",
"dist": {
"shasum": "ef7f6f92dfbbf68306ec3bfa1c707a9d8d959d1e"
},
"_from": "easysax@",
"_resolved": "https://registry.npmjs.org/easysax/-/easysax-0.1.14.tgz"
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,83 @@
{
"name": "esprima",
"description": "ECMAScript parsing infrastructure for multipurpose analysis",
"homepage": "http://esprima.org",
"main": "esprima.js",
"bin": {
"esparse": "./bin/esparse.js",
"esvalidate": "./bin/esvalidate.js"
},
"version": "2.0.0-dev",
"files": [
"bin",
"test/run.js",
"test/runner.js",
"test/test.js",
"test/compat.js",
"test/reflect.js",
"esprima.js"
],
"engines": {
"node": ">=0.4.0"
},
"author": {
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com"
},
"maintainers": [{
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com",
"web": "http://ariya.ofilabs.com"
}],
"repository": {
"type": "git",
"url": "https://github.com/ariya/esprima.git"
},
"bugs": {
"url": "http://issues.esprima.org"
},
"licenses": [{
"type": "BSD",
"url": "https://github.com/ariya/esprima/raw/master/LICENSE.BSD"
}],
"devDependencies": {
"jslint": "~0.1.9",
"eslint": "~0.6.2",
"jscs": "~1.2.4",
"istanbul": "~0.2.6",
"complexity-report": "~0.6.1",
"regenerate": "~0.6.2",
"unicode-7.0.0": "~0.1.5",
"json-diff": "~0.3.1",
"optimist": "~0.6.0"
},
"keywords": [
"ast",
"ecmascript",
"javascript",
"parser",
"syntax"
],
"scripts": {
"generate-regex": "node tools/generate-identifier-regex.js",
"test": "npm run-script lint && node test/run.js && npm run-script coverage && npm run-script complexity",
"lint": "npm run-script check-version && npm run-script eslint && npm run-script jscs && npm run-script jslint",
"check-version": "node tools/check-version.js",
"eslint": "node node_modules/eslint/bin/eslint.js esprima.js",
"jscs": "node node_modules/jscs/bin/jscs esprima.js",
"jslint": "node node_modules/jslint/bin/jslint.js esprima.js",
"coverage": "npm run-script analyze-coverage && npm run-script check-coverage",
"analyze-coverage": "node node_modules/istanbul/lib/cli.js cover test/runner.js",
"check-coverage": "node node_modules/istanbul/lib/cli.js check-coverage --statement 100 --branch 100 --function 100",
"complexity": "npm run-script analyze-complexity && npm run-script check-complexity",
"analyze-complexity": "node tools/list-complexity.js",
"check-complexity": "node node_modules/complexity-report/src/cli.js --maxcc 15 --silent -l -w esprima.js",
"benchmark": "node test/benchmarks.js",
"benchmark-quick": "node test/benchmarks.js quick"
}
}

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "polymer-expressions",
"main" : "polymer-expressions.js" }

Просмотреть файл

@ -0,0 +1,409 @@
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function (global) {
'use strict';
function detectEval() {
// Don't test for eval if we're running in a Chrome App environment.
// We check for APIs set that only exist in a Chrome App context.
if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) {
return false;
}
// Firefox OS Apps do not allow eval. This feature detection is very hacky
// but even if some other platform adds support for this function this code
// will continue to work.
if (typeof navigator != 'undefined' && navigator.getDeviceStorage) {
return false;
}
try {
var f = new Function('', 'return true;');
return f();
} catch (ex) {
return false;
}
}
var hasEval = detectEval();
function isIndex(s) {
return +s === s >>> 0 && s !== '';
}
function toNumber(s) {
return +s;
}
function isObject(obj) {
return obj === Object(obj);
}
var numberIsNaN = global.Number.isNaN || function (value) {
return typeof value === 'number' && global.isNaN(value);
}
function areSameValue(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
if (numberIsNaN(left) && numberIsNaN(right))
return true;
return left !== left && right !== right;
}
var createObject = ('__proto__' in {}) ?
function (obj) { return obj; } :
function (obj) {
var proto = obj.__proto__;
if (!proto)
return obj;
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function (name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
var identStart = '[\$_a-zA-Z]';
var identPart = '[\$_a-zA-Z0-9]';
var identRegExp = new RegExp('^' + identStart + '+' + identPart + '*' + '$');
function getPathCharType(char) {
if (char === undefined)
return 'eof';
var code = char.charCodeAt(0);
switch (code) {
case 0x5B: // [
case 0x5D: // ]
case 0x2E: // .
case 0x22: // "
case 0x27: // '
case 0x30: // 0
return char;
case 0x5F: // _
case 0x24: // $
return 'ident';
case 0x20: // Space
case 0x09: // Tab
case 0x0A: // Newline
case 0x0D: // Return
case 0xA0: // No-break space
case 0xFEFF: // Byte Order Mark
case 0x2028: // Line Separator
case 0x2029: // Paragraph Separator
return 'ws';
}
// a-z, A-Z
if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A))
return 'ident';
// 1-9
if (0x31 <= code && code <= 0x39)
return 'number';
return 'else';
}
var pathStateMachine = {
'beforePath': {
'ws': ['beforePath'],
'ident': ['inIdent', 'append'],
'[': ['beforeElement'],
'eof': ['afterPath']
},
'inPath': {
'ws': ['inPath'],
'.': ['beforeIdent'],
'[': ['beforeElement'],
'eof': ['afterPath']
},
'beforeIdent': {
'ws': ['beforeIdent'],
'ident': ['inIdent', 'append']
},
'inIdent': {
'ident': ['inIdent', 'append'],
'0': ['inIdent', 'append'],
'number': ['inIdent', 'append'],
'ws': ['inPath', 'push'],
'.': ['beforeIdent', 'push'],
'[': ['beforeElement', 'push'],
'eof': ['afterPath', 'push']
},
'beforeElement': {
'ws': ['beforeElement'],
'0': ['afterZero', 'append'],
'number': ['inIndex', 'append'],
"'": ['inSingleQuote', 'append', ''],
'"': ['inDoubleQuote', 'append', '']
},
'afterZero': {
'ws': ['afterElement', 'push'],
']': ['inPath', 'push']
},
'inIndex': {
'0': ['inIndex', 'append'],
'number': ['inIndex', 'append'],
'ws': ['afterElement'],
']': ['inPath', 'push']
},
'inSingleQuote': {
"'": ['afterElement'],
'eof': ['error'],
'else': ['inSingleQuote', 'append']
},
'inDoubleQuote': {
'"': ['afterElement'],
'eof': ['error'],
'else': ['inDoubleQuote', 'append']
},
'afterElement': {
'ws': ['afterElement'],
']': ['inPath', 'push']
}
}
function noop() { }
function parsePath(path) {
var keys = [];
var index = -1;
var c, newChar, key, type, transition, action, typeMap, mode = 'beforePath';
var actions = {
push: function () {
if (key === undefined)
return;
keys.push(key);
key = undefined;
},
append: function () {
if (key === undefined)
key = newChar
else
key += newChar;
}
};
function maybeUnescapeQuote() {
if (index >= path.length)
return;
var nextChar = path[index + 1];
if ((mode == 'inSingleQuote' && nextChar == "'") ||
(mode == 'inDoubleQuote' && nextChar == '"')) {
index++;
newChar = nextChar;
actions.append();
return true;
}
}
while (mode) {
index++;
c = path[index];
if (c == '\\' && maybeUnescapeQuote(mode))
continue;
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap['else'] || 'error';
if (transition == 'error')
return; // parse error;
mode = transition[0];
action = actions[transition[1]] || noop;
newChar = transition[2] === undefined ? c : transition[2];
action();
if (mode === 'afterPath') {
return keys;
}
}
return; // parse error
}
function isIdent(s) {
return identRegExp.test(s);
}
var constructorIsPrivate = {};
function Path(parts, privateToken) {
if (privateToken !== constructorIsPrivate)
throw Error('Use Path.get to retrieve path objects');
for (var i = 0; i < parts.length; i++) {
this.push(String(parts[i]));
}
if (hasEval && this.length) {
this.getValueFrom = this.compiledGetValueFromFn();
}
}
// TODO(rafaelw): Make simple LRU cache
var pathCache = {};
function getPath(pathString) {
if (pathString instanceof Path)
return pathString;
if (pathString == null || pathString.length == 0)
pathString = '';
if (typeof pathString != 'string') {
if (isIndex(pathString.length)) {
// Constructed with array-like (pre-parsed) keys
return new Path(pathString, constructorIsPrivate);
}
pathString = String(pathString);
}
var path = pathCache[pathString];
if (path)
return path;
var parts = parsePath(pathString);
if (!parts)
return invalidPath;
var path = new Path(parts, constructorIsPrivate);
pathCache[pathString] = path;
return path;
}
Path.get = getPath;
function formatAccessor(key) {
if (isIndex(key)) {
return '[' + key + ']';
} else {
return '["' + key.replace(/"/g, '\\"') + '"]';
}
}
Path.prototype = createObject({
__proto__: [],
valid: true,
toString: function () {
var pathString = '';
for (var i = 0; i < this.length; i++) {
var key = this[i];
if (isIdent(key)) {
pathString += i ? '.' + key : key;
} else {
pathString += formatAccessor(key);
}
}
return pathString;
},
getValueFrom: function (obj, directObserver) {
for (var i = 0; i < this.length; i++) {
if (obj == null)
return;
obj = obj[this[i]];
}
return obj;
},
iterateObjects: function (obj, observe) {
for (var i = 0; i < this.length; i++) {
if (i)
obj = obj[this[i - 1]];
if (!isObject(obj))
return;
observe(obj, this[i]);
}
},
compiledGetValueFromFn: function () {
var str = '';
var pathString = 'obj';
str += 'if (obj != null';
var i = 0;
var key;
for (; i < (this.length - 1) ; i++) {
key = this[i];
pathString += isIdent(key) ? '.' + key : formatAccessor(key);
str += ' &&\n ' + pathString + ' != null';
}
str += ')\n';
var key = this[i];
pathString += isIdent(key) ? '.' + key : formatAccessor(key);
str += ' return ' + pathString + ';\nelse\n return undefined;';
return new Function('obj', str);
},
setValueFrom: function (obj, value) {
if (!this.length)
return false;
for (var i = 0; i < this.length - 1; i++) {
if (!isObject(obj))
return false;
obj = obj[this[i]];
}
if (!isObject(obj))
return false;
obj[this[i]] = value;
return true;
}
});
var invalidPath = new Path('', constructorIsPrivate);
invalidPath.valid = false;
invalidPath.getValueFrom = invalidPath.setValueFrom = function () { };
// Export the observe-js object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, export as a global object.
var expose = global;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
expose = exports = module.exports;
}
expose = exports;
}
expose.Path = Path;
})(typeof global !== 'undefined' && global && typeof module !== 'undefined' && module ? global : this || window);

Просмотреть файл

@ -0,0 +1,531 @@
// Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
// This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
// The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
// The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
// Code distributed by Google as part of the polymer project is also
// subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
var esprima = require("js-libs/esprima").esprima;
var Path = require("js-libs/polymer-expressions/path-parser").Path;
(function (global) {
'use strict';
// TODO(rafaelw): Implement simple LRU.
var expressionParseCache = Object.create(null);
function getExpression(expressionText) {
var expression = expressionParseCache[expressionText];
if (!expression) {
var delegate = new ASTDelegate();
esprima.parse(expressionText, delegate);
expression = new Expression(delegate);
expressionParseCache[expressionText] = expression;
}
return expression;
}
function Literal(value) {
this.value = value;
this.valueFn_ = undefined;
}
Literal.prototype = {
valueFn: function () {
if (!this.valueFn_) {
var value = this.value;
this.valueFn_ = function () {
return value;
}
}
return this.valueFn_;
}
}
function IdentPath(name) {
this.name = name;
this.path = Path.get(name);
}
IdentPath.prototype = {
valueFn: function () {
if (!this.valueFn_) {
var name = this.name;
var path = this.path;
this.valueFn_ = function (model, observer) {
if (observer)
observer.addPath(model, path);
return path.getValueFrom(model);
}
}
return this.valueFn_;
},
setValue: function (model, newValue) {
if (this.path.length == 1);
model = findScope(model, this.path[0]);
return this.path.setValueFrom(model, newValue);
}
};
function MemberExpression(object, property, accessor) {
this.computed = accessor == '[';
this.dynamicDeps = typeof object == 'function' ||
object.dynamicDeps ||
(this.computed && !(property instanceof Literal));
this.simplePath =
!this.dynamicDeps &&
(property instanceof IdentPath || property instanceof Literal) &&
(object instanceof MemberExpression || object instanceof IdentPath);
this.object = this.simplePath ? object : getFn(object);
this.property = !this.computed || this.simplePath ?
property : getFn(property);
}
MemberExpression.prototype = {
get fullPath() {
if (!this.fullPath_) {
var parts = this.object instanceof MemberExpression ?
this.object.fullPath.slice() : [this.object.name];
parts.push(this.property instanceof IdentPath ?
this.property.name : this.property.value);
this.fullPath_ = Path.get(parts);
}
return this.fullPath_;
},
valueFn: function () {
if (!this.valueFn_) {
var object = this.object;
if (this.simplePath) {
var path = this.fullPath;
this.valueFn_ = function (model, observer) {
if (observer)
observer.addPath(model, path);
return path.getValueFrom(model);
};
} else if (!this.computed) {
var path = Path.get(this.property.name);
this.valueFn_ = function (model, observer, filterRegistry) {
var context = object(model, observer, filterRegistry);
if (observer)
observer.addPath(context, path);
return path.getValueFrom(context);
}
} else {
// Computed property.
var property = this.property;
this.valueFn_ = function (model, observer, filterRegistry) {
var context = object(model, observer, filterRegistry);
var propName = property(model, observer, filterRegistry);
if (observer)
observer.addPath(context, [propName]);
return context ? context[propName] : undefined;
};
}
}
return this.valueFn_;
},
setValue: function (model, newValue) {
if (this.simplePath) {
this.fullPath.setValueFrom(model, newValue);
return newValue;
}
var object = this.object(model);
var propName = this.property instanceof IdentPath ? this.property.name :
this.property(model);
return object[propName] = newValue;
}
};
function Filter(name, args) {
this.name = name;
this.args = [];
for (var i = 0; i < args.length; i++) {
this.args[i] = getFn(args[i]);
}
}
Filter.prototype = {
transform: function (model, observer, filterRegistry, toModelDirection,
initialArgs) {
var fn = filterRegistry[this.name];
var context = model;
if (fn) {
context = undefined;
} else {
fn = context[this.name];
if (!fn) {
console.error('Cannot find function or filter: ' + this.name);
return;
}
}
// If toModelDirection is falsey, then the "normal" (dom-bound) direction
// is used. Otherwise, it looks for a 'toModel' property function on the
// object.
if (toModelDirection) {
fn = fn.toModel;
} else if (typeof fn.toDOM == 'function') {
fn = fn.toDOM;
}
if (typeof fn != 'function') {
console.error('Cannot find function or filter: ' + this.name);
return;
}
var args = initialArgs || [];
for (var i = 0; i < this.args.length; i++) {
args.push(getFn(this.args[i])(model, observer, filterRegistry));
}
return fn.apply(context, args);
}
};
function notImplemented() { throw Error('Not Implemented'); }
var unaryOperators = {
'+': function (v) { return +v; },
'-': function (v) { return -v; },
'!': function (v) { return !v; }
};
var binaryOperators = {
'+': function (l, r) { return l + r; },
'-': function (l, r) { return l - r; },
'*': function (l, r) { return l * r; },
'/': function (l, r) { return l / r; },
'%': function (l, r) { return l % r; },
'<': function (l, r) { return l < r; },
'>': function (l, r) { return l > r; },
'<=': function (l, r) { return l <= r; },
'>=': function (l, r) { return l >= r; },
'==': function (l, r) { return l == r; },
'!=': function (l, r) { return l != r; },
'===': function (l, r) { return l === r; },
'!==': function (l, r) { return l !== r; },
'&&': function (l, r) { return l && r; },
'||': function (l, r) { return l || r; },
};
function getFn(arg) {
return typeof arg == 'function' ? arg : arg.valueFn();
}
function ASTDelegate() {
this.expression = null;
this.filters = [];
this.deps = {};
this.currentPath = undefined;
this.scopeIdent = undefined;
this.indexIdent = undefined;
this.dynamicDeps = false;
}
ASTDelegate.prototype = {
createUnaryExpression: function (op, argument) {
if (!unaryOperators[op])
throw Error('Disallowed operator: ' + op);
argument = getFn(argument);
return function (model, observer, filterRegistry) {
return unaryOperators[op](argument(model, observer, filterRegistry));
};
},
createBinaryExpression: function (op, left, right) {
if (!binaryOperators[op])
throw Error('Disallowed operator: ' + op);
left = getFn(left);
right = getFn(right);
switch (op) {
case '||':
this.dynamicDeps = true;
return function (model, observer, filterRegistry) {
return left(model, observer, filterRegistry) ||
right(model, observer, filterRegistry);
};
case '&&':
this.dynamicDeps = true;
return function (model, observer, filterRegistry) {
return left(model, observer, filterRegistry) &&
right(model, observer, filterRegistry);
};
}
return function (model, observer, filterRegistry) {
return binaryOperators[op](left(model, observer, filterRegistry),
right(model, observer, filterRegistry));
};
},
createConditionalExpression: function (test, consequent, alternate) {
test = getFn(test);
consequent = getFn(consequent);
alternate = getFn(alternate);
this.dynamicDeps = true;
return function (model, observer, filterRegistry) {
return test(model, observer, filterRegistry) ?
consequent(model, observer, filterRegistry) :
alternate(model, observer, filterRegistry);
}
},
createIdentifier: function (name) {
var ident = new IdentPath(name);
ident.type = 'Identifier';
return ident;
},
createMemberExpression: function (accessor, object, property) {
var ex = new MemberExpression(object, property, accessor);
if (ex.dynamicDeps)
this.dynamicDeps = true;
return ex;
},
createCallExpression: function (expression, args) {
if (!(expression instanceof IdentPath))
throw Error('Only identifier function invocations are allowed');
var filter = new Filter(expression.name, args);
return function (model, observer, filterRegistry) {
return filter.transform(model, observer, filterRegistry, false);
};
},
createLiteral: function (token) {
return new Literal(token.value);
},
createArrayExpression: function (elements) {
for (var i = 0; i < elements.length; i++)
elements[i] = getFn(elements[i]);
return function (model, observer, filterRegistry) {
var arr = []
for (var i = 0; i < elements.length; i++)
arr.push(elements[i](model, observer, filterRegistry));
return arr;
}
},
createProperty: function (kind, key, value) {
return {
key: key instanceof IdentPath ? key.name : key.value,
value: value
};
},
createObjectExpression: function (properties) {
for (var i = 0; i < properties.length; i++)
properties[i].value = getFn(properties[i].value);
return function (model, observer, filterRegistry) {
var obj = {};
for (var i = 0; i < properties.length; i++)
obj[properties[i].key] =
properties[i].value(model, observer, filterRegistry);
return obj;
}
},
createFilter: function (name, args) {
this.filters.push(new Filter(name, args));
},
createAsExpression: function (expression, scopeIdent) {
this.expression = expression;
this.scopeIdent = scopeIdent;
},
createInExpression: function (scopeIdent, indexIdent, expression) {
this.expression = expression;
this.scopeIdent = scopeIdent;
this.indexIdent = indexIdent;
},
createTopLevel: function (expression) {
this.expression = expression;
},
createThisExpression: notImplemented
}
function Expression(delegate) {
this.scopeIdent = delegate.scopeIdent;
this.indexIdent = delegate.indexIdent;
if (!delegate.expression)
throw Error('No expression found.');
this.expression = delegate.expression;
getFn(this.expression); // forces enumeration of path dependencies
this.filters = delegate.filters;
this.dynamicDeps = delegate.dynamicDeps;
}
Expression.prototype = {
getValue: function (model, observer, filterRegistry) {
var value = getFn(this.expression)(model, observer, filterRegistry);
for (var i = 0; i < this.filters.length; i++) {
value = this.filters[i].transform(model, observer, filterRegistry,
false, [value]);
}
return value;
},
setValue: function (model, newValue, filterRegistry) {
var count = this.filters ? this.filters.length : 0;
while (count-- > 0) {
newValue = this.filters[count].transform(model, undefined,
filterRegistry, true, [newValue]);
}
if (this.expression.setValue)
return this.expression.setValue(model, newValue);
}
}
/**
* Converts a style property name to a css property name. For example:
* "WebkitUserSelect" to "-webkit-user-select"
*/
function convertStylePropertyName(name) {
return String(name).replace(/[A-Z]/g, function (c) {
return '-' + c.toLowerCase();
});
}
var parentScopeName = '@' + Math.random().toString(36).slice(2);
// Single ident paths must bind directly to the appropriate scope object.
// I.e. Pushed values in two-bindings need to be assigned to the actual model
// object.
function findScope(model, prop) {
while (model[parentScopeName] &&
!Object.prototype.hasOwnProperty.call(model, prop)) {
model = model[parentScopeName];
}
return model;
}
function isLiteralExpression(pathString) {
switch (pathString) {
case '':
return false;
case 'false':
case 'null':
case 'true':
return true;
}
if (!isNaN(Number(pathString)))
return true;
return false;
};
function PolymerExpressions() { }
PolymerExpressions.prototype = {
// "built-in" filters
styleObject: function (value) {
var parts = [];
for (var key in value) {
parts.push(convertStylePropertyName(key) + ': ' + value[key]);
}
return parts.join('; ');
},
tokenList: function (value) {
var tokens = [];
for (var key in value) {
if (value[key])
tokens.push(key);
}
return tokens.join(' ');
},
// binding delegate API
prepareInstancePositionChanged: function (template) {
var indexIdent = template.polymerExpressionIndexIdent_;
if (!indexIdent)
return;
return function (templateInstance, index) {
templateInstance.model[indexIdent] = index;
};
},
prepareInstanceModel: function (template) {
var scopeName = template.polymerExpressionScopeIdent_;
if (!scopeName)
return;
var parentScope = template.templateInstance ?
template.templateInstance.model :
template.model;
var indexName = template.polymerExpressionIndexIdent_;
return function (model) {
return createScopeObject(parentScope, model, scopeName, indexName);
};
}
};
var createScopeObject = ('__proto__' in {}) ?
function (parentScope, model, scopeName, indexName) {
var scope = {};
scope[scopeName] = model;
scope[indexName] = undefined;
scope[parentScopeName] = parentScope;
scope.__proto__ = parentScope;
return scope;
} :
function (parentScope, model, scopeName, indexName) {
var scope = Object.create(parentScope);
Object.defineProperty(scope, scopeName,
{ value: model, configurable: true, writable: true });
Object.defineProperty(scope, indexName,
{ value: undefined, configurable: true, writable: true });
Object.defineProperty(scope, parentScopeName,
{ value: parentScope, configurable: true, writable: true });
return scope;
};
global.PolymerExpressions = PolymerExpressions;
PolymerExpressions.getExpression = getExpression;
})(module.exports);

Просмотреть файл

@ -0,0 +1,18 @@
{
"name": "reworkcss",
"version": "2.1.0",
"description": "CSS parser",
"main": "reworkcss.js",
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/reworkcss/css.git"
},
"keywords": [
"css",
"parser",
"stringifier",
"stylesheet"
]
}

Просмотреть файл

@ -0,0 +1,596 @@
// http://www.w3.org/TR/CSS21/grammar.html
// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027
var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g
module.exports.parse = function(css, options){
options = options || {};
/**
* Positional.
*/
var lineno = 1;
var column = 1;
/**
* Update lineno and column based on `str`.
*/
function updatePosition(str) {
var lines = str.match(/\n/g);
if (lines) lineno += lines.length;
var i = str.lastIndexOf('\n');
column = ~i ? str.length - i : column + str.length;
}
/**
* Mark position and patch `node.position`.
*/
function position() {
var start = { line: lineno, column: column };
return function(node){
node.position = new Position(start);
whitespace();
return node;
};
}
/**
* Store position information for a node
*/
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
/**
* Non-enumerable source string
*/
Position.prototype.content = css;
/**
* Error `msg`.
*/
function error(msg) {
if (options.silent === true) {
return false;
}
var err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);
err.reason = msg;
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = css;
throw err;
}
/**
* Parse stylesheet.
*/
function stylesheet() {
return {
type: 'stylesheet',
stylesheet: {
rules: rules()
}
};
}
/**
* Opening brace.
*/
function open() {
return match(/^{\s*/);
}
/**
* Closing brace.
*/
function close() {
return match(/^}/);
}
/**
* Parse ruleset.
*/
function rules() {
var node;
var rules = [];
whitespace();
comments(rules);
while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) {
if (node !== false) {
rules.push(node);
comments(rules);
}
}
return rules;
}
/**
* Match `re` and return captures.
*/
function match(re) {
var m = re.exec(css);
if (!m) return;
var str = m[0];
updatePosition(str);
css = css.slice(str.length);
return m;
}
/**
* Parse whitespace.
*/
function whitespace() {
match(/^\s*/);
}
/**
* Parse comments;
*/
function comments(rules) {
var c;
rules = rules || [];
while (c = comment()) {
if (c !== false) {
rules.push(c);
}
}
return rules;
}
/**
* Parse comment.
*/
function comment() {
var pos = position();
if ('/' != css.charAt(0) || '*' != css.charAt(1)) return;
var i = 2;
while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i;
i += 2;
if ("" === css.charAt(i-1)) {
return error('End of comment missing');
}
var str = css.slice(2, i - 2);
column += 2;
updatePosition(str);
css = css.slice(i);
column += 2;
return pos({
type: 'comment',
comment: str
});
}
/**
* Parse selector.
*/
function selector() {
var m = match(/^([^{]+)/);
if (!m) return;
/* @fix Remove all comments from selectors
* http://ostermiller.org/findcomment.html */
return trim(m[0])
.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '')
.replace(/(?:"[^"]*"|'[^']*')/g, function(m) {
return m.replace(/,/g, '\u200C');
})
.split(/\s*(?![^(]*\)),\s*/)
.map(function(s) {
return s.replace(/\u200C/g, ',');
});
}
/**
* Parse declaration.
*/
function declaration() {
var pos = position();
// prop
var prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
if (!prop) return;
prop = trim(prop[0]);
// :
if (!match(/^:\s*/)) return error("property missing ':'");
// val
var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);
var ret = pos({
type: 'declaration',
property: prop.replace(commentre, ''),
value: val ? trim(val[0]).replace(commentre, '') : ''
});
// ;
match(/^[;\s]*/);
return ret;
}
/**
* Parse declarations.
*/
function declarations() {
var decls = [];
if (!open()) return error("missing '{'");
comments(decls);
// declarations
var decl;
while (decl = declaration()) {
if (decl !== false) {
decls.push(decl);
comments(decls);
}
}
if (!close()) return error("missing '}'");
return decls;
}
/**
* Parse keyframe.
*/
function keyframe() {
var m;
var vals = [];
var pos = position();
while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) {
vals.push(m[1]);
match(/^,\s*/);
}
if (!vals.length) return;
return pos({
type: 'keyframe',
values: vals,
declarations: declarations()
});
}
/**
* Parse keyframes.
*/
function atkeyframes() {
var pos = position();
var m = match(/^@([-\w]+)?keyframes */);
if (!m) return;
var vendor = m[1];
// identifier
var m = match(/^([-\w]+)\s*/);
if (!m) return error("@keyframes missing name");
var name = m[1];
if (!open()) return error("@keyframes missing '{'");
var frame;
var frames = comments();
while (frame = keyframe()) {
frames.push(frame);
frames = frames.concat(comments());
}
if (!close()) return error("@keyframes missing '}'");
return pos({
type: 'keyframes',
name: name,
vendor: vendor,
keyframes: frames
});
}
/**
* Parse supports.
*/
function atsupports() {
var pos = position();
var m = match(/^@supports *([^{]+)/);
if (!m) return;
var supports = trim(m[1]);
if (!open()) return error("@supports missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@supports missing '}'");
return pos({
type: 'supports',
supports: supports,
rules: style
});
}
/**
* Parse host.
*/
function athost() {
var pos = position();
var m = match(/^@host */);
if (!m) return;
if (!open()) return error("@host missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@host missing '}'");
return pos({
type: 'host',
rules: style
});
}
/**
* Parse media.
*/
function atmedia() {
var pos = position();
var m = match(/^@media *([^{]+)/);
if (!m) return;
var media = trim(m[1]);
if (!open()) return error("@media missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@media missing '}'");
return pos({
type: 'media',
media: media,
rules: style
});
}
/**
* Parse custom-media.
*/
function atcustommedia() {
var pos = position();
var m = match(/^@custom-media (--[^\s]+) *([^{;]+);/);
if (!m) return;
return pos({
type: 'custom-media',
name: trim(m[1]),
media: trim(m[2])
});
}
/**
* Parse paged media.
*/
function atpage() {
var pos = position();
var m = match(/^@page */);
if (!m) return;
var sel = selector() || [];
if (!open()) return error("@page missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("@page missing '}'");
return pos({
type: 'page',
selectors: sel,
declarations: decls
});
}
/**
* Parse document.
*/
function atdocument() {
var pos = position();
var m = match(/^@([-\w]+)?document *([^{]+)/);
if (!m) return;
var vendor = trim(m[1]);
var doc = trim(m[2]);
if (!open()) return error("@document missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@document missing '}'");
return pos({
type: 'document',
document: doc,
vendor: vendor,
rules: style
});
}
/**
* Parse font-face.
*/
function atfontface() {
var pos = position();
var m = match(/^@font-face */);
if (!m) return;
if (!open()) return error("@font-face missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("@font-face missing '}'");
return pos({
type: 'font-face',
declarations: decls
});
}
/**
* Parse import
*/
var atimport = _compileAtrule('import');
/**
* Parse charset
*/
var atcharset = _compileAtrule('charset');
/**
* Parse namespace
*/
var atnamespace = _compileAtrule('namespace');
/**
* Parse non-block at-rules
*/
function _compileAtrule(name) {
var re = new RegExp('^@' + name + ' *([^;\\n]+);');
return function() {
var pos = position();
var m = match(re);
if (!m) return;
var ret = { type: name };
ret[name] = m[1].trim();
return pos(ret);
}
}
/**
* Parse at rule.
*/
function atrule() {
if (css[0] != '@') return;
return atkeyframes()
|| atmedia()
|| atcustommedia()
|| atsupports()
|| atimport()
|| atcharset()
|| atnamespace()
|| atdocument()
|| atpage()
|| athost()
|| atfontface();
}
/**
* Parse rule.
*/
function rule() {
var pos = position();
var sel = selector();
if (!sel) return error('selector missing');
comments();
return pos({
type: 'rule',
selectors: sel,
declarations: declarations()
});
}
return addParent(stylesheet());
};
/**
* Trim `str`.
*/
function trim(str) {
return str ? str.replace(/^\s+|\s+$/g, '') : '';
}
/**
* Adds non-enumerable parent node reference to each node.
*/
function addParent(obj, parent) {
var isNode = obj && typeof obj.type === 'string';
var childParent = isNode ? obj : parent;
for (var k in obj) {
var value = obj[k];
if (Array.isArray(value)) {
value.forEach(function(v) { addParent(v, childParent); });
} else if (value && typeof value === 'object') {
addParent(value, childParent);
}
}
if (isNode) {
Object.defineProperty(obj, 'parent', {
configurable: true,
writable: true,
enumerable: false,
value: parent || null
});
}
return obj;
}

Просмотреть файл

@ -0,0 +1,10 @@
exports.checkKey = function (key) {
if ("string" !== typeof key) {
throw new Error("key: '" + key + "' must be a string");
}
};
exports.ensureValidValue = function (value, valueType) {
if (valueType !== typeof value) {
throw new Error("value: '" + value + "' must be a " + valueType);
}
};

Просмотреть файл

@ -0,0 +1,55 @@
var appModule = require("application");
var Common = require("local-settings/local-settings-common");
var sharedPreferences = appModule.android.context.getSharedPreferences("prefs.db", 0);
exports.hasKey = function (key) {
Common.checkKey(key);
return sharedPreferences.contains(key);
};
exports.getBoolean = function (key, defaultValue) {
Common.checkKey(key);
if (exports.hasKey(key)) {
return sharedPreferences.getBoolean(key, false);
}
return defaultValue;
};
exports.getString = function (key, defaultValue) {
Common.checkKey(key);
if (exports.hasKey(key)) {
return sharedPreferences.getString(key, "");
}
return defaultValue;
};
exports.getNumber = function (key, defaultValue) {
Common.checkKey(key);
if (exports.hasKey(key)) {
return sharedPreferences.getFloat(key, float(0.0));
}
return defaultValue;
};
exports.setBoolean = function (key, value) {
Common.checkKey(key);
Common.ensureValidValue(value, "boolean");
var editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
};
exports.setString = function (key, value) {
Common.checkKey(key);
Common.ensureValidValue(value, "string");
var editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
};
exports.setNumber = function (key, value) {
Common.checkKey(key);
Common.ensureValidValue(value, "number");
var editor = sharedPreferences.edit();
editor.putFloat(key, float(value));
editor.commit();
};
exports.remove = function (key) {
Common.checkKey(key);
var editor = sharedPreferences.edit();
editor.remove(key);
editor.commit();
};

Просмотреть файл

@ -0,0 +1,50 @@
var Common = require("local-settings/local-settings-common");
var userDefaults = NSUserDefaults.standardUserDefaults();
exports.hasKey = function (key) {
Common.checkKey(key);
return userDefaults.objectForKey(key) !== null;
};
exports.getBoolean = function (key, defaultValue) {
Common.checkKey(key);
if (exports.hasKey(key)) {
return userDefaults.boolForKey(key);
}
return defaultValue;
};
exports.getString = function (key, defaultValue) {
Common.checkKey(key);
if (exports.hasKey(key)) {
return userDefaults.stringForKey(key);
}
return defaultValue;
};
exports.getNumber = function (key, defaultValue) {
Common.checkKey(key);
if (exports.hasKey(key)) {
return userDefaults.doubleForKey(key);
}
return defaultValue;
};
exports.setBoolean = function (key, value) {
Common.checkKey(key);
Common.ensureValidValue(value, "boolean");
userDefaults.setBoolForKey(value, key);
userDefaults.synchronize();
};
exports.setString = function (key, value) {
Common.checkKey(key);
Common.ensureValidValue(value, "string");
userDefaults.setObjectForKey(value, key);
userDefaults.synchronize();
};
exports.setNumber = function (key, value) {
Common.checkKey(key);
Common.ensureValidValue(value, "number");
userDefaults.setDoubleForKey(value, key);
userDefaults.synchronize();
};
exports.remove = function (key) {
Common.checkKey(key);
userDefaults.removeObjectForKey(key);
userDefaults.synchronize();
};

Просмотреть файл

@ -0,0 +1,2 @@
{ "name" : "local-settings",
"main" : "local-settings.js" }

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше