Merge remote-tracking branch 'origin/main' into main

This commit is contained in:
Hosted Weblate 2021-04-08 16:43:49 +02:00
commit ffe06fdeaa
6 changed files with 14819 additions and 3401 deletions

View file

@ -5,13 +5,12 @@
colSpan="2" colSpan="2"
rowSpan="2" rowSpan="2"
class="options-list" class="options-list"
@loaded="listViewLoad"
for="item in items" for="item in items"
> >
<v-template if="$index == 0"> <v-template if="$index == 0">
<Label class="pageTitle" :text="'db' | L" /> <Label class="pageTitle" :text="'db' | L" />
</v-template> </v-template>
<v-template if="$index == 3"> <v-template if="$index == 4">
<StackLayout class="listSpace"> </StackLayout> <StackLayout class="listSpace"> </StackLayout>
</v-template> </v-template>
<v-template> <v-template>
@ -21,19 +20,42 @@
@touch="touch($event, item.action)" @touch="touch($event, item.action)"
> >
<Label class="ico" :text="icon[item.icon]" /> <Label class="ico" :text="icon[item.icon]" />
<StackLayout col="1"> <StackLayout col="1" verticalAlignment="center">
<Label :text="item.title | L" class="info" /> <Label :text="item.title | L" class="info" />
<Label :text="item.subTitle | L" class="sub" /> <Label v-if="item.subTitle" :text="item.subTitle" class="sub" />
</StackLayout> </StackLayout>
</GridLayout> </GridLayout>
</v-template> </v-template>
</ListView> </ListView>
<GridLayout row="1" class="appbar" rows="*" columns="auto, *"> <GridLayout
<Button v-show="!toast && !backupProgress"
class="ico" row="1"
:text="icon.back" class="appbar"
@tap="$navigateBack()" rows="*"
/> columns="auto, *"
>
<Button class="ico" :text="icon.back" @tap="$navigateBack()" />
</GridLayout>
<GridLayout
v-show="toast"
row="1"
colSpan="2"
class="appbar snackBar"
columns="*"
@tap="toast = null"
>
<FlexboxLayout minHeight="48" alignItems="center">
<Label class="title msg" :text="toast" />
</FlexboxLayout>
</GridLayout>
<GridLayout
v-show="backupProgress"
row="1"
colSpan="2"
class="appbar snackBar"
columns="*"
>
<Progress :value="backupProgress" maxValue="100" />
</GridLayout> </GridLayout>
</GridLayout> </GridLayout>
</Page> </Page>
@ -47,10 +69,11 @@ import {
File, File,
Folder, Folder,
Observable, Observable,
Application,
} from "@nativescript/core"; } from "@nativescript/core";
import * as Permissions from "@nativescript-community/perms"; import * as Permissions from "@nativescript-community/perms";
import { Zip } from "@nativescript/zip"; import { Zip } from "@nativescript/zip";
// import * as Filepicker from "nativescript-plugin-filepicker"; import { openFilePicker } from "@nativescript-community/ui-document-picker";
import { localize } from "@nativescript/localize"; import { localize } from "@nativescript/localize";
import ConfirmDialog from "../modal/ConfirmDialog.vue"; import ConfirmDialog from "../modal/ConfirmDialog.vue";
import { mapState, mapActions } from "vuex"; import { mapState, mapActions } from "vuex";
@ -60,8 +83,9 @@ import * as utils from "~/shared/utils";
export default { export default {
data() { data() {
return { return {
backupFolder: null,
backupProgress: 0, backupProgress: 0,
backupInProgress: false, toast: null,
}; };
}, },
computed: { computed: {
@ -78,17 +102,24 @@ export default {
items() { items() {
return [ return [
{}, {},
{
icon: "folder",
title: "Backup folder",
subTitle: this.backupFolder,
action: this.setBackupFolder,
},
{ {
icon: "exp", icon: "exp",
title: "expBu", title: "expBu",
subTitle: "buInfo", subTitle: localize("buInfo"),
action: this.exportCheck, action: this.exportCheck,
}, },
{ {
icon: "imp", icon: "imp",
title: "impBu", title: "impBu",
subTitle: "impInfo", subTitle: localize("impInfo"),
action: this.importCheck, // action: this.importCheck,
action: this.openZipFile,
}, },
{}, {},
]; ];
@ -104,11 +135,30 @@ export default {
onPageLoad(args) { onPageLoad(args) {
const page = args.object; const page = args.object;
page.bindingContext = new Observable(); page.bindingContext = new Observable();
const downloadsFolder = Folder.fromPath(
android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
).getFolder("Download").path;
this.backupFolder = ApplicationSettings.getString(
"backupFolder",
downloadsFolder
);
},
// BACKUP FOLDER PICKER
setBackupFolder() {
utils.pickFolder().then((res) => {
if (res != null) {
this.backupFolder = res;
ApplicationSettings.setString("backupFolder", this.backupFolder);
}
});
}, },
// EXPORT HANDLERS // EXPORT HANDLERS
exportCheck() { exportCheck() {
if (!this.recipes.length) { if (!this.recipes.length) {
// Toast.makeText(localize("aFBu")).show(); this.toast = localize("aFBu");
utils.timer(5, (val) => {
if (!val) this.toast = val;
});
} else { } else {
this.permissionCheck( this.permissionCheck(
this.permissionConfirmation, this.permissionConfirmation,
@ -130,28 +180,19 @@ export default {
("0" + date.getHours()).slice(-2) + ("0" + date.getHours()).slice(-2) +
("0" + date.getMinutes()).slice(-2) + ("0" + date.getMinutes()).slice(-2) +
("0" + date.getSeconds()).slice(-2); ("0" + date.getSeconds()).slice(-2);
const sdDownloadPath = Folder.fromPath(
android.os.Environment.getExternalStorageDirectory().getAbsolutePath() let filename = `EnRecipes_${formattedDate}.zip`;
).getFolder("Download").path;
let fromPath = path.join(knownFolders.documents().path, "EnRecipes"); let fromPath = path.join(knownFolders.documents().path, "EnRecipes");
let destPath = path.join( let sdcard = android.os.Environment.isExternalStorageManager();
sdDownloadPath, let destPath = path.join(this.backupFolder, filename);
`EnRecipes-Backup_${formattedDate}.zip` console.log(sdcard);
);
this.backupInProgress = true;
Zip.zip({ Zip.zip({
directory: fromPath, directory: fromPath,
archive: destPath, archive: destPath,
onProgress: (progress) => { onProgress: (progress) => (this.backupProgress = progress),
this.backupProgress = progress; }).then(() => {
}, this.showExportSummary(filename);
}).then((success) => {
// Toast.makeText(
// "Backup file successfully saved to Download folder",
// "long"
// ).show();
this.exportFiles("delete"); this.exportFiles("delete");
setTimeout((e) => (this.backupInProgress = false), 3000);
}); });
}, },
exportFiles(option) { exportFiles(option) {
@ -211,20 +252,63 @@ export default {
this.permissionCheck( this.permissionCheck(
this.permissionConfirmation, this.permissionConfirmation,
localize("reqAcc"), localize("reqAcc"),
this.openFilePicker this.openZipFile
); );
}, },
openFilePicker() { openZipFile() {
// Filepicker.create({ const ContentResolver = Application.android.nativeApp.getContentResolver();
// mode: "single",
utils.getBackupFile().then((uri) => {
console.log(uri);
const inputStream = ContentResolver.openInputStream(uri);
console.log(inputStream);
let newFile = knownFolders.temp().getFile("test.zip");
console.log(newFile);
try {
const input = new java.io.BufferedInputStream(inputStream);
console.log(input);
const outputStream = new java.io.BufferedOutputStream(
new java.io.FileOutputStream(newFile.path)
);
console.log(outputStream);
let size = inputStream.available();
console.log(size);
let buffer = Array.create("byte", size);
input.read(buffer);
do {
outputStream.write(buffer);
} while (input.read(buffer) != -1);
} catch (e) {
console.log(e);
} finally {
outputStream.flush();
outputStream.close();
input.close();
}
// console.log(zipInputStream);
// console.log(zipInputStream);
// let extractedFile = new java.io.File(
// knownFolders.temp().path + "/tmp.zip"
// );
// if (!extractedFile.exists()) {
// extractedFile.mkdirs();
// }
// console.log(extractedFile);
// let outputStream = new java.io.OutputStream(extractedFile);
// android.os.FileUtils.copy(inputStream, outputStream);
// let outputStream = new java.io.FileOutputStream(extractedFile);
// console.log(outputStream);
// while ((readLen = zipInputStream.read(readBuffer)) != -1) {
// outputStream.write(readBuffer, 0, readLen);
// }
// console.log(outputStream, 2);
});
// openFilePicker({
// extensions: ["zip"], // extensions: ["zip"],
// }) // }).then((res) => this.validateZipContent(res.files[0]));
// .present()
// .then((selection) => {
// // Toast.makeText(localize("vrfy") + "...").show();
// let zipPath = selection[0];
// this.validateZipContent(zipPath);
// });
}, },
importDataToDB(data, db, zipPath) { importDataToDB(data, db, zipPath) {
switch (db) { switch (db) {
@ -315,9 +399,11 @@ export default {
}); });
}, },
validateZipContent(zipPath) { validateZipContent(zipPath) {
console.log(zipPath);
Zip.unzip({ Zip.unzip({
archive: zipPath, archive: zipPath,
overwrite: true, overwrite: true,
onProgress: (progress) => (this.backupProgress = progress),
}).then((extractedFolderPath) => { }).then((extractedFolderPath) => {
let cacheFolderPath = extractedFolderPath + "/EnRecipes"; let cacheFolderPath = extractedFolderPath + "/EnRecipes";
const EnRecipesFilePath = cacheFolderPath + "/recipes.json"; const EnRecipesFilePath = cacheFolderPath + "/recipes.json";
@ -380,6 +466,7 @@ export default {
archive: sourcePath, archive: sourcePath,
directory: dest, directory: dest,
overwrite: true, overwrite: true,
onProgress: (progress) => (this.backupProgress = progress),
}).then((res) => { }).then((res) => {
this.showImportSummary(); this.showImportSummary();
this.unlinkBrokenImages(); this.unlinkBrokenImages();
@ -399,7 +486,16 @@ export default {
)}${importedNote}${existsNote}${updatedNote}`, )}${importedNote}${existsNote}${updatedNote}`,
okButtonText: "OK", okButtonText: "OK",
}, },
}); }).then(() => (this.backupProgress = 0));
},
showExportSummary(filename) {
this.$showModal(ConfirmDialog, {
props: {
title: "expSuc",
description: `Backed up to ${filename}`,
okButtonText: "OK",
},
}).then(() => (this.backupProgress = 0));
}, },
// PERMISSIONS HANDLER // PERMISSIONS HANDLER
permissionCheck(confirmation, description, action) { permissionCheck(confirmation, description, action) {
@ -411,7 +507,6 @@ export default {
if (status === "authorized") action(); if (status === "authorized") action();
if (status !== "denied") if (status !== "denied")
ApplicationSettings.setBoolean("storagePermissionAsked", true); ApplicationSettings.setBoolean("storagePermissionAsked", true);
// else Toast.makeText(localize("dend")).show();
}); });
} }
}); });

View file

@ -78,10 +78,6 @@
"large": "large", "large": "large",
"strAdd": "Start adding your recipes!", "strAdd": "Start adding your recipes!",
"plsAdd": "Use the plus button to add one", "plsAdd": "Use the plus button to add one",
"pAIng": "Use the pencil button to add ingredients",
"pAIns": "Use the pencil button to add instructions",
"pACmb": "Use the pencil button to add combinations",
"pANo": "Use the pencil button to add notes",
"aD": "All done!", "aD": "All done!",
"tLInfo": "Recipes you want to try later are listed here", "tLInfo": "Recipes you want to try later are listed here",
"noFavs": "No favourites yet", "noFavs": "No favourites yet",
@ -96,6 +92,7 @@
"Theme": "Theme", "Theme": "Theme",
"Light": "Light", "Light": "Light",
"Dark": "Dark", "Dark": "Dark",
"Black": "Black",
"db": "Database", "db": "Database",
"expBu": "Export full backup", "expBu": "Export full backup",
"buInfo": "Generates a ZIP file containing all your data that can be imported back", "buInfo": "Generates a ZIP file containing all your data that can be imported back",
@ -103,7 +100,6 @@
"impInfo": "Supports full backups exported by this app", "impInfo": "Supports full backups exported by this app",
"ver": "Version", "ver": "Version",
"joinTG": "Join the Telegram group", "joinTG": "Join the Telegram group",
"tgInfo": "For reporting issues, suggestions and feedback",
"newRec": "New recipe", "newRec": "New recipe",
"editRec": "Edit recipe", "editRec": "Edit recipe",
"title": "Title", "title": "Title",
@ -260,6 +256,7 @@
"ts": "Tags", "ts": "Tags",
"tsInfo": "separate with spaces", "tsInfo": "separate with spaces",
"impSuc": "Import success", "impSuc": "Import success",
"expSuc": "Export success",
"recF": "recipes found", "recF": "recipes found",
"recI": "recipes imported", "recI": "recipes imported",
"recE": "recipes already exists", "recE": "recipes already exists",
@ -304,10 +301,12 @@
"noAccSensor": "Accelerometer sensor is either disabled or is not working", "noAccSensor": "Accelerometer sensor is either disabled or is not working",
"listVM": "List view mode", "listVM": "List view mode",
"detailed": "Detailed", "detailed": "Detailed",
"simple": "Simple",
"grid": "Grid", "grid": "Grid",
"photogrid": "Photo Grid",
"simple": "Simple",
"minimal": "Minimal", "minimal": "Minimal",
"apply": "APPLY", "apply": "APPLY",
"fltr": "Filter", "fltr": "Filter",
"yld": "Yield" "yld": "Yield",
"swm": "Start week on Monday"
} }

View file

@ -1,4 +1,5 @@
import { Application, Utils } from '@nativescript/core' import { Application, AndroidApplication, Utils } from '@nativescript/core'
let timerOne
export const restartApp = () => { export const restartApp = () => {
let mStartActivity = new android.content.Intent( let mStartActivity = new android.content.Intent(
Application.android.context, Application.android.context,
@ -48,3 +49,254 @@ export const vibrate = (duration) => {
) )
if (vibratorService.hasVibrator()) vibratorService.vibrate(duration) if (vibratorService.hasVibrator()) vibratorService.vibrate(duration)
} }
export const timer = (dur, callback) => {
clearInterval(timerOne)
callback(true)
timerOne = setInterval(() => {
dur--
callback(true)
if (dur == 0) {
callback(false)
clearInterval(timerOne)
}
}, 1000)
}
// FOLDER PICKER
function callIntent(context, intent, pickerType) {
return new Promise((resolve, reject) => {
const onEvent = function(e) {
if (e.requestCode === pickerType) {
resolve(e)
Application.android.off(AndroidApplication.activityResultEvent, onEvent)
}
}
Application.android.once(AndroidApplication.activityResultEvent, onEvent)
context.startActivityForResult(intent, pickerType)
})
}
//SOURCE: https://github.com/NativeScript/nativescript-imagepicker/blob/bc9209dd7d773eb437ff812f07873c72c789d572/src/imagepicker.android.ts
function getDataColumn(uri, selection, selectionArgs, isDownload) {
const ContentResolver = Application.android.nativeApp.getContentResolver()
let cursor = null
let filePath
if (isDownload) {
let columns = ['_display_name']
try {
cursor = ContentResolver.query(
uri,
columns,
selection,
selectionArgs,
null
)
if (cursor != null && cursor.moveToFirst()) {
let column_index = cursor.getColumnIndexOrThrow(columns[0])
filePath = cursor.getString(column_index)
if (filePath) {
const dl = android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS
)
filePath = `${dl}/${filePath}`
return filePath
}
}
} catch (e) {
console.log(e)
} finally {
if (cursor) {
cursor.close()
}
}
} else {
let columns = [android.provider.MediaStore.MediaColumns.DATA]
let filePath
try {
cursor = ContentResolver.query(
uri,
columns,
selection,
selectionArgs,
null
)
if (cursor != null && cursor.moveToFirst()) {
let column_index = cursor.getColumnIndexOrThrow(columns[0])
filePath = cursor.getString(column_index)
if (filePath) {
return filePath
}
}
} catch (e) {
console.log(e)
} finally {
if (cursor) {
cursor.close()
}
}
}
return undefined
}
function getTreeUri(uri) {
const DocumentsContract = android.provider.DocumentsContract
const ContentResolver = Application.android.nativeApp.getContentResolver()
if (DocumentsContract.isTreeUri(uri)) {
let docId, id, type
let contentUri = null
if ('com.android.externalstorage.documents' === uri.getAuthority()) {
docId = DocumentsContract.getTreeDocumentId(uri).split(':')
type = docId[0]
id = docId[1]
if ('primary' === type.toLowerCase())
return android.os.Environment.getExternalStorageDirectory() + '/' + id
else {
ContentResolver.takePersistableUriPermission(
uri,
android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION |
android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
const externalMediaDirs = Application.android.context.getExternalMediaDirs()
if (externalMediaDirs.length > 1) {
let filePath = externalMediaDirs[1].getAbsolutePath()
filePath = filePath.substring(0, filePath.indexOf('Android')) + id
return filePath
}
}
}
// DownloadsProvider
else if (
'com.android.providers.downloads.documents' === uri.getAuthority()
) {
return getDataColumn(uri, null, null, true)
}
// MediaProvider
else if ('com.android.providers.media.documents' === uri.getAuthority()) {
docId = DocumentsContract.getTreeDocumentId(uri).split(':')
type = docId[0]
id = docId[1]
if ('image' === type)
contentUri =
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
else if ('video' === type)
contentUri =
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI
else if ('audio' === type)
contentUri =
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
let selection = '_id=?'
let selectionArgs = [id]
return getDataColumn(contentUri, selection, selectionArgs, false)
}
}
return undefined
}
function getFileUri(uri) {
const DocumentsContract = android.provider.DocumentsContract
const ContentResolver = Application.android.nativeApp.getContentResolver()
if (DocumentsContract.isDocumentUri(Application.android.context, uri)) {
let docId, id, type
let contentUri = null
if ('com.android.externalstorage.documents' === uri.getAuthority()) {
docId = DocumentsContract.getDocumentId(uri).split(':')
type = docId[0]
id = docId[1]
if ('primary' === type.toLowerCase())
return android.os.Environment.getExternalStorageDirectory() + '/' + id
else {
ContentResolver.takePersistableUriPermission(
uri,
android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION |
android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
const externalMediaDirs = Application.android.context.getExternalMediaDirs()
if (externalMediaDirs.length > 1) {
let filePath = externalMediaDirs[1].getAbsolutePath()
filePath = filePath.substring(0, filePath.indexOf('Android')) + id
return filePath
}
}
}
// DownloadsProvider
else if (
'com.android.providers.downloads.documents' === uri.getAuthority()
) {
return getDataColumn(uri, null, null, true)
}
// MediaProvider
else if ('com.android.providers.media.documents' === uri.getAuthority()) {
docId = DocumentsContract.getDocumentId(uri).split(':')
type = docId[0]
id = docId[1]
if ('image' === type)
contentUri =
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
else if ('video' === type)
contentUri =
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI
else if ('audio' === type)
contentUri =
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
let selection = '_id=?'
let selectionArgs = [id]
return getDataColumn(contentUri, selection, selectionArgs, false)
}
}
return undefined
}
export const pickFolder = () => {
const context =
Application.android.foregroundActivity || Application.android.startActivity
const DIR_CODE = Math.round(Math.random() * 10000)
const intent = new android.content.Intent(
android.content.Intent.ACTION_OPEN_DOCUMENT_TREE
)
intent.addCategory(android.content.Intent.CATEGORY_DEFAULT)
return callIntent(context, intent, DIR_CODE).then((res) => {
if (res.resultCode === android.app.Activity.RESULT_OK)
if (res.intent != null && res.intent.getData())
return getTreeUri(res.intent.getData())
})
}
function callBackupIntent(context, intent, pickerType) {
return new Promise((resolve, reject) => {
const onEvent = function(e) {
if (e.requestCode === pickerType) {
resolve(e)
Application.android.off(AndroidApplication.activityResultEvent, onEvent)
}
}
Application.android.once(AndroidApplication.activityResultEvent, onEvent)
context.startActivityForResult(intent, pickerType)
})
}
export const getBackupFile = () => {
const context =
Application.android.foregroundActivity || Application.android.startActivity
const DIR_CODE = Math.round(Math.random() * 10000)
const intent = new android.content.Intent(
android.content.Intent.ACTION_GET_CONTENT
)
intent.addCategory(android.content.Intent.CATEGORY_OPENABLE)
intent.setType('application/zip')
// intent.setFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
return callBackupIntent(context, intent, DIR_CODE).then((res) => {
if (res.resultCode === android.app.Activity.RESULT_OK) {
if (res.intent != null && res.intent.getData()) {
// return getFileUri(res.intent.getData())
return res.intent.getData()
}
}
})
}

17389
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{ {
"name": "enrecipes", "name": "enrecipes",
"main": "./app/main.js", "main": "main.js",
"version": "1.0.0", "version": "1.0.0",
"description": "A native application built with NativeScript-Vue", "description": "A native application built with NativeScript-Vue",
"homepage": "https://enrecipes.vercel.app/", "homepage": "https://enrecipes.vercel.app/",
@ -20,7 +20,7 @@
"dependencies": { "dependencies": {
"@nativescript-community/perms": "^2.1.5", "@nativescript-community/perms": "^2.1.5",
"@nativescript-community/ui-collectionview": "^4.0.29", "@nativescript-community/ui-collectionview": "^4.0.29",
"@nativescript/core": "~8.0.0", "@nativescript/core": "7.3.0",
"@nativescript/localize": "^5.0.4", "@nativescript/localize": "^5.0.4",
"@nativescript/social-share": "^2.0.4", "@nativescript/social-share": "^2.0.4",
"@nativescript/zip": "^5.0.0", "@nativescript/zip": "^5.0.0",
@ -32,12 +32,13 @@
"vuex": "^3.6.2" "vuex": "^3.6.2"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "~7.1.0", "@babel/core": "^7.12.10",
"@babel/preset-env": "~7.1.0", "@babel/preset-env": "^7.12.11",
"@nativescript/android": "8.0.0", "@nativescript/android": "7.0.1",
"@nativescript/webpack": "5.0.0-beta.0", "@nativescript/webpack": "4.1.0",
"babel-loader": "~8.0.0", "babel-loader": "^8.2.2",
"nativescript-vue-template-compiler": "^2.8.4", "nativescript-vue-template-compiler": "^2.8.3",
"sass": "^1.32.8" "node-sass": "^4.14.1",
"vue-loader": "^15.9.6"
} }
} }

View file

@ -1,11 +1,357 @@
const webpack = require("@nativescript/webpack"); const { join, relative, resolve, sep } = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const TerserPlugin = require('terser-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const NsVueTemplateCompiler = require('nativescript-vue-template-compiler');
const nsWebpack = require('@nativescript/webpack');
const nativescriptTarget = require('@nativescript/webpack/nativescript-target');
const { NativeScriptWorkerPlugin } = require('nativescript-worker-loader/NativeScriptWorkerPlugin');
const hashSalt = Date.now().toString();
module.exports = (env) => { module.exports = (env) => {
webpack.init(env); const platform = env && ((env.android && 'android') || (env.ios && 'ios') || env.platform);
if (!platform) {
throw new Error('You need to provide a target platform!');
}
// todo: comments for common usage const platforms = ['ios', 'android'];
const projectRoot = __dirname;
return webpack.resolveConfig(); if (env.platform) {
platforms.push(env.platform);
}
// Default destination inside platforms/<platform>/...
const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
const {
// The 'appPath' and 'appResourcesPath' values are fetched from
// the nsconfig.json configuration file.
appPath = 'app',
appResourcesPath = 'app/App_Resources',
// You can provide the following flags when running 'tns run android|ios'
snapshot, // --env.snapshot
production, // --env.production
report, // --env.report
hmr, // --env.hmr
sourceMap, // --env.sourceMap
hiddenSourceMap, // --env.hiddenSourceMap
unitTesting, // --env.unitTesting
testing, // --env.testing
verbose, // --env.verbose
ci, // --env.ci
snapshotInDocker, // --env.snapshotInDocker
skipSnapshotTools, // --env.skipSnapshotTools
compileSnapshot, // --env.compileSnapshot
appComponents = [],
entries = {},
} = env;
const useLibs = compileSnapshot;
const isAnySourceMapEnabled = !!sourceMap || !!hiddenSourceMap;
const externals = nsWebpack.getConvertedExternals(env.externals);
const mode = production ? 'production' : 'development';
const appFullPath = resolve(projectRoot, appPath);
const hasRootLevelScopedModules = nsWebpack.hasRootLevelScopedModules({ projectDir: projectRoot });
let coreModulesPackageName = 'tns-core-modules';
const alias = env.alias || {};
alias['~/package.json'] = resolve(projectRoot, 'package.json');
alias['~'] = appFullPath;
alias['@'] = appFullPath;
alias['vue'] = 'nativescript-vue';
if (hasRootLevelScopedModules) {
coreModulesPackageName = '@nativescript/core';
alias['tns-core-modules'] = coreModulesPackageName;
}
const appResourcesFullPath = resolve(projectRoot, appResourcesPath);
const copyIgnore = { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] };
const entryModule = nsWebpack.getEntryModule(appFullPath, platform);
const entryPath = `.${sep}${entryModule}`;
Object.assign(entries, { bundle: entryPath }, entries);
const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some((e) => e.indexOf('@nativescript') > -1);
if (platform === 'ios' && !areCoreModulesExternal && !testing) {
entries['tns_modules/inspector_modules'] = '@nativescript/core/inspector_modules';
}
console.log(`Bundling application for entryPath ${entryPath}...`);
let sourceMapFilename = nsWebpack.getSourceMapFilename(hiddenSourceMap, __dirname, dist);
const itemsToClean = [`${dist}/**/*`];
if (platform === 'android') {
itemsToClean.push(`${join(projectRoot, 'platforms', 'android', 'app', 'src', 'main', 'assets', 'snapshots')}`);
itemsToClean.push(`${join(projectRoot, 'platforms', 'android', 'app', 'build', 'configurations', 'nativescript-android-snapshot')}`);
}
// Add your custom Activities, Services and other android app components here.
appComponents.push('@nativescript/core/ui/frame', '@nativescript/core/ui/frame/activity');
nsWebpack.processAppComponents(appComponents, platform);
const config = {
mode: mode,
context: appFullPath,
externals,
watchOptions: {
ignored: [
appResourcesFullPath,
// Don't watch hidden files
'**/.*',
],
},
target: nativescriptTarget,
// target: nativeScriptVueTarget,
entry: entries,
output: {
pathinfo: false,
path: dist,
sourceMapFilename,
libraryTarget: 'commonjs2',
filename: '[name].js',
globalObject: 'global',
hashSalt,
},
resolve: {
extensions: ['.vue', '.ts', '.js', '.scss', '.css'],
// Resolve {N} system modules from @nativescript/core
modules: [resolve(__dirname, `node_modules/${coreModulesPackageName}`), resolve(__dirname, 'node_modules'), `node_modules/${coreModulesPackageName}`, 'node_modules'],
alias,
// resolve symlinks to symlinked modules
symlinks: true,
},
resolveLoader: {
// don't resolve symlinks to symlinked loaders
symlinks: false,
},
node: {
// Disable node shims that conflict with NativeScript
http: false,
timers: false,
setImmediate: false,
fs: 'empty',
__dirname: false,
},
devtool: hiddenSourceMap ? 'hidden-source-map' : sourceMap ? 'inline-source-map' : 'none',
optimization: {
runtimeChunk: 'single',
noEmitOnErrors: true,
splitChunks: {
cacheGroups: {
vendor: {
name: 'vendor',
chunks: 'all',
test: (module) => {
const moduleName = module.nameForCondition ? module.nameForCondition() : '';
return /[\\/]node_modules[\\/]/.test(moduleName) || appComponents.some((comp) => comp === moduleName);
},
enforce: true,
},
},
},
minimize: Boolean(production),
minimizer: [
new TerserPlugin({
parallel: true,
cache: !ci,
sourceMap: isAnySourceMapEnabled,
terserOptions: {
output: {
comments: false,
semicolons: !isAnySourceMapEnabled,
},
compress: {
// The Android SBG has problems parsing the output
// when these options are enabled
collapse_vars: platform !== 'android',
sequences: platform !== 'android',
// For v8 Compatibility
keep_infinity: true, // for V8
reduce_funcs: false, // for V8
// custom
drop_console: production,
drop_debugger: true,
global_defs: {
__UGLIFIED__: true,
},
},
keep_fnames: true,
// Required for Element Level CSS, Observable Events, & Android Frame
keep_classnames: true,
},
}),
],
},
module: {
rules: [
{
include: [join(appFullPath, entryPath + '.js'), join(appFullPath, entryPath + '.ts')],
use: [
// Require all Android app components
platform === 'android' && {
loader: '@nativescript/webpack/helpers/android-app-components-loader',
options: { modules: appComponents },
},
{
loader: '@nativescript/webpack/bundle-config-loader',
options: {
registerPages: true, // applicable only for non-angular apps
loadCss: !snapshot, // load the application css if in debug mode
unitTesting,
appFullPath,
projectRoot,
ignoredFiles: nsWebpack.getUserDefinedEntries(entries, platform),
},
},
].filter((loader) => Boolean(loader)),
},
{
test: /[\/|\\]app\.css$/,
use: [
'@nativescript/webpack/helpers/style-hot-loader',
{
loader: '@nativescript/webpack/helpers/css2json-loader',
options: { useForImports: true },
},
],
},
{
test: /[\/|\\]app\.scss$/,
use: [
'@nativescript/webpack/helpers/style-hot-loader',
{
loader: '@nativescript/webpack/helpers/css2json-loader',
options: { useForImports: true },
},
'sass-loader',
],
},
{
test: /\.css$/,
exclude: /[\/|\\]app\.css$/,
use: ['@nativescript/webpack/helpers/style-hot-loader', '@nativescript/webpack/helpers/apply-css-loader.js', { loader: 'css-loader', options: { url: false } }],
},
{
test: /\.scss$/,
exclude: /[\/|\\]app\.scss$/,
use: ['@nativescript/webpack/helpers/style-hot-loader', '@nativescript/webpack/helpers/apply-css-loader.js', { loader: 'css-loader', options: { url: false } }, 'sass-loader'],
},
{
test: /\.js$/,
loader: 'babel-loader',
},
{
test: /\.ts$/,
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/],
allowTsInNodeModules: true,
compilerOptions: {
declaration: false,
},
getCustomTransformers: (program) => ({
before: [require('@nativescript/webpack/transformers/ns-transform-native-classes').default],
}),
},
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
compiler: NsVueTemplateCompiler,
},
},
],
},
plugins: [
// ... Vue Loader plugin omitted
// make sure to include the plugin!
new VueLoaderPlugin(),
// Define useful constants like TNS_WEBPACK
new webpack.DefinePlugin({
'global.TNS_WEBPACK': 'true',
'global.isAndroid': platform === 'android',
'global.isIOS': platform === 'ios',
TNS_ENV: JSON.stringify(mode),
process: 'global.process',
}),
// Remove all files from the out dir.
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: itemsToClean,
verbose: !!verbose,
}),
// Copy assets
new CopyWebpackPlugin([{ from: { glob: 'assets/**', dot: false } }, { from: { glob: 'fonts/**', dot: false } }, { from: { glob: '**/*.jpg', dot: false } }, { from: { glob: '**/*.png', dot: false } }], copyIgnore),
new nsWebpack.GenerateNativeScriptEntryPointsPlugin('bundle'),
// For instructions on how to set up workers with webpack
// check out https://github.com/nativescript/worker-loader
new NativeScriptWorkerPlugin(),
new nsWebpack.PlatformFSPlugin({
platform,
platforms,
}),
// Does IPC communication with the {N} CLI to notify events when running in watch mode.
new nsWebpack.WatchStateLoggerPlugin(),
],
};
if (unitTesting) {
config.module.rules.push(
{
test: /-page\.js$/,
use: '@nativescript/webpack/helpers/script-hot-loader',
},
{
test: /\.(html|xml)$/,
use: '@nativescript/webpack/helpers/markup-hot-loader',
},
{ test: /\.(html|xml)$/, use: '@nativescript/webpack/helpers/xml-namespace-loader' }
);
}
if (report) {
// Generate report files for bundles content
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
generateStatsFile: true,
reportFilename: resolve(projectRoot, 'report', `report.html`),
statsFilename: resolve(projectRoot, 'report', `stats.json`),
})
);
}
if (snapshot) {
config.plugins.push(
new nsWebpack.NativeScriptSnapshotPlugin({
chunk: 'vendor',
requireModules: ['@nativescript/core/bundle-entry-points'],
projectRoot,
webpackConfig: config,
snapshotInDocker,
skipSnapshotTools,
useLibs,
})
);
}
if (hmr) {
config.plugins.push(new webpack.HotModuleReplacementPlugin());
}
return config;
}; };