Publish Vulpes Preview 15 sources for desktop, Android and Tundra
Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
61
gaia/apps/search/build/build.js
Executable file
|
|
@ -0,0 +1,61 @@
|
|||
'use strict';
|
||||
|
||||
/* jshint node: true */
|
||||
|
||||
var utils = require('utils');
|
||||
|
||||
var SearchAppBuilder = function() {
|
||||
};
|
||||
|
||||
function pickAsset(root, filename, ppx) {
|
||||
if (ppx !== '1') {
|
||||
var suffix = '@' + ppx + 'x';
|
||||
var hdpiFile = filename.replace(/(\.[a-z]+$)/, suffix + '$1');
|
||||
var file = utils.getFile(root.path, hdpiFile);
|
||||
if (file.exists()) {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
return utils.getFile(root.path, filename);
|
||||
}
|
||||
|
||||
SearchAppBuilder.prototype.setOptions = function(options) {
|
||||
this.stageDir = utils.getFile(options.STAGE_APP_DIR);
|
||||
this.appDir = utils.getFile(options.APP_DIR);
|
||||
this.buildDir = utils.getFile(this.appDir.path, '/build');
|
||||
this.distDirPath = options.GAIA_DISTRIBUTION_DIR;
|
||||
};
|
||||
|
||||
SearchAppBuilder.prototype.initTopsitesJSON = function() {
|
||||
var defaultJSONpath =
|
||||
utils.joinPath(this.appDir.path, 'build', 'topsites.json');
|
||||
var defaultJson = utils.getJSON(utils.getFile(defaultJSONpath));
|
||||
|
||||
defaultJson.forEach(function(site) {
|
||||
if (site.tilePath) {
|
||||
var file = pickAsset(this.buildDir, site.tilePath,
|
||||
this.options.GAIA_DEV_PIXELS_PER_PX);
|
||||
var icon = utils.getFileAsDataURI(file);
|
||||
site.tile = icon;
|
||||
delete site.tilePath;
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
var file = utils.getFile(this.stageDir.path, 'js', 'inittopsites.json');
|
||||
var fileContents = utils.getDistributionFileContent('topsites', defaultJson,
|
||||
this.distDirPath);
|
||||
utils.writeContent(file, fileContents);
|
||||
};
|
||||
|
||||
SearchAppBuilder.prototype.execute = function(options) {
|
||||
this.options = options;
|
||||
this.setOptions(options);
|
||||
if (options.PROFILE_FOLDER !== 'profile-test') {
|
||||
this.initTopsitesJSON();
|
||||
}
|
||||
};
|
||||
|
||||
exports.execute = function(options) {
|
||||
utils.copyToStage(options);
|
||||
(new SearchAppBuilder()).execute(options);
|
||||
};
|
||||
BIN
gaia/apps/search/build/mozilla.org.jpg
Executable file
|
After Width: | Height: | Size: 7.8 KiB |
BIN
gaia/apps/search/build/mozilla.org@1.5x.jpg
Executable file
|
After Width: | Height: | Size: 12 KiB |
BIN
gaia/apps/search/build/mozilla.org@2.25x.jpg
Executable file
|
After Width: | Height: | Size: 18 KiB |
BIN
gaia/apps/search/build/mozilla.org@2x.jpg
Executable file
|
After Width: | Height: | Size: 16 KiB |
BIN
gaia/apps/search/build/mozillasupport.jpg
Executable file
|
After Width: | Height: | Size: 6.9 KiB |
BIN
gaia/apps/search/build/mozillasupport@1.5x.jpg
Executable file
|
After Width: | Height: | Size: 12 KiB |
BIN
gaia/apps/search/build/mozillasupport@2.25x.jpg
Executable file
|
After Width: | Height: | Size: 16 KiB |
BIN
gaia/apps/search/build/mozillasupport@2x.jpg
Executable file
|
After Width: | Height: | Size: 17 KiB |
14
gaia/apps/search/build/topsites.json
Executable file
|
|
@ -0,0 +1,14 @@
|
|||
[
|
||||
{
|
||||
"title": "Mozilla",
|
||||
"url": "https://mozilla.org",
|
||||
"frecency": 0,
|
||||
"tilePath": "mozilla.org.jpg"
|
||||
},
|
||||
{
|
||||
"title": "Mozilla Support",
|
||||
"url": "https://support.mozilla.org",
|
||||
"frecency": 0,
|
||||
"tilePath": "mozillasupport.jpg"
|
||||
}
|
||||
]
|
||||
115
gaia/apps/search/index.html
Executable file
|
|
@ -0,0 +1,115 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0">
|
||||
<link rel="stylesheet" href="style/search.css">
|
||||
<link rel="stylesheet" href="shared/elements/gaia_grid/style/external.css">
|
||||
<link rel="stylesheet" href="shared/style/progress_activity.css">
|
||||
<meta name="defaultLanguage" content="en-US">
|
||||
<meta name="availableLanguages" content="en-US">
|
||||
<link rel="localization" href="locales/search.{locale}.properties">
|
||||
<link rel="localization" href="/shared/elements/gaia_grid/locales/gaia_grid.{locale}.properties">
|
||||
|
||||
<script defer src="shared/js/l10n.js"></script>
|
||||
<script defer src="shared/js/lazy_loader.js"></script>
|
||||
<script defer src="shared/js/async_storage.js"></script>
|
||||
<script defer src="shared/js/utilities.js"></script>
|
||||
<script defer src="shared/js/settings_listener.js"></script>
|
||||
<script defer src="shared/js/format.js"></script>
|
||||
<script defer src="shared/js/search_provider.js"></script>
|
||||
<!-- <script defer src="shared/js/search_providers.json"></script> -->
|
||||
|
||||
<!-- Confirm dialog component -->
|
||||
<script defer src="/shared/js/component_utils.js"></script>
|
||||
<script defer src="/shared/elements/gaia_buttons/script.js"></script>
|
||||
<script defer src="/shared/elements/gaia_confirm/script.js"></script>
|
||||
<!--- gaia_grid required scripts -->
|
||||
<script defer src="shared/js/homescreens/homescreen_settings.js"></script>
|
||||
<script defer src="shared/js/homescreens/confirm_dialog_helper.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/grid_view.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/grid_icon_renderer.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/grid_layout.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/grid_zoom.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/script.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/items/grid_item.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/items/bookmark.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/items/marketplace_app.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/items/divider.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/items/mozapp.js"></script>
|
||||
<script defer src="shared/elements/gaia_grid/js/items/placeholder.js"></script>
|
||||
|
||||
<script defer src="shared/js/async_storage.js"></script>
|
||||
<script defer src="shared/js/url_helper.js"></script>
|
||||
<script defer src="shared/js/web_manifest_helper.js"></script>
|
||||
<script defer src="shared/js/utilities.js"></script>
|
||||
<script defer src="shared/js/dedupe.js"></script>
|
||||
<script defer src="js/places_idb.js"></script>
|
||||
<script defer src="shared/js/sync_datastore.js"></script>
|
||||
<script defer src="shared/js/icons_helper.js"></script>
|
||||
<script defer src="shared/js/metrics_helper.js"></script>
|
||||
<script defer src="js/contextmenu.js"></script>
|
||||
<script defer src="js/search.js"></script>
|
||||
<script defer src="js/providers/provider.js"></script>
|
||||
<script defer src="js/providers/grid_provider.js"></script>
|
||||
|
||||
<!-- Ordering of the following files will impact which queries we send first -->
|
||||
<script defer src="js/providers/marketplace.js"></script>
|
||||
<script defer src="js/providers/suggestions.js"></script>
|
||||
<script defer src="js/providers/bookmarks.js"></script>
|
||||
<script defer src="js/providers/places.js"></script>
|
||||
<script defer src="js/providers/local_apps.js"></script>
|
||||
|
||||
<!-- Include the app icon in the application.zip -->
|
||||
<link rel="resource" type="image/png" href="shared/resources/branding/browser_84.png"/>
|
||||
<link rel="resource" type="image/png" href="shared/resources/branding/browser_126.png"/>
|
||||
<link rel="resource" type="image/png" href="shared/resources/branding/browser_142.png"/>
|
||||
<link rel="resource" type="image/png" href="shared/resources/branding/browser_189.png"/>
|
||||
<link rel="resource" type="image/png" href="shared/resources/branding/browser_284.png"/>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div id="search-results" class="hidden">
|
||||
<div id="offline-message">
|
||||
<span id="settings-connectivity"></span>
|
||||
<span data-l10n-id="offline-message"></span>
|
||||
</div>
|
||||
|
||||
<section id="contacts" class="local" data-l10n-id="contacts"
|
||||
aria-label="Contacts"></section>
|
||||
|
||||
<section id="icons-wrapper" class="apps" data-l10n-id="apps" aria-label="Apps">
|
||||
<gaia-grid cols="4" text-rows="3" id="icons"></gaia-grid>
|
||||
</section>
|
||||
|
||||
<h2 id="places-header" class="hidden"><span data-l10n-id="history"></span></h2>
|
||||
<section id="places" class="local" data-l10n-id="places"
|
||||
aria-label="Places"></section>
|
||||
|
||||
<div id="suggestions-wrapper">
|
||||
<h2>
|
||||
<select id="suggestions-select"></select>
|
||||
<label for="suggestions-select" id="suggestions-provider"></label>
|
||||
<span id="suggestions-provider-dropdown"></span>
|
||||
</h2>
|
||||
|
||||
<div id="suggestions-notice-wrapper" hidden>
|
||||
<p data-l10n-id="suggestions-settings-notice">
|
||||
<span id="settings-link"></span>
|
||||
</p>
|
||||
<button id="suggestions-notice-confirm" data-l10n-id="ok"></button>
|
||||
</div>
|
||||
|
||||
<section id="suggestions"
|
||||
class="suggestions" data-l10n-id="suggestions"
|
||||
aria-label="Suggestions"></section>
|
||||
<div class="loading"><progress></progress></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<menu id="contextmenu" hidden>
|
||||
<menuitem id="add-to-homescreen" data-l10n-id="add-to-home-screen" type="button"></menuitem>
|
||||
</menu>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
92
gaia/apps/search/js/contextmenu.js
Executable file
|
|
@ -0,0 +1,92 @@
|
|||
'use strict';
|
||||
/* global MozActivity */
|
||||
/* global Bookmarks */
|
||||
|
||||
(function(exports) {
|
||||
|
||||
/**
|
||||
* The search context menu handles bookmarking of search
|
||||
* results when the users long presses them.
|
||||
*/
|
||||
function Contextmenu() {
|
||||
this.menu = document.getElementById('contextmenu');
|
||||
this.grid = document.getElementById('icons');
|
||||
|
||||
this.bookmarkButton = this.menu.querySelector('#add-to-homescreen');
|
||||
|
||||
this.grid.addEventListener('contextmenu', this);
|
||||
this.bookmarkButton.addEventListener('click', this);
|
||||
}
|
||||
|
||||
Contextmenu.prototype = {
|
||||
|
||||
/**
|
||||
* The current icon target.
|
||||
*/
|
||||
icon: null,
|
||||
|
||||
handleEvent: function(e) {
|
||||
switch(e.type) {
|
||||
case 'contextmenu':
|
||||
var identifier = e.target.dataset.identifier;
|
||||
var icon = this.grid.getIcon(identifier);
|
||||
|
||||
// Only show for bookmark targets
|
||||
if (!icon || icon.detail.type !== 'bookmark') {
|
||||
return;
|
||||
}
|
||||
|
||||
var url = icon.detail.url;
|
||||
if (Bookmarks.get(url)) {
|
||||
// Bookmark already installed in device
|
||||
return;
|
||||
}
|
||||
|
||||
// In order to benefit from the system contextmenu in such a way that
|
||||
// it overlaps search bar, let's create a contextmenu attribute on
|
||||
// the fly, and remove it once the event dispatching is done.
|
||||
e.target.setAttribute('contextmenu', 'contextmenu');
|
||||
|
||||
// Stop the grid from listening to events to prevent it from
|
||||
// receiving a touchend event and launching the icon. This is
|
||||
// restored on next tick.
|
||||
this.grid.stop();
|
||||
|
||||
setTimeout(() => {
|
||||
e.target.removeAttribute('contextmenu');
|
||||
this.grid.start();
|
||||
});
|
||||
|
||||
this.icon = icon;
|
||||
break;
|
||||
|
||||
case 'click':
|
||||
/* jshint nonew: false */
|
||||
/**
|
||||
* We could have several cases for icons in the search grid:
|
||||
* - Icons from e.me: this.icon.icon will be url
|
||||
* - Icons from places: this.icon.icon can be:
|
||||
* - a blob, cached icon
|
||||
* - a icon url
|
||||
* To solve this, added an extra feature attribute: iconUrl,
|
||||
* so GaiaGridItems with this extra attribute in the detail
|
||||
* will have a way to keep track of the original url.
|
||||
*/
|
||||
var iconUrl = this.icon.detail.iconUrl || this.icon.icon;
|
||||
new MozActivity({
|
||||
name: 'save-bookmark',
|
||||
data: {
|
||||
type: 'url',
|
||||
url: this.icon.detail.url,
|
||||
name: this.icon.name,
|
||||
icon: iconUrl
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.Contextmenu = Contextmenu;
|
||||
|
||||
}(window));
|
||||
197
gaia/apps/search/js/newtab.js
Executable file
|
|
@ -0,0 +1,197 @@
|
|||
'use strict';
|
||||
/* global asyncStorage, MozActivity, SettingsListener */
|
||||
|
||||
(function(exports) {
|
||||
|
||||
var isManuallyPrivate = window.location.search.includes('private=1');
|
||||
var isManuallyRegular = window.location.search.includes('private=0');
|
||||
var isPrivateByDefault = false;
|
||||
|
||||
SettingsListener.observe('browser.private.default', false, function (value) {
|
||||
if (value) {
|
||||
isPrivateByDefault = true;
|
||||
} else {
|
||||
isPrivateByDefault = false;
|
||||
}
|
||||
|
||||
exports.newtab.togglePrivacyMode();
|
||||
});
|
||||
|
||||
/**
|
||||
* The main Newtab page object.
|
||||
* Instantiates places to populate history and top sites.
|
||||
*/
|
||||
function Newtab() {
|
||||
// Initialize the parent port connection
|
||||
var self = this;
|
||||
navigator.mozApps.getSelf().onsuccess = function() {
|
||||
var app = this.result;
|
||||
app.connect('search-results').then(function onConnAccepted(ports) {
|
||||
ports.forEach(function(port) {
|
||||
self._port = port;
|
||||
});
|
||||
self.init();
|
||||
}, function onConnectionRejected(reason) {
|
||||
console.log('Error connecting: ' + reason + '\n');
|
||||
});
|
||||
};
|
||||
|
||||
this.togglePrivacyMode();
|
||||
}
|
||||
|
||||
Newtab.prototype = {
|
||||
|
||||
/**
|
||||
* A reference to the Places provider.
|
||||
*/
|
||||
provider: null,
|
||||
|
||||
/**
|
||||
* Initializes top sites and history.
|
||||
*/
|
||||
init: function() {
|
||||
this.provider.init();
|
||||
this.provider.searchObj = this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Requests a screenshot of the page from the system app.
|
||||
*/
|
||||
requestScreenshot: function(url) {
|
||||
this._port.postMessage({
|
||||
'action': 'request-screenshot',
|
||||
'url': url
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Requests that the system app opens a new private window.
|
||||
*/
|
||||
requestPrivateWindow: function() {
|
||||
this._port.postMessage({
|
||||
'action': 'private-window'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Toggles the privacy mode.
|
||||
*
|
||||
* When private browsing _IS_ the default and we _ARE NOT_ manually being
|
||||
* regular or when private browsing _IS NOT_ the default and we _ARE_
|
||||
* manually bring private: Makes this window look like a private window by
|
||||
* applying the necessary theme color and background. The window can't be
|
||||
* truly private, otherwise we wouldn't have access to local history and
|
||||
* bookmarks.
|
||||
*
|
||||
* When private browsing _IS_ the default and we _ARE_ manually regular:
|
||||
* Makes this window look normal by removing private theme settings.
|
||||
*/
|
||||
togglePrivacyMode: function() {
|
||||
var themeMeta = document.querySelector('meta[name="theme-color"]');
|
||||
var themeColor = document.createElement('meta');
|
||||
|
||||
if ((isPrivateByDefault && !isManuallyRegular) ||
|
||||
(!isPrivateByDefault && isManuallyPrivate)) {
|
||||
|
||||
if (themeMeta) {
|
||||
document.head.removeChild(themeMeta);
|
||||
}
|
||||
|
||||
themeColor.setAttribute('name', 'theme-color');
|
||||
themeColor.setAttribute('content', '#392E54');
|
||||
document.head.appendChild(themeColor);
|
||||
document.body.classList.add('private');
|
||||
|
||||
// Show the private dialog if needed.
|
||||
asyncStorage.getItem('shouldSuppressPrivateDialog', value => {
|
||||
if (value) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.privateBrowserDialog = document.getElementById(
|
||||
'private-window-dialog');
|
||||
this.privateBrowserDialog.removeAttribute('hidden');
|
||||
|
||||
this.privateBrowserDialogClose = document.getElementById(
|
||||
'private-window-hide-dialog');
|
||||
this.privateBrowserDialogClose.addEventListener('click', this);
|
||||
|
||||
this.privateBrowserLearnMore = document.getElementById(
|
||||
'private-learn-more');
|
||||
this.privateBrowserLearnMore.addEventListener('click', this);
|
||||
});
|
||||
}
|
||||
|
||||
if (isPrivateByDefault && isManuallyRegular) {
|
||||
if (themeMeta) {
|
||||
document.head.removeChild(themeMeta);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* General event handler.
|
||||
*/
|
||||
handleEvent: function(e) {
|
||||
switch(e.target) {
|
||||
case this.privateBrowserDialogClose:
|
||||
this.hidePrivateBrowserDialog();
|
||||
break;
|
||||
case this.privateBrowserLearnMore:
|
||||
this.learnAboutPrivateBrowsing(e);
|
||||
break;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Hides the private browser dialog.
|
||||
*/
|
||||
hidePrivateBrowserDialog: function() {
|
||||
this.privateBrowserDialog.setAttribute('hidden', true);
|
||||
|
||||
// Set async storage value if we have checked the box so we don't
|
||||
// attempt to show it again.
|
||||
var checkbox = this.privateBrowserDialog.querySelector('gaia-checkbox');
|
||||
if (checkbox.checked) {
|
||||
asyncStorage.setItem('shouldSuppressPrivateDialog', true);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Opens the learn more dialog.
|
||||
*/
|
||||
learnAboutPrivateBrowsing: function(e) {
|
||||
e.preventDefault();
|
||||
/* jshint nonew: false */
|
||||
new MozActivity({
|
||||
name: 'view',
|
||||
data: {
|
||||
type: 'url',
|
||||
url: e.target.href
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.newtab = new Newtab();
|
||||
|
||||
/**
|
||||
* Stub search object to populate providers.
|
||||
* TODO: We should split up the places provider into some data layer where
|
||||
* the search or newtab page could leverage it.
|
||||
*/
|
||||
exports.Search = {
|
||||
provider: function(provider) {
|
||||
exports.newtab.provider = provider;
|
||||
},
|
||||
|
||||
/**
|
||||
* Opens a browser to a URL.
|
||||
* @param {String} url The url to navigate to
|
||||
*/
|
||||
navigate: function(url) {
|
||||
new MozActivity({name:'view',data:{type:'url',url:url}});
|
||||
}
|
||||
};
|
||||
|
||||
})(window);
|
||||
180
gaia/apps/search/js/places_idb.js
Executable file
|
|
@ -0,0 +1,180 @@
|
|||
/* globals Promise, asyncStorage, IDBKeyRange */
|
||||
|
||||
(function(exports) {
|
||||
|
||||
'use strict';
|
||||
|
||||
var DB_NAME = 'places_idb_store';
|
||||
var DB_VERSION = 3;
|
||||
|
||||
var PLACES_STORE = 'places';
|
||||
var VISITS_STORE = 'visits';
|
||||
|
||||
function PlacesIdbStore() {}
|
||||
|
||||
PlacesIdbStore.prototype = {
|
||||
|
||||
db: null,
|
||||
|
||||
latestRevision: null,
|
||||
|
||||
init: function() {
|
||||
var self = this;
|
||||
return new Promise(function(resolve, reject) {
|
||||
var req = window.indexedDB.open(DB_NAME, DB_VERSION);
|
||||
req.onupgradeneeded = self.upgradeSchema;
|
||||
req.onsuccess = function(e) {
|
||||
self.db = e.target.result;
|
||||
asyncStorage.getItem('latest-revision', function(value) {
|
||||
self.latestRevision = value || 0;
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
upgradeSchema: function(e) {
|
||||
var db = e.target.result;
|
||||
var fromVersion = e.oldVersion;
|
||||
|
||||
if (fromVersion < 1) {
|
||||
var places = db.createObjectStore(PLACES_STORE, { keyPath: 'url' });
|
||||
places.createIndex('frecency', 'frecency', { unique: false });
|
||||
places.createIndex('visited', 'visited', { unique: false });
|
||||
}
|
||||
|
||||
if (fromVersion < 2) {
|
||||
asyncStorage.removeItem('latest-revision');
|
||||
var visits = db.createObjectStore(VISITS_STORE, { keyPath: 'date' });
|
||||
visits.createIndex('date', 'date', { unique: true });
|
||||
}
|
||||
|
||||
if (fromVersion < 3) {
|
||||
var oStore = e.target.transaction.objectStore(VISITS_STORE);
|
||||
oStore.createIndex('url', 'url', { unique: false });
|
||||
}
|
||||
},
|
||||
|
||||
add: function(id, data, rev) {
|
||||
return new Promise((resolve, reject) => {
|
||||
var txn = this.db
|
||||
.transaction([PLACES_STORE, VISITS_STORE], 'readwrite');
|
||||
|
||||
if (data.visits && data.visits.length === 0) {
|
||||
// Removed via browsing history clearing, let's remove it.
|
||||
this._removeUrl(id).then(this.saveAndResolve(rev, resolve));
|
||||
} else {
|
||||
txn.objectStore(PLACES_STORE).put(data);
|
||||
|
||||
if (!data.visits) {
|
||||
data.visits = Number.isFinite(data.visited) ? [data.visited] : [];
|
||||
}
|
||||
|
||||
var visitsStore = txn.objectStore(VISITS_STORE);
|
||||
data.visits.filter(Number.isFinite).forEach(function(date) {
|
||||
visitsStore.put({
|
||||
date: date,
|
||||
url: data.url,
|
||||
title: data.title,
|
||||
icons: data.icons
|
||||
});
|
||||
});
|
||||
|
||||
txn.oncomplete = this.saveAndResolve(rev, resolve);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
addPlace: function(place) {
|
||||
return new Promise((resolve, reject) => {
|
||||
var txn = this.db.transaction([PLACES_STORE], 'readwrite');
|
||||
txn.objectStore(PLACES_STORE).put(place);
|
||||
txn.oncomplete = resolve;
|
||||
});
|
||||
},
|
||||
|
||||
remove: function(id, rev) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this._removeUrl(id).then(this.saveAndResolve(rev, resolve));
|
||||
});
|
||||
},
|
||||
|
||||
_removeUrl: function(id) {
|
||||
return Promise.all([
|
||||
// Remove the url from places store.
|
||||
new Promise((resolve, reject) => {
|
||||
var txn = this.db.transaction([PLACES_STORE], 'readwrite');
|
||||
txn.objectStore(PLACES_STORE).delete(id);
|
||||
txn.oncomplete = resolve;
|
||||
}),
|
||||
|
||||
// Clear visits from this url.
|
||||
new Promise((resolve, reject) => {
|
||||
var txn = this.db.transaction([VISITS_STORE], 'readwrite');
|
||||
var visitsStore = txn.objectStore(VISITS_STORE);
|
||||
var urlIndex = visitsStore.index('url');
|
||||
var req = urlIndex.openCursor(IDBKeyRange.only(id));
|
||||
req.onsuccess = function() {
|
||||
var cursor = req.result;
|
||||
if (cursor) {
|
||||
visitsStore.delete(cursor.primaryKey);
|
||||
cursor.continue();
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
})
|
||||
]);
|
||||
},
|
||||
|
||||
clear: function(rev) {
|
||||
return new Promise((resolve, reject) => {
|
||||
var txn = this.db
|
||||
.transaction([PLACES_STORE, VISITS_STORE], 'readwrite');
|
||||
txn.objectStore(PLACES_STORE).clear();
|
||||
txn.objectStore(VISITS_STORE).clear();
|
||||
txn.oncomplete = this.saveAndResolve(rev, resolve);
|
||||
});
|
||||
},
|
||||
|
||||
saveAndResolve: function(rev, resolve) {
|
||||
return function() {
|
||||
asyncStorage.setItem('latest-revision', rev);
|
||||
resolve();
|
||||
};
|
||||
},
|
||||
|
||||
readStore: function(store, index, limit, done, filter) {
|
||||
var results = [];
|
||||
var txn = this.db.transaction(store, 'readonly');
|
||||
var oStore = txn.objectStore(store);
|
||||
|
||||
oStore.index(index).openCursor(null, 'prev').onsuccess = function(event) {
|
||||
var cursor = event.target.result;
|
||||
if (cursor) {
|
||||
if (!filter || filter(cursor.value)) {
|
||||
results.push(cursor.value);
|
||||
}
|
||||
if (results.length < limit) {
|
||||
cursor.continue();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
txn.oncomplete = function() {
|
||||
done(results);
|
||||
};
|
||||
},
|
||||
|
||||
read: function(index, limit, done, filter) {
|
||||
this.readStore(PLACES_STORE, index, limit, done, filter);
|
||||
},
|
||||
|
||||
readVisits: function(limit, done, filter) {
|
||||
this.readStore(VISITS_STORE, 'date', limit, done, filter);
|
||||
}
|
||||
};
|
||||
|
||||
exports.PlacesIdbStore = PlacesIdbStore;
|
||||
|
||||
})(window);
|
||||
72
gaia/apps/search/js/providers/bookmarks.js
Executable file
|
|
@ -0,0 +1,72 @@
|
|||
/* globals DataGridProvider, GaiaGrid, Search,
|
||||
Promise, SyncDataStore, InMemoryStore */
|
||||
|
||||
(function(exports) {
|
||||
|
||||
'use strict';
|
||||
|
||||
var STORE_NAME = 'bookmarks_store';
|
||||
|
||||
function formatBookmark(bookmark) {
|
||||
return {
|
||||
data: new GaiaGrid.Bookmark({
|
||||
id: bookmark.url,
|
||||
name: bookmark.name || bookmark.url,
|
||||
url: bookmark.url,
|
||||
icon: bookmark.icon
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function Bookmarks() {}
|
||||
|
||||
Bookmarks.prototype = {
|
||||
|
||||
__proto__: DataGridProvider.prototype,
|
||||
|
||||
name: 'Bookmarks',
|
||||
|
||||
init: function() {
|
||||
DataGridProvider.prototype.init.apply(this, arguments);
|
||||
this.persistStore = new InMemoryStore();
|
||||
this.syncStore = new SyncDataStore(STORE_NAME, this.persistStore, 'url');
|
||||
return this.syncStore.sync();
|
||||
},
|
||||
|
||||
get: function(url) {
|
||||
var results = this.persistStore.results;
|
||||
|
||||
for (var idx in results) {
|
||||
var item = results[idx];
|
||||
if (item.url === url) {
|
||||
return formatBookmark(item);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
|
||||
search: function(filter) {
|
||||
var self = this;
|
||||
return new Promise(function(resolve, reject) {
|
||||
var renderResults = [];
|
||||
filter = filter.toLowerCase();
|
||||
for(var elem in self.persistStore.results) {
|
||||
var bookmark = self.persistStore.results[elem];
|
||||
var name = ('name' in bookmark) && bookmark.name.toLowerCase();
|
||||
if ((!bookmark.url || bookmark.url.indexOf(filter) == -1) &&
|
||||
(!name || name.indexOf(filter) == -1)) {
|
||||
continue;
|
||||
}
|
||||
renderResults.push(formatBookmark(bookmark));
|
||||
}
|
||||
resolve(renderResults);
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
exports.Bookmarks = new Bookmarks();
|
||||
Search.provider(exports.Bookmarks);
|
||||
|
||||
}(window));
|
||||
77
gaia/apps/search/js/providers/contacts.js
Executable file
|
|
@ -0,0 +1,77 @@
|
|||
(function() {
|
||||
|
||||
'use strict';
|
||||
/* global MozActivity, Promise, Provider, Search */
|
||||
|
||||
function Contacts() {
|
||||
}
|
||||
|
||||
Contacts.prototype = {
|
||||
|
||||
__proto__: Provider.prototype,
|
||||
|
||||
name: 'Contacts',
|
||||
|
||||
click: function(e) {
|
||||
var target = e.target;
|
||||
|
||||
Search.close();
|
||||
/* jshint nonew: false */
|
||||
new MozActivity({
|
||||
name: 'open',
|
||||
data: {
|
||||
type: 'webcontacts/contact',
|
||||
params: {
|
||||
'id': target.dataset.contactId
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
search: function(input) {
|
||||
return new Promise((resolve, reject) => {
|
||||
var options = {
|
||||
filterValue: input,
|
||||
filterBy: ['givenName'],
|
||||
filterOp: 'startsWith'
|
||||
};
|
||||
|
||||
this.clear();
|
||||
|
||||
var request = navigator.mozContacts.find(options);
|
||||
request.onsuccess = (function() {
|
||||
var results = request.result;
|
||||
if (!results.length) {
|
||||
return reject();
|
||||
}
|
||||
|
||||
var renderResults = [];
|
||||
for (var i = 0; i < results.length; i++) {
|
||||
var result = results[i];
|
||||
for (var j = 0; j < result.name.length; j++) {
|
||||
var renderObj = {
|
||||
title: result.name[j],
|
||||
dataset: {
|
||||
contactId: result.id
|
||||
}
|
||||
};
|
||||
|
||||
if (result.photo) {
|
||||
renderObj.icon = result.photo[0];
|
||||
}
|
||||
|
||||
renderResults.push(renderObj);
|
||||
}
|
||||
}
|
||||
resolve(renderResults);
|
||||
}).bind(this);
|
||||
|
||||
request.onerror = function() {
|
||||
};
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Search.provider(new Contacts());
|
||||
|
||||
}());
|
||||
33
gaia/apps/search/js/providers/grid_provider.js
Executable file
|
|
@ -0,0 +1,33 @@
|
|||
/* global Provider */
|
||||
|
||||
'use strict';
|
||||
|
||||
function DataGridProvider() {
|
||||
}
|
||||
|
||||
DataGridProvider.prototype = {
|
||||
|
||||
__proto__: Provider.prototype,
|
||||
|
||||
name: 'DataGridProvider',
|
||||
|
||||
isGridProvider: true,
|
||||
|
||||
init: function() {
|
||||
this.grid = document.getElementById('icons');
|
||||
},
|
||||
|
||||
clear: function() {
|
||||
this.grid.clear();
|
||||
},
|
||||
|
||||
render: function(results) {
|
||||
results.forEach(function(config, index) {
|
||||
this.grid.add(config.data);
|
||||
}, this);
|
||||
|
||||
this.grid.render({
|
||||
skipDivider: true
|
||||
});
|
||||
}
|
||||
};
|
||||
170
gaia/apps/search/js/providers/local_apps.js
Executable file
|
|
@ -0,0 +1,170 @@
|
|||
/* global Search, DataGridProvider, GaiaGrid, Promise */
|
||||
|
||||
(function() {
|
||||
|
||||
'use strict';
|
||||
|
||||
function LocalApps() {
|
||||
this.apps = {};
|
||||
this.appListing = [];
|
||||
this.blacklist;
|
||||
|
||||
var mozApps = navigator.mozApps.mgmt;
|
||||
|
||||
mozApps.oninstall = e => {
|
||||
var app = e.application;
|
||||
var processApp = () => {
|
||||
this.apps[app.manifestURL] = app;
|
||||
this.createAppListing();
|
||||
};
|
||||
|
||||
if (app.downloading) {
|
||||
app.ondownloadapplied = processApp;
|
||||
} else {
|
||||
processApp();
|
||||
}
|
||||
};
|
||||
|
||||
mozApps.onuninstall = e => {
|
||||
delete this.apps[e.application.manifestURL];
|
||||
this.createAppListing();
|
||||
};
|
||||
|
||||
mozApps.getAll().onsuccess = e => {
|
||||
e.target.result.forEach(app => {
|
||||
this.apps[app.manifestURL] = app;
|
||||
});
|
||||
this.createBlacklist().then(() => {
|
||||
this.createAppListing();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
LocalApps.prototype = {
|
||||
|
||||
__proto__: DataGridProvider.prototype,
|
||||
|
||||
name: 'LocalApps',
|
||||
|
||||
dedupes: true,
|
||||
dedupeStrategy: 'exact',
|
||||
|
||||
createBlacklist: function() {
|
||||
return new Promise((resolve, reject) => {
|
||||
var self = this;
|
||||
var key = 'app.launch_path.blacklist';
|
||||
var req = navigator.mozSettings.createLock().get(key);
|
||||
req.onsuccess = function onsuccess() {
|
||||
self.blacklist = req.result[key] || [];
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
createAppListing: function() {
|
||||
var appListing = [];
|
||||
var blacklist = this.blacklist;
|
||||
|
||||
var manifestURLs = Object.keys(this.apps);
|
||||
|
||||
manifestURLs.forEach(function eachManifest(manifestURL) {
|
||||
var app = this.apps[manifestURL];
|
||||
var manifest = app.manifest || app.updateManifest;
|
||||
|
||||
var HIDDEN_ROLES = [
|
||||
'system', 'input', 'homescreen', 'search', 'theme', 'addon',
|
||||
'langpack'
|
||||
];
|
||||
if (HIDDEN_ROLES.indexOf(manifest.role) !== -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
var entryPoints = manifest.entry_points;
|
||||
if (entryPoints) {
|
||||
for (var i in entryPoints) {
|
||||
var entry = entryPoints[i];
|
||||
entry.entryPoint = i;
|
||||
entry.manifestURL = app.manifestURL;
|
||||
appListing.push(entry);
|
||||
}
|
||||
} else {
|
||||
manifest.manifestURL = app.manifestURL;
|
||||
appListing.push(manifest);
|
||||
}
|
||||
|
||||
if (blacklist) {
|
||||
blacklist.forEach(function(blackentry) {
|
||||
for (var i in appListing) {
|
||||
var app = appListing[i];
|
||||
if (app.launch_path === blackentry) {
|
||||
appListing.splice(i, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}, this);
|
||||
|
||||
this.appListing = appListing;
|
||||
},
|
||||
|
||||
removeAppListing: function(app) {
|
||||
for (var i in this.appListing) {
|
||||
var manifest = this.appListing[i];
|
||||
if (manifest.manifestURL === app.manifestURL) {
|
||||
this.appListing.splice(i, 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
search: function(input) {
|
||||
return new Promise((resolve, reject) => {
|
||||
var results = this.find(input);
|
||||
var formatted = [];
|
||||
|
||||
results.forEach(function eachResult(result) {
|
||||
formatted.push({
|
||||
dedupeId: result.app.manifestURL,
|
||||
data: new GaiaGrid.Mozapp(result.app, result.entryPoint)
|
||||
});
|
||||
}, this);
|
||||
|
||||
resolve(formatted);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks if an app manifest matches a query.
|
||||
*/
|
||||
matches: function(manifest, query) {
|
||||
query = query.toLowerCase();
|
||||
|
||||
// Get the localized name from the query.
|
||||
var shortName = manifest.short_name || '';
|
||||
var userLang = document.documentElement.lang;
|
||||
var locales = manifest.locales;
|
||||
var localized = locales && locales[userLang] && locales[userLang].name;
|
||||
localized = localized || '';
|
||||
|
||||
return shortName.toLowerCase().indexOf(query) != -1 ||
|
||||
manifest.name.toLowerCase().indexOf(query) != -1 ||
|
||||
localized.toLowerCase().indexOf(query) != -1;
|
||||
},
|
||||
|
||||
find: function(query) {
|
||||
var results = [];
|
||||
this.appListing.forEach(function(manifest) {
|
||||
if (this.matches(manifest, query)) {
|
||||
results.push({
|
||||
app: this.apps[manifest.manifestURL],
|
||||
entryPoint: manifest.entryPoint
|
||||
});
|
||||
}
|
||||
}, this);
|
||||
|
||||
return results;
|
||||
}
|
||||
};
|
||||
|
||||
Search.provider(new LocalApps());
|
||||
|
||||
}());
|
||||
85
gaia/apps/search/js/providers/marketplace.js
Executable file
|
|
@ -0,0 +1,85 @@
|
|||
/* global Search, DataGridProvider, GaiaGrid, Promise */
|
||||
|
||||
(function() {
|
||||
|
||||
'use strict';
|
||||
|
||||
const NUM_DISPLAY = 4;
|
||||
var apiUrl = null;
|
||||
|
||||
function Marketplace() {}
|
||||
|
||||
Marketplace.prototype = {
|
||||
|
||||
__proto__: DataGridProvider.prototype,
|
||||
|
||||
name: 'Marketplace',
|
||||
|
||||
dedupes: true,
|
||||
dedupeStrategy: 'exact',
|
||||
remote: true,
|
||||
|
||||
init: function() {
|
||||
|
||||
DataGridProvider.prototype.init.apply(this, arguments);
|
||||
var urlKey = 'search.marketplace.url';
|
||||
var req = navigator.mozSettings.createLock().get(urlKey);
|
||||
req.onsuccess = function () {
|
||||
if (req.result[urlKey]) {
|
||||
apiUrl = req.result[urlKey]
|
||||
.replace('{limit}', NUM_DISPLAY)
|
||||
.replace('{lang}', document.documentElement.lang);
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
search: function(input) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.abort();
|
||||
|
||||
if (!input || !apiUrl) {
|
||||
return resolve([]);
|
||||
}
|
||||
|
||||
var req = new XMLHttpRequest();
|
||||
req.open('GET', apiUrl.replace('{q}', encodeURIComponent(input)), true);
|
||||
req.onload = (function onload() {
|
||||
var results = JSON.parse(req.responseText);
|
||||
if (!results.length) {
|
||||
resolve([]); return;
|
||||
}
|
||||
|
||||
var length = Math.min(NUM_DISPLAY, results.length);
|
||||
var formatted = [];
|
||||
for (var i = 0; i < length; i++) {
|
||||
var app = results[i];
|
||||
formatted.push({
|
||||
dedupeId: app.manifest_url,
|
||||
data: new GaiaGrid.MarketPlaceApp({
|
||||
id: app.manifest_url,
|
||||
name: navigator.mozL10n.get('install-marketplace-title', {
|
||||
title: app.name
|
||||
}),
|
||||
icons: app.icons,
|
||||
slug: app.slug
|
||||
})
|
||||
});
|
||||
}
|
||||
resolve(formatted);
|
||||
}).bind(this);
|
||||
req.onerror = function onerror() {
|
||||
console.log('Marketplace error.');
|
||||
reject();
|
||||
};
|
||||
req.ontimeout = function ontimeout() {
|
||||
console.log('Marketplace timeout.');
|
||||
reject();
|
||||
};
|
||||
req.send();
|
||||
this.request = req;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Search.provider(new Marketplace());
|
||||
}());
|
||||
400
gaia/apps/search/js/providers/places.js
Executable file
|
|
@ -0,0 +1,400 @@
|
|||
/* globals Provider, SyncDataStore, Promise, IconsHelper */
|
||||
/* globals Search, PlacesIdbStore */
|
||||
/* globals DateHelper */
|
||||
/* globals asyncStorage */
|
||||
/* globals LazyLoader */
|
||||
(function(exports) {
|
||||
|
||||
'use strict';
|
||||
|
||||
var _ = navigator.mozL10n.get;
|
||||
|
||||
// Maximum number of results to show show for a single query
|
||||
var MAX_AWESOME_RESULTS = 4;
|
||||
var MAX_HISTORY_RESULTS = 20;
|
||||
var MAX_TOPSITES_RESULTS = 6;
|
||||
|
||||
// Name of the datastore we pick up places from
|
||||
var STORE_NAME = 'places';
|
||||
|
||||
var topSitesWrapper = document.getElementById('top-sites');
|
||||
var historyWrapper = document.getElementById('history');
|
||||
|
||||
// These elements are only included in the newtab page.
|
||||
if (topSitesWrapper && historyWrapper) {
|
||||
topSitesWrapper.addEventListener('click', itemClicked);
|
||||
historyWrapper.addEventListener('click', itemClicked);
|
||||
}
|
||||
|
||||
var cachedLink = document.createElement('a');
|
||||
function parseUrl(url) {
|
||||
cachedLink.href = url;
|
||||
return cachedLink;
|
||||
}
|
||||
|
||||
// Storage for locally fetched icons
|
||||
var icons = {};
|
||||
var iconUrls = {};
|
||||
|
||||
function getIcon(place) {
|
||||
|
||||
if (place.url in icons && icons[place.url]) {
|
||||
return icons[place.url];
|
||||
}
|
||||
|
||||
IconsHelper.getIcon(place.url, null, place).then(icon => {
|
||||
saveIcon(place.url, icon);
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function saveIcon(key, url) {
|
||||
if (key in icons) {
|
||||
return;
|
||||
}
|
||||
icons[key] = null;
|
||||
iconUrls[key] = url;
|
||||
fetchIcon(url, function(err, icon) {
|
||||
if (!err) {
|
||||
icons[key] = icon;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function fetchIcon(uri, callback) {
|
||||
var xhr = new XMLHttpRequest({mozSystem: true});
|
||||
xhr.open('GET', uri, true);
|
||||
xhr.responseType = 'blob';
|
||||
xhr.addEventListener('load', function() {
|
||||
// Check icon was successfully downloded
|
||||
// 0 is due to https://bugzilla.mozilla.org/show_bug.cgi?id=716491
|
||||
if (!(xhr.status === 200 || xhr.status === 0)) {
|
||||
return callback(new Error('error_downloading'));
|
||||
}
|
||||
|
||||
var blob = xhr.response;
|
||||
|
||||
if (blob.size > this.MAX_ICON_SIZE) {
|
||||
return callback(new Error('image_to_large'));
|
||||
}
|
||||
|
||||
// Only save the icon if it can be loaded as an image bigger than 0px
|
||||
var img = document.createElement('img');
|
||||
img.src = window.URL.createObjectURL(blob);
|
||||
|
||||
img.onload = function() {
|
||||
window.URL.revokeObjectURL(img.src);
|
||||
if (img.naturalWidth <= 0) {
|
||||
return callback(new Error('Cannot load image'));
|
||||
}
|
||||
callback(null, blob);
|
||||
};
|
||||
|
||||
img.onerror = function() {
|
||||
window.URL.revokeObjectURL(img.src);
|
||||
return callback(new Error('Cannot load image'));
|
||||
};
|
||||
});
|
||||
|
||||
xhr.onerror = function(err) {
|
||||
return callback(new Error('Cannot load uri'));
|
||||
};
|
||||
xhr.send();
|
||||
}
|
||||
|
||||
function itemClicked(e) {
|
||||
if (e.target.dataset.url) {
|
||||
Search.navigate(e.target.dataset.url);
|
||||
}
|
||||
}
|
||||
|
||||
var listTemplate = createList();
|
||||
|
||||
function createList() {
|
||||
var list = document.createElement('ul');
|
||||
list.setAttribute('role', 'listbox');
|
||||
return list;
|
||||
}
|
||||
|
||||
function incrementHistoryThreshold(timestamp, currentThreshold, thresholds) {
|
||||
var newThreshold = currentThreshold += 1;
|
||||
if (timestamp < thresholds[newThreshold]) {
|
||||
return incrementHistoryThreshold(timestamp, newThreshold, thresholds);
|
||||
}
|
||||
return newThreshold;
|
||||
}
|
||||
|
||||
function drawHistoryHeading(parent, threshold, timestamp) {
|
||||
|
||||
var LABELS = [
|
||||
'future',
|
||||
'today',
|
||||
'yesterday',
|
||||
'last-7-days',
|
||||
'this-month',
|
||||
'last-6-months',
|
||||
'older-than-6-months'
|
||||
];
|
||||
|
||||
var text = '';
|
||||
|
||||
// Special case for month headings
|
||||
if (threshold == 5 && timestamp) {
|
||||
var date = new Date(timestamp);
|
||||
var now = new Date();
|
||||
text = _('month-' + date.getMonth());
|
||||
if (date.getFullYear() != now.getFullYear()) {
|
||||
text += ' ' + date.getFullYear();
|
||||
}
|
||||
} else {
|
||||
text = _(LABELS[threshold]);
|
||||
}
|
||||
|
||||
var h3 = document.createElement('h3');
|
||||
var spanNode = document.createElement('span');
|
||||
spanNode.textContent = text;
|
||||
var ul = listTemplate.cloneNode(true);
|
||||
h3.appendChild(spanNode);
|
||||
parent.appendChild(h3);
|
||||
parent.appendChild(ul);
|
||||
}
|
||||
|
||||
function updateIcon(visit, iconWrapper) {
|
||||
var iconDom = iconWrapper.querySelector('img');
|
||||
IconsHelper.getIcon(visit.url, null, visit).then((icon) => {
|
||||
if (icon && iconDom) {
|
||||
iconDom.onload = function () {
|
||||
iconWrapper.classList.remove('empty');
|
||||
iconDom.style.display = 'block';
|
||||
};
|
||||
iconDom.src = icon;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildHistory(visits) {
|
||||
|
||||
var thresholds = [
|
||||
Date.now(), // 0. Now
|
||||
DateHelper.todayStarted(), // 1. Today
|
||||
DateHelper.yesterdayStarted(), // 2. Yesterday
|
||||
DateHelper.thisWeekStarted(), // 3. This week
|
||||
DateHelper.thisMonthStarted(), // 4. This month
|
||||
DateHelper.lastSixMonthsStarted(), // 5. Six months
|
||||
0 // 6. Epoch!
|
||||
];
|
||||
|
||||
var threshold = 0;
|
||||
var month = null;
|
||||
var year = null;
|
||||
|
||||
var fragment = document.createDocumentFragment();
|
||||
|
||||
visits.forEach(function(visit) {
|
||||
// Draw new heading if new threshold reached
|
||||
if (visit.date > 0 && visit.date < thresholds[threshold]) {
|
||||
threshold = incrementHistoryThreshold(visit.date,
|
||||
threshold, thresholds);
|
||||
// Special case for month headings
|
||||
if (threshold != 5) {
|
||||
drawHistoryHeading(fragment, threshold);
|
||||
}
|
||||
}
|
||||
|
||||
if (threshold === 5) {
|
||||
var timestampDate = new Date(visit.date);
|
||||
if (timestampDate.getMonth() != month ||
|
||||
timestampDate.getFullYear() != year) {
|
||||
month = timestampDate.getMonth();
|
||||
year = timestampDate.getFullYear();
|
||||
drawHistoryHeading(fragment, threshold, visit.date);
|
||||
}
|
||||
}
|
||||
|
||||
visit.meta = visit.url;
|
||||
visit.dataset = { url: visit.url };
|
||||
var dom = exports.Places.buildResultsDom([visit]);
|
||||
var iconDom = dom.querySelector('.icon');
|
||||
fragment.appendChild(dom);
|
||||
updateIcon(visit, iconDom);
|
||||
});
|
||||
|
||||
return fragment;
|
||||
}
|
||||
|
||||
function showStartPage() {
|
||||
|
||||
if (!topSitesWrapper || !historyWrapper) {
|
||||
return;
|
||||
}
|
||||
|
||||
var store = exports.Places.persistStore;
|
||||
|
||||
var urls = [];
|
||||
store.readVisits(MAX_HISTORY_RESULTS, function(results) {
|
||||
var docFragment = buildHistory(results);
|
||||
historyWrapper.innerHTML = '';
|
||||
historyWrapper.appendChild(docFragment);
|
||||
}, function filter(visit) {
|
||||
var isStored = visit.url in urls;
|
||||
urls[visit.url] = true;
|
||||
return !isStored;
|
||||
});
|
||||
|
||||
store.read('frecency', MAX_TOPSITES_RESULTS, function(results) {
|
||||
var docFragment = document.createDocumentFragment();
|
||||
results.forEach(function(x) {
|
||||
docFragment.appendChild(formatTopResult(x));
|
||||
});
|
||||
topSitesWrapper.innerHTML = '';
|
||||
topSitesWrapper.appendChild(docFragment);
|
||||
});
|
||||
}
|
||||
|
||||
function formatTopResult(result) {
|
||||
var div = document.createElement('div');
|
||||
var span = document.createElement('span');
|
||||
if (result.title) {
|
||||
span.setAttribute('dir', 'auto');
|
||||
span.textContent = result.title;
|
||||
} else {
|
||||
span.setAttribute('dir', 'ltr');
|
||||
span.textContent = result.url;
|
||||
}
|
||||
div.dataset.url = result.url;
|
||||
div.classList.add('top-site');
|
||||
div.appendChild(span);
|
||||
div.setAttribute('role', 'link');
|
||||
|
||||
if (result.screenshot || result.tile) {
|
||||
var img = result.screenshot || result.tile;
|
||||
var imgUrl = (typeof img === 'string') ? img : URL.createObjectURL(img);
|
||||
div.style.backgroundImage = 'url(' + imgUrl + ')';
|
||||
}
|
||||
|
||||
return div;
|
||||
}
|
||||
|
||||
function matchesFilter(value, filter) {
|
||||
return !filter || (value && value.match(new RegExp(filter, 'i')) !== null);
|
||||
}
|
||||
|
||||
function formatPlace(placeObj, filter) {
|
||||
|
||||
var result = {
|
||||
'title': placeObj.title,
|
||||
'meta': placeObj.url,
|
||||
'icon': getIcon(placeObj),
|
||||
'dataset': {
|
||||
'url': placeObj.url
|
||||
},
|
||||
'label': placeObj.title
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function Places() {}
|
||||
|
||||
Places.prototype = {
|
||||
|
||||
__proto__: Provider.prototype,
|
||||
|
||||
name: 'Places',
|
||||
|
||||
click: itemClicked,
|
||||
|
||||
init: function() {
|
||||
|
||||
// If not on new tab page, set places div as container
|
||||
if (!topSitesWrapper || !historyWrapper) {
|
||||
this.header = document.getElementById(this.name.toLowerCase() +
|
||||
'-header');
|
||||
this.container = document.getElementById(this.name.toLowerCase());
|
||||
this.container.addEventListener('click', this.click.bind(this));
|
||||
}
|
||||
|
||||
this.persistStore = new PlacesIdbStore();
|
||||
|
||||
this.persistStore.init().then(() => {
|
||||
|
||||
this.syncStore =
|
||||
new SyncDataStore(STORE_NAME, this.persistStore, 'url');
|
||||
|
||||
this.syncStore.filter = function(place) {
|
||||
return place.url.startsWith('app://') ||
|
||||
place.url === 'about:blank';
|
||||
};
|
||||
this.syncStore.onChange = function() {
|
||||
showStartPage();
|
||||
};
|
||||
// Make init return a promise, so we know when
|
||||
// we did the sync. Used right now for testing
|
||||
// porpoises.
|
||||
var rev = this.persistStore.latestRevision || 0;
|
||||
return this.syncStore.sync(rev).then(() => {
|
||||
return new Promise(resolve => {
|
||||
|
||||
function done() {
|
||||
showStartPage();
|
||||
resolve();
|
||||
}
|
||||
|
||||
asyncStorage.getItem('have-preloaded-sites', (havePreloaded) => {
|
||||
if (!havePreloaded) {
|
||||
this.preloadTopSites().then(() => {
|
||||
asyncStorage.setItem('have-preloaded-sites', true);
|
||||
done();
|
||||
});
|
||||
} else {
|
||||
done();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
saveSites: function(sites) {
|
||||
return Promise.all(sites.map(site => {
|
||||
site.frecency = -2;
|
||||
return this.persistStore.addPlace(site);
|
||||
}));
|
||||
},
|
||||
|
||||
preloadTopSites: function() {
|
||||
// load default build top sites
|
||||
return LazyLoader.getJSON('/js/inittopsites.json').then(sites => {
|
||||
return this.saveSites(sites);
|
||||
});
|
||||
},
|
||||
|
||||
search: function(filter) {
|
||||
return new Promise((resolve, reject) => {
|
||||
var matchedOrigins = {};
|
||||
this.persistStore.read('frecency', MAX_AWESOME_RESULTS, (results) => {
|
||||
resolve(results.map(function(result) {
|
||||
return formatPlace(result, filter);
|
||||
}));
|
||||
}, function filterFun(result) {
|
||||
if (result.frecency <= 0) {
|
||||
return false;
|
||||
}
|
||||
var url = parseUrl(result.url);
|
||||
var matches = !(url.hostname in matchedOrigins) &&
|
||||
(matchesFilter(result.title, filter) ||
|
||||
matchesFilter(result.url, filter));
|
||||
if (matches) {
|
||||
matchedOrigins[url.hostname] = true;
|
||||
}
|
||||
return matches;
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.Places = new Places();
|
||||
Search.provider(exports.Places);
|
||||
|
||||
}(window));
|
||||