提交 14f199dc 编写于 作者: fxy060608's avatar fxy060608

wip(i18n): titleText and tabBar

上级 318147aa
......@@ -350,6 +350,10 @@ var serviceContext = (function () {
return typeof fn === 'function'
}
function isStr (str) {
return typeof str === 'string'
}
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
......@@ -1465,6 +1469,9 @@ var serviceContext = (function () {
},
};
}
function isI18nStr(value, delimiters) {
return value.indexOf(delimiters[0]) > -1;
}
var en = {
"uni.app.quit": "Press back button again to exit",
......@@ -1683,6 +1690,78 @@ var serviceContext = (function () {
localeWatchers.forEach(watch => watch(v));
}
});
}
const I18N_JSON_DELIMITERS = ['%', '%'];
function getLocaleMessage () {
const locale = uni.getLocale();
const locales = __uniConfig.locales;
return (
locales[locale] || locales[__uniConfig.fallbackLocale] || locales.en || {}
)
}
function formatI18n (message) {
if (isI18nStr(message, I18N_JSON_DELIMITERS)) {
return i18n.f(message, getLocaleMessage(), I18N_JSON_DELIMITERS)
}
return message
}
function resolveJsonObj (
jsonObj,
names
) {
if (names.length === 1) {
if (jsonObj) {
const value = jsonObj[names[0]];
if (isStr(value) && isI18nStr(value, I18N_JSON_DELIMITERS)) {
return jsonObj
}
}
return
}
const name = names.shift();
return resolveJsonObj(jsonObj && jsonObj[name], names)
}
function defineI18nProperties (
obj,
names
) {
return names.map((name) => defineI18nProperty(obj, name))
}
function defineI18nProperty (obj, names) {
const jsonObj = resolveJsonObj(obj, names);
if (!jsonObj) {
return false
}
const prop = names[names.length - 1];
let value = jsonObj[prop];
Object.defineProperty(jsonObj, prop, {
get () {
return formatI18n(value)
},
set (v) {
value = v;
}
});
return true
}
function isEnableLocale () {
return __uniConfig.locales && !!Object.keys(__uniConfig.locales).length
}
function initNavigationBarI18n (navigationBar) {
if (isEnableLocale()) {
return defineI18nProperties(navigationBar, [
['titleText'],
['searchInput', 'placeholder']
])
}
}
const setClipboardData = {
......@@ -8459,81 +8538,125 @@ var serviceContext = (function () {
const WEBVIEW_REMOVED = 'webviewRemoved';
const WEBVIEW_ID_PREFIX = 'webviewId';
function createButtonOnClick (index) {
return function onClick (btn) {
function createButtonOnClick(index) {
return function onClick(btn) {
const pages = getCurrentPages();
if (!pages.length) {
return
return;
}
btn.index = index;
const page = pages[pages.length - 1];
page.$vm &&
page.$vm.__call_hook &&
page.$vm.__call_hook('onNavigationBarButtonTap', btn);
}
page.$vm.__call_hook("onNavigationBarButtonTap", btn);
};
}
function parseTitleNViewButtons (titleNView) {
function parseTitleNViewButtons(titleNView) {
const buttons = titleNView.buttons;
if (!Array.isArray(buttons)) {
return titleNView
return titleNView;
}
buttons.forEach((btn, index) => {
btn.onclick = createButtonOnClick(index);
});
return titleNView
return titleNView;
}
function parseTitleNView (routeOptions) {
function parseTitleNView(id, routeOptions) {
const windowOptions = routeOptions.window;
const titleNView = windowOptions.titleNView;
routeOptions.meta.statusBarStyle = windowOptions.navigationBarTextStyle === 'black' ? 'dark' : 'light';
if ( // 无头
routeOptions.meta.statusBarStyle =
windowOptions.navigationBarTextStyle === "black" ? "dark" : "light";
if (
// 无头
titleNView === false ||
titleNView === 'false' ||
(
windowOptions.navigationStyle === 'custom' &&
!isPlainObject(titleNView)
) || (
windowOptions.transparentTitle === 'always' &&
!isPlainObject(titleNView)
)
titleNView === "false" ||
(windowOptions.navigationStyle === "custom" &&
!isPlainObject(titleNView)) ||
(windowOptions.transparentTitle === "always" && !isPlainObject(titleNView))
) {
return false
return false;
}
const titleImage = windowOptions.titleImage || '';
const transparentTitle = windowOptions.transparentTitle || 'none';
const titleImage = windowOptions.titleImage || "";
const transparentTitle = windowOptions.transparentTitle || "none";
const titleNViewTypeList = {
none: 'default',
auto: 'transparent',
always: 'float'
none: "default",
auto: "transparent",
always: "float"
};
const navigationBarBackgroundColor = windowOptions.navigationBarBackgroundColor;
const navigationBarBackgroundColor =
windowOptions.navigationBarBackgroundColor;
const ret = {
autoBackButton: !routeOptions.meta.isQuit,
titleText: titleImage === '' ? windowOptions.navigationBarTitleText || '' : '',
titleColor: windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff',
titleText:
titleImage === "" ? windowOptions.navigationBarTitleText || "" : "",
titleColor:
windowOptions.navigationBarTextStyle === "black" ? "#000000" : "#ffffff",
type: titleNViewTypeList[transparentTitle],
backgroundColor: (/^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) || navigationBarBackgroundColor === 'transparent') ? navigationBarBackgroundColor : '#f7f7f7',
tags: titleImage === '' ? [] : [{
tag: 'img',
src: titleImage,
position: {
left: 'auto',
top: 'auto',
width: 'auto',
height: '26px'
}
}]
backgroundColor:
/^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) ||
navigationBarBackgroundColor === "transparent"
? navigationBarBackgroundColor
: "#f7f7f7",
tags:
titleImage === ""
? []
: [
{
tag: "img",
src: titleImage,
position: {
left: "auto",
top: "auto",
width: "auto",
height: "26px"
}
}
]
};
if (isPlainObject(titleNView)) {
return Object.assign(ret, parseTitleNViewButtons(titleNView))
return initTitleNViewI18n(
id,
Object.assign(ret, parseTitleNViewButtons(titleNView))
);
}
return initTitleNViewI18n(id, ret);
}
return ret
function initTitleNViewI18n(id, titleNView) {
const i18nResult = initNavigationBarI18n(titleNView);
if (!i18nResult) {
return titleNView;
}
const [titleTextI18n, searchInputPlaceholderI18n] = i18nResult;
if (titleTextI18n || searchInputPlaceholderI18n) {
uni.onLocaleChange(() => {
const webview = plus.webview.getWebviewById(id + "");
if (!webview) {
return;
}
const newTitleNView = {};
if (titleTextI18n) {
newTitleNView.titleText = titleNView.titleText;
}
if (searchInputPlaceholderI18n) {
newTitleNView.searchInput = {
placeholder: titleNView.searchInput.placeholder
};
}
if (process.env.NODE_ENV !== "production") {
console.log("[uni-app] updateWebview", webview.id, newTitleNView);
}
webview.setStyle({
titleNView: newTitleNView
});
});
}
return titleNView;
}
function parsePullToRefresh (routeOptions) {
......@@ -8624,10 +8747,12 @@ var serviceContext = (function () {
};
// 合并
routeOptions.window = parseStyleUnit(Object.assign(
JSON.parse(JSON.stringify(__uniConfig.window || {})),
routeOptions.window || {}
));
routeOptions.window = parseStyleUnit(
Object.assign(
JSON.parse(JSON.stringify(__uniConfig.window || {})),
routeOptions.window || {}
)
);
Object.keys(routeOptions.window).forEach(name => {
if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) {
......@@ -8636,7 +8761,10 @@ var serviceContext = (function () {
});
const backgroundColor = routeOptions.window.backgroundColor;
if (/^#[a-z0-9]{6}$/i.test(backgroundColor) || backgroundColor === 'transparent') {
if (
/^#[a-z0-9]{6}$/i.test(backgroundColor) ||
backgroundColor === 'transparent'
) {
if (!webviewStyle.background) {
webviewStyle.background = backgroundColor;
}
......@@ -8645,7 +8773,7 @@ var serviceContext = (function () {
}
}
const titleNView = parseTitleNView(routeOptions);
const titleNView = parseTitleNView(id, routeOptions);
if (titleNView) {
if (
id === 1 &&
......@@ -8670,7 +8798,8 @@ var serviceContext = (function () {
delete webviewStyle.popGesture;
}
if (routeOptions.meta.isQuit) { // 退出
if (routeOptions.meta.isQuit) {
// 退出
webviewStyle.popGesture = plus.os.name === 'iOS' ? 'appback' : 'none';
}
......
{
"warning": "Warning⚠",
"syntaxError": "Syntax Error❌",
"compilerVersion": "Compiler version",
"compiling": "Compiling...",
"see": "see",
"platform": "platform",
"plugin": "plugin",
"performingHotReload": "Performing hot reload...",
"cliShared.parsingFailed": "Parsing failed",
"cliShared.doesNotExist": "does not exist",
"cliShared.pagesJsonError": "pages.json page configuration error, has been ignored, see {{0}}",
"cliShared.requireReturnJsonObject": "require return a json object",
"cliShared.requireExportFunction": "Function must be exported",
"cliShared.easycomConflict": "easycom component conflict:",
"cliShared.noFoundPlatformPlugin": "Missing platform {{0}} plugin",
"cliShared.extendOnlySupportH5": "Currently only supports expansion based on the h5 platform",
"cliShared.supportPlatform": "{{0}} support the following platforms {{1}}",
"cliShared.requireConfigUniPlatform": "{{0}} does not exist, you must configure the env->UNI_PLATFORM base platform",
"cliShared.missingNameAttribute": "{{0}} missing name property",
"cliShared.missingUniConfig": "{{0}} missing uni.config.js",
"migration.errorOnlySupportConvert": "Error: {{0}} conversion is currently supported",
"migration.errorInputNotExists": "Error: '{{0}}' not exist",
"migration.errorCannotConvert": "Error: '{{0}}' does not support conversion",
"migration.errorConvertRequireFileUrl": "Error: Single file conversion requires {{0}} file url",
"mpWeChat.onlySupportDestructuringSlot": "Currently only supports destructuring slot {{0}}, such as {{1}}",
"mpWeChat.slotPropNoSupportReanme": "Deconstructing the slot Prop, does not support renaming {{0}} to {{1}}, the performance will be affected after renaming",
"uniStat.missingParameter": "Missing [eventName] parameter",
"uniStat.parameterLengthLess": "Parameter length cannot be greater than",
"uniStat.parameterTypeErrrorString": "Parameter type error, it can only be of type String",
"uniStat.parameterTypeErrrorStringOrObject": "Parameter type error, Only supports String or Object type",
"uniStat.hasTitleOptionString": "When the parameter is title, the [options] parameter can only be of type String",
"templateCompiler.noH5KeyNoSupportExpression": "Non-h5 platforms: key does not support expression {{0}}, for details, please refer to: {{1}}",
"templateCompiler.notCurrentlySupportScopedSlot": "Not currently supported scoped slot {{0}}",
"templateCompiler.idAttribNotAllowInCustomComponentProps": "id is reserved as a property name and is not allowed to be defined as props in custom component {{0}}",
"templateCompiler.notSupportDynamicSlotName": "{{0}} Does not support dynamic slot names",
"templateCompiler.forNestedIndexNameNoArrowRepeat": "{{0}} When v-for is nested, the index name {{1}} is not allowed to be repeated",
"templateCompiler.noSupportSyntax": "Does not support {{0}} syntax",
"pluginHbuilderx.plaseHXCompileAppPlatform": "Please use HBuilderX to compile and run to the app-plus platform",
"pluginHbuilderx.hxBuildFailed": "Build failed: HBuilderX installation directory cannot include special characters such as {{0}}",
"pluginHbuilderx.nvueCssWarning": "The following css is not supported in nvue. If the global or public style is affected, it is recommended to write the warning style in the conditional compilation of ifndef APP-PLUS-NVUE. The details are as follows:",
"pluginUni.runDebugMode": "Please note that in running mode, due to log output, sourcemap, and uncompressed source code, the performance and package size are not as good as release mode.",
"pluginUni.runDebugModeNvue": "Especially the sourcemap of app-nvue has a greater impact",
"pluginUni.runDebugModeMP": "To officially release, please click the release menu or use the cli release command to release",
"pluginUni.compileToMpPluginOnlySupportWeChat": "Compile to mini-program plug-in only supports WeChat mini-program",
"pluginUni.startCompileProjectToPlatform": "Start to compile the current project to the {{0}} {{1}}...",
"pluginUni.fileNoExistsCheckAfterRetry": "{{0}} file does not exist, please check and try again",
"pluginUni.entryDileNoExistsCheckAfterRetry": "{{0}} The entry file does not exist, please check and try again",
"pluginUni.nvueCompileModeForDetail": "Current NVUE compile mode {{0}}. see: {{1}}",
"pluginUni.currentProjectDefaultSpaceId": "The default service space spaceId used by uniCloud of the current project is: {{0}}",
"pluginUni.unicloudReleaseH5": "To release H5, you need to operate on the uniCloud web console and bind a secure domain name, otherwise it will be inaccessible due to cross-domain issues. Tutorial reference:{{0}}",
"pluginUni.unicloudShowedRunByHBuilderX": "The current project uses uniCloud. In order to avoid the cross-domain problem of cloud function calls, it is recommended to debug in the HBuilderX built-in browser. If you use an external browser, you need to handle cross-domain. See details: {{0}}",
"pluginUni.pleaseSpecifyPluginName": "Please specify the plugin name",
"pluginUni.pluginNameNotExist": "Plug-in name does not exist",
"pluginUni.pluginIllegal": "The plugin is illegal",
"pluginUni.uniStatisticsNoAppid": "The current application is not configured with Appid, and uni statistics cannot be used. For details, see {{0}}",
"pluginUni.pleaseConfigScriptName": "Please specify the script name under package.json->uni-app->scripts",
"pluginUni.mpBrowserKernelDifference": "There are differences in the implementation mechanism of the browser kernels and custom components of each mini-program, and there may be compatibility issues with styles and layouts, please refer to: {{0}}",
"mpLoader.firstParameterNeedStaticString": "The first parameter of {{0}} must be a static string",
"mpLoader.requireTwoParameter": "{{0}} requires two parameters",
"mpLoader.findFail": "{{0}} find fail",
"mpLoader.componentReferenceError": "Component {{0}} reference error",
"mpLoader.componentReferenceErrorOnlySupportImport": "Component {{0}} reference error, only supports import components",
"pagesLoader.pagesNodeCannotNull": "Pages node in pages.json cannot be empty",
"pagesLoader.nvueFirstPageStartModeIsFast": "Nvue homepage startup mode: fast. For details, see: {{0}}",
"pagesLoader.pagesTabbarMinItem2": "{{0}} must contain at least 2 items",
"pagesLoader.needInPagesNode": "{{0}} needs to be in the pages array"
}
\ No newline at end of file
{
"warning": "Warning⚠",
"syntaxError": "Syntax Error❌",
"compilerVersion": "Compiler version",
"compiling": "Compiling...",
"see": "see",
"platform": "platform",
"plugin": "plugin",
"performingHotReload": "Performing hot reload...",
"cliShared.parsingFailed": "Parsing failed",
"cliShared.doesNotExist": "does not exist",
"cliShared.pagesJsonError": "pages.json page configuration error, has been ignored, see {{0}}",
"cliShared.requireReturnJsonObject": "require return a json object",
"cliShared.requireExportFunction": "Function must be exported",
"cliShared.easycomConflict": "easycom component conflict:",
"cliShared.noFoundPlatformPlugin": "Missing platform {{0}} plugin",
"cliShared.extendOnlySupportH5": "Currently only supports expansion based on the h5 platform",
"cliShared.supportPlatform": "{{0}} support the following platforms {{1}}",
"cliShared.requireConfigUniPlatform": "{{0}} does not exist, you must configure the env->UNI_PLATFORM base platform",
"cliShared.missingNameAttribute": "{{0}} missing name property",
"cliShared.missingUniConfig": "{{0}} missing uni.config.js",
"migration.errorOnlySupportConvert": "Error: {{0}} conversion is currently supported",
"migration.errorInputNotExists": "Error: '{{0}}' not exist",
"migration.errorCannotConvert": "Error: '{{0}}' does not support conversion",
"migration.errorConvertRequireFileUrl": "Error: Single file conversion requires {{0}} file url",
"mpWeChat.onlySupportDestructuringSlot": "Currently only supports destructuring slot {{0}}, such as {{1}}",
"mpWeChat.slotPropNoSupportReanme": "Deconstructing the slot Prop, does not support renaming {{0}} to {{1}}, the performance will be affected after renaming",
"uniStat.missingParameter": "Missing [eventName] parameter",
"uniStat.parameterLengthLess": "Parameter length cannot be greater than",
"uniStat.parameterTypeErrrorString": "Parameter type error, it can only be of type String",
"uniStat.parameterTypeErrrorStringOrObject": "Parameter type error, Only supports String or Object type",
"uniStat.hasTitleOptionString": "When the parameter is title, the [options] parameter can only be of type String",
"templateCompiler.noH5KeyNoSupportExpression": "Non-h5 platforms: key does not support expression {{0}}, for details, please refer to: {{1}}",
"templateCompiler.notCurrentlySupportScopedSlot": "Not currently supported scoped slot {{0}}",
"templateCompiler.idAttribNotAllowInCustomComponentProps": "id is reserved as a property name and is not allowed to be defined as props in custom component {{0}}",
"templateCompiler.notSupportDynamicSlotName": "{{0}} Does not support dynamic slot names",
"templateCompiler.forNestedIndexNameNoArrowRepeat": "{{0}} When v-for is nested, the index name {{1}} is not allowed to be repeated",
"templateCompiler.noSupportSyntax": "Does not support {{0}} syntax",
"pluginHbuilderx.plaseHXCompileAppPlatform": "Please use HBuilderX to compile and run to the app-plus platform",
"pluginHbuilderx.hxBuildFailed": "Build failed: HBuilderX installation directory cannot include special characters such as {{0}}",
"pluginHbuilderx.nvueCssWarning": "The following css is not supported in nvue. If the global or public style is affected, it is recommended to write the warning style in the conditional compilation of ifndef APP-PLUS-NVUE. The details are as follows:",
"pluginUni.runDebugMode": "Please note that in running mode, due to log output, sourcemap, and uncompressed source code, the performance and package size are not as good as release mode.",
"pluginUni.runDebugModeNvue": "Especially the sourcemap of app-nvue has a greater impact",
"pluginUni.runDebugModeMP": "To officially release, please click the release menu or use the cli release command to release",
"pluginUni.compileToMpPluginOnlySupportWeChat": "Compile to mini-program plug-in only supports WeChat mini-program",
"pluginUni.startCompileProjectToPlatform": "Start to compile the current project to the {{0}} {{1}}...",
"pluginUni.fileNoExistsCheckAfterRetry": "{{0}} file does not exist, please check and try again",
"pluginUni.entryDileNoExistsCheckAfterRetry": "{{0}} The entry file does not exist, please check and try again",
"pluginUni.nvueCompileModeForDetail": "Current NVUE compile mode {{0}}. see: {{1}}",
"pluginUni.currentProjectDefaultSpaceId": "The default service space spaceId used by uniCloud of the current project is: {{0}}",
"pluginUni.unicloudReleaseH5": "To release H5, you need to operate on the uniCloud web console and bind a secure domain name, otherwise it will be inaccessible due to cross-domain issues. Tutorial reference:{{0}}",
"pluginUni.unicloudShowedRunByHBuilderX": "The current project uses uniCloud. In order to avoid the cross-domain problem of cloud function calls, it is recommended to debug in the HBuilderX built-in browser. If you use an external browser, you need to handle cross-domain. See details: {{0}}",
"pluginUni.pleaseSpecifyPluginName": "Please specify the plugin name",
"pluginUni.pluginNameNotExist": "Plug-in name does not exist",
"pluginUni.pluginIllegal": "The plugin is illegal",
"pluginUni.uniStatisticsNoAppid": "The current application is not configured with Appid, and uni statistics cannot be used. For details, see {{0}}",
"pluginUni.pleaseConfigScriptName": "Please specify the script name under package.json->uni-app->scripts",
"pluginUni.mpBrowserKernelDifference": "There are differences in the implementation mechanism of the browser kernels and custom components of each mini-program, and there may be compatibility issues with styles and layouts, please refer to: {{0}}",
"mpLoader.firstParameterNeedStaticString": "The first parameter of {{0}} must be a static string",
"mpLoader.requireTwoParameter": "{{0}} requires two parameters",
"mpLoader.findFail": "{{0}} find fail",
"mpLoader.componentReferenceError": "Component {{0}} reference error",
"mpLoader.componentReferenceErrorOnlySupportImport": "Component {{0}} reference error, only supports import components",
"pagesLoader.pagesNodeCannotNull": "Pages node in pages.json cannot be empty",
"pagesLoader.nvueFirstPageStartModeIsFast": "Nvue homepage startup mode: fast. For details, see: {{0}}",
"pagesLoader.pagesTabbarMinItem2": "{{0}} must contain at least 2 items",
"pagesLoader.needInPagesNode": "{{0}} needs to be in the pages array",
"i18n.fallbackLocale.default": "fallbackLocale is missing in manifest.json, use:{{locale}}",
"i18n.fallbackLocale.missing": "./local/{locale}.json is missing"
}
{
"warning": "警告⚠",
"syntaxError": "语法错误❌",
"compilerVersion": "编译器版本",
"compiling": "正在编译中...",
"see": "看",
"platform": "平台",
"plugin": "插件",
"performingHotReload": "正在热重载...",
"cliShared.parsingFailed": "解析失败",
"cliShared.doesNotExist": "不存在",
"cliShared.pagesJsonError": "pages.json 页面配置错误,已被忽略,查看文档: {{0}}",
"cliShared.requireReturnJsonObject": "必须返回一个 json 对象",
"cliShared.requireExportFunction": "必须导出 function",
"cliShared.easycomConflict": "easycom组件冲突:{{0}}",
"cliShared.noFoundPlatformPlugin": "缺少平台 {{0}} 插件",
"cliShared.extendOnlySupportH5": "目前仅支持基于 h5 平台做扩展",
"cliShared.supportPlatform": "{{0}} 支持以下平台 {{1}}",
"cliShared.requireConfigUniPlatform": "{{0}} 不存在,必须配置 env->UNI_PLATFORM 基础平台",
"cliShared.missingNameAttribute": "{{0}} 缺少 name 属性",
"cliShared.missingUniConfig": "{{0}} 缺少 uni.config.js",
"migration.errorOnlySupportConvert": "错误: 目前支持 {{0}} 转换",
"migration.errorInputNotExists": "错误: '{{0}}' 不存在",
"migration.errorCannotConvert": "错误: '{{0}}' 不支持转换",
"migration.errorConvertRequireFileUrl": "错误: 单文件转换需要传入 {{0}} 文件地址",
"mpWeChat.onlySupportDestructuringSlot": "目前仅支持解构插槽 {{0}},如 {{1}}",
"mpWeChat.slotPropNoSupportReanme": "解构插槽 Prop,不支持将 {{0}} 重命名为 {{1}},重命名后会影响性能",
"uniStat.missingParameter": "缺少 [eventName] 参数",
"uniStat.parameterLengthLess": "参数长度不能大于",
"uniStat.parameterTypeErrrorString": "参数类型错误,只能为 String 类型",
"uniStat.parameterTypeErrrorStringOrObject": "参数类型错误,只能为 String 或 Object 类型",
"uniStat.hasTitleOptionString": "参数为 title 时,[options] 参数只能为 String 类型",
"templateCompiler.noH5KeyNoSupportExpression": "非 h5 平台 :key 不支持表达式 {{0}},详情参考: {{1}}",
"templateCompiler.notCurrentlySupportScopedSlot": "暂不支持 scoped slot {{0}}",
"templateCompiler.idAttribNotAllowInCustomComponentProps": "id 作为属性保留名,不允许在自定义组件 {{0}} 中定义为 props",
"templateCompiler.notSupportDynamicSlotName": "{{0}} 不支持动态插槽名",
"templateCompiler.forNestedIndexNameNoArrowRepeat": "{{0}} v-for 嵌套时,索引名称 {{1}} 不允许重复",
"templateCompiler.noSupportSyntax": "不支持 {{0}} 语法",
"pluginHbuilderx.plaseHXCompileAppPlatform": "请使用 HBuilderX 编译运行至 app-plus 平台",
"pluginHbuilderx.hxBuildFailed": "编译失败:HBuilderX 安装目录不能包括 {{0}} 等特殊字符",
"pluginHbuilderx.nvueCssWarning": "nvue中不支持如下css。如全局或公共样式受影响,建议将告警样式写在ifndef APP-PLUS-NVUE的条件编译中,详情如下:",
"pluginUni.runDebugMode": "请注意运行模式下,因日志输出、sourcemap以及未压缩源码等原因,性能和包体积,均不及发行模式。",
"pluginUni.runDebugModeNvue": "尤其是app-nvue的sourcemap影响较大",
"pluginUni.runDebugModeMP": "若要正式发布,请点击发行菜单或使用cli发布命令进行发布",
"pluginUni.compileToMpPluginOnlySupportWeChat": "编译到小程序插件只支持微信小程序",
"pluginUni.startCompileProjectToPlatform": "开始编译当前项目至 {{0}} {{1}}...",
"pluginUni.fileNoExistsCheckAfterRetry": "{{0}} 文件不存在,请检查后重试",
"pluginUni.entryDileNoExistsCheckAfterRetry": "{{0}} 入口文件不存在,请检查后重试",
"pluginUni.nvueCompileModeForDetail": "当前nvue编译模式:{{0}}。编译模式差异见 {{1}}",
"pluginUni.currentProjectDefaultSpaceId": "当前项目的uniCloud使用的默认服务空间spaceId为:{{0}}",
"pluginUni.unicloudReleaseH5": "发布H5,需要在uniCloud web控制台操作,绑定安全域名,否则会因为跨域问题而无法访问。教程参考:{{0}}",
"pluginUni.unicloudShowedRunByHBuilderX": "当前项目使用了uniCloud,为避免云函数调用跨域问题,建议在HBuilderX内置浏览器里调试,如使用外部浏览器需处理跨域,详见:{{0}}",
"pluginUni.pleaseSpecifyPluginName": "请指定插件名",
"pluginUni.pluginNameNotExist": "插件名称不存在",
"pluginUni.pluginIllegal": "插件不合法",
"pluginUni.uniStatisticsNoAppid": "当前应用未配置Appid,无法使用uni统计,详情参考 {{0}}",
"pluginUni.pleaseConfigScriptName": "请指定 package.json->uni-app->scripts 下的 script 名称",
"pluginUni.mpBrowserKernelDifference": "小程序各家浏览器内核及自定义组件实现机制存在差异,可能存在样式布局兼容问题,参考:{{0}}",
"mpLoader.firstParameterNeedStaticString": "{{0}}的第一个参数必须为静态字符串",
"mpLoader.requireTwoParameter": "{{0}}需要两个参数",
"mpLoader.findFail": "{{0}}查找失败",
"mpLoader.componentReferenceError": "组件 {{0}} 引用错误",
"mpLoader.componentReferenceErrorOnlySupportImport": "组件 {{0}} 引用错误,仅支持 import 方式引入组件",
"pagesLoader.pagesNodeCannotNull": "pages.json 中的 pages 节点不能为空",
"pagesLoader.nvueFirstPageStartModeIsFast": "Nvue 首页启动模式: fast, 详见: {{0}}",
"pagesLoader.pagesTabbarMinItem2": "{{0}} 需至少包含2项",
"pagesLoader.needInPagesNode": "{{0}} 需在 pages 数组中"
}
\ No newline at end of file
{
"warning": "警告⚠",
"syntaxError": "语法错误❌",
"compilerVersion": "编译器版本",
"compiling": "正在编译中...",
"see": "看",
"platform": "平台",
"plugin": "插件",
"performingHotReload": "正在热重载...",
"cliShared.parsingFailed": "解析失败",
"cliShared.doesNotExist": "不存在",
"cliShared.pagesJsonError": "pages.json 页面配置错误,已被忽略,查看文档: {{0}}",
"cliShared.requireReturnJsonObject": "必须返回一个 json 对象",
"cliShared.requireExportFunction": "必须导出 function",
"cliShared.easycomConflict": "easycom组件冲突:{{0}}",
"cliShared.noFoundPlatformPlugin": "缺少平台 {{0}} 插件",
"cliShared.extendOnlySupportH5": "目前仅支持基于 h5 平台做扩展",
"cliShared.supportPlatform": "{{0}} 支持以下平台 {{1}}",
"cliShared.requireConfigUniPlatform": "{{0}} 不存在,必须配置 env->UNI_PLATFORM 基础平台",
"cliShared.missingNameAttribute": "{{0}} 缺少 name 属性",
"cliShared.missingUniConfig": "{{0}} 缺少 uni.config.js",
"migration.errorOnlySupportConvert": "错误: 目前支持 {{0}} 转换",
"migration.errorInputNotExists": "错误: '{{0}}' 不存在",
"migration.errorCannotConvert": "错误: '{{0}}' 不支持转换",
"migration.errorConvertRequireFileUrl": "错误: 单文件转换需要传入 {{0}} 文件地址",
"mpWeChat.onlySupportDestructuringSlot": "目前仅支持解构插槽 {{0}},如 {{1}}",
"mpWeChat.slotPropNoSupportReanme": "解构插槽 Prop,不支持将 {{0}} 重命名为 {{1}},重命名后会影响性能",
"uniStat.missingParameter": "缺少 [eventName] 参数",
"uniStat.parameterLengthLess": "参数长度不能大于",
"uniStat.parameterTypeErrrorString": "参数类型错误,只能为 String 类型",
"uniStat.parameterTypeErrrorStringOrObject": "参数类型错误,只能为 String 或 Object 类型",
"uniStat.hasTitleOptionString": "参数为 title 时,[options] 参数只能为 String 类型",
"templateCompiler.noH5KeyNoSupportExpression": "非 h5 平台 :key 不支持表达式 {{0}},详情参考: {{1}}",
"templateCompiler.notCurrentlySupportScopedSlot": "暂不支持 scoped slot {{0}}",
"templateCompiler.idAttribNotAllowInCustomComponentProps": "id 作为属性保留名,不允许在自定义组件 {{0}} 中定义为 props",
"templateCompiler.notSupportDynamicSlotName": "{{0}} 不支持动态插槽名",
"templateCompiler.forNestedIndexNameNoArrowRepeat": "{{0}} v-for 嵌套时,索引名称 {{1}} 不允许重复",
"templateCompiler.noSupportSyntax": "不支持 {{0}} 语法",
"pluginHbuilderx.plaseHXCompileAppPlatform": "请使用 HBuilderX 编译运行至 app-plus 平台",
"pluginHbuilderx.hxBuildFailed": "编译失败:HBuilderX 安装目录不能包括 {{0}} 等特殊字符",
"pluginHbuilderx.nvueCssWarning": "nvue中不支持如下css。如全局或公共样式受影响,建议将告警样式写在ifndef APP-PLUS-NVUE的条件编译中,详情如下:",
"pluginUni.runDebugMode": "请注意运行模式下,因日志输出、sourcemap以及未压缩源码等原因,性能和包体积,均不及发行模式。",
"pluginUni.runDebugModeNvue": "尤其是app-nvue的sourcemap影响较大",
"pluginUni.runDebugModeMP": "若要正式发布,请点击发行菜单或使用cli发布命令进行发布",
"pluginUni.compileToMpPluginOnlySupportWeChat": "编译到小程序插件只支持微信小程序",
"pluginUni.startCompileProjectToPlatform": "开始编译当前项目至 {{0}} {{1}}...",
"pluginUni.fileNoExistsCheckAfterRetry": "{{0}} 文件不存在,请检查后重试",
"pluginUni.entryDileNoExistsCheckAfterRetry": "{{0}} 入口文件不存在,请检查后重试",
"pluginUni.nvueCompileModeForDetail": "当前nvue编译模式:{{0}}。编译模式差异见 {{1}}",
"pluginUni.currentProjectDefaultSpaceId": "当前项目的uniCloud使用的默认服务空间spaceId为:{{0}}",
"pluginUni.unicloudReleaseH5": "发布H5,需要在uniCloud web控制台操作,绑定安全域名,否则会因为跨域问题而无法访问。教程参考:{{0}}",
"pluginUni.unicloudShowedRunByHBuilderX": "当前项目使用了uniCloud,为避免云函数调用跨域问题,建议在HBuilderX内置浏览器里调试,如使用外部浏览器需处理跨域,详见:{{0}}",
"pluginUni.pleaseSpecifyPluginName": "请指定插件名",
"pluginUni.pluginNameNotExist": "插件名称不存在",
"pluginUni.pluginIllegal": "插件不合法",
"pluginUni.uniStatisticsNoAppid": "当前应用未配置Appid,无法使用uni统计,详情参考 {{0}}",
"pluginUni.pleaseConfigScriptName": "请指定 package.json->uni-app->scripts 下的 script 名称",
"pluginUni.mpBrowserKernelDifference": "小程序各家浏览器内核及自定义组件实现机制存在差异,可能存在样式布局兼容问题,参考:{{0}}",
"mpLoader.firstParameterNeedStaticString": "{{0}}的第一个参数必须为静态字符串",
"mpLoader.requireTwoParameter": "{{0}}需要两个参数",
"mpLoader.findFail": "{{0}}查找失败",
"mpLoader.componentReferenceError": "组件 {{0}} 引用错误",
"mpLoader.componentReferenceErrorOnlySupportImport": "组件 {{0}} 引用错误,仅支持 import 方式引入组件",
"pagesLoader.pagesNodeCannotNull": "pages.json 中的 pages 节点不能为空",
"pagesLoader.nvueFirstPageStartModeIsFast": "Nvue 首页启动模式: fast, 详见: {{0}}",
"pagesLoader.pagesTabbarMinItem2": "{{0}} 需至少包含2项",
"pagesLoader.needInPagesNode": "{{0}} 需在 pages 数组中",
"i18n.fallbackLocale.default": "当前应用未在 manifest.json 配置 fallbackLocale,默认使用:{{locale}}",
"i18n.fallbackLocale.missing": "当前应用配置的 fallbackLocale 或 locale 为:{locale},但 locale 目录缺少该语言文件"
}
const fs = require('fs')
const path = require('path')
const { parseJson } = require('./json')
const { getManifestJson } = require('./manifest')
const delimiters = ['%', '%']
function initI18nOptions (
platform,
inputDir,
warning = false,
withMessages = true
) {
const locales = initLocales(path.resolve(inputDir, 'locale'), withMessages)
if (!Object.keys(locales).length) {
return
}
const manifestJson = getManifestJson()
const fallbackLocale = manifestJson.fallbackLocale || manifestJson.locale
const locale = resolveI18nLocale(
platform,
Object.keys(locales),
fallbackLocale
)
if (warning) {
if (!fallbackLocale) {
console.warn()
} else if (locale !== fallbackLocale) {
console.warn()
}
}
return {
locale,
locales,
delimiters
}
}
function initLocales (dir, withMessages = true) {
if (!fs.existsSync(dir)) {
return {}
}
return fs.readdirSync(dir).reduce((res, filename) => {
if (path.extname(filename) === '.json') {
try {
res[path.basename(filename).replace('.json', '')] = withMessages
? parseJson(fs.readFileSync(path.join(dir, filename), 'utf8'))
: {}
} catch (e) {}
}
return res
}, {})
}
function resolveI18nLocale (platfrom, locales, locale) {
if (locale && locales.includes(locale)) {
return locale
}
const defaultLocales = ['zh-Hans', 'zh-Hant']
if (platfrom === 'app' || platfrom === 'h5') {
defaultLocales.unshift('en')
} else {
// 小程序
defaultLocales.push('en')
}
return defaultLocales.find(locale => locales.includes(locale)) || locales[0]
}
module.exports = {
initLocales,
initI18nOptions
}
const fs = require('fs')
const path = require('path')
const { compileI18nJsonStr } = require('@dcloudio/uni-i18n')
const { initI18nOptions } = require('@dcloudio/uni-cli-shared/lib/i18n')
const assetsDir = 'static'
function getAssetsCopyOption (from, options = {}) {
if (path.isAbsolute(from)) {
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR)
}, options)
return Object.assign(
{
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR)
},
options
)
}
}
const to = from
from = path.resolve(process.env.UNI_INPUT_DIR, from)
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR, to)
}, options)
return Object.assign(
{
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR, to)
},
options
)
}
}
// 暂未考虑动态添加static目录
......@@ -40,29 +47,38 @@ function getAssetsCopyOptions (assetsDir) {
copyOptions.push(mainAssetsCopyOption)
}
// 分包静态资源
process.UNI_SUBPACKAGES && Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
const subAssetsCopyOption = getAssetsCopyOption(path.join(root, assetsDir), {
ignore
process.UNI_SUBPACKAGES &&
Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
const subAssetsCopyOption = getAssetsCopyOption(
path.join(root, assetsDir),
{
ignore
}
)
if (subAssetsCopyOption) {
copyOptions.push(subAssetsCopyOption)
}
})
if (subAssetsCopyOption) {
copyOptions.push(subAssetsCopyOption)
}
})
return copyOptions
}
function getUniModulesAssetsCopyOptions (assetsDir) {
const copyOptions = []
global.uniModules.forEach(module => {
copyOptions.push(...getAssetsCopyOptions('uni_modules/' + module + '/' + assetsDir))
copyOptions.push(
...getAssetsCopyOptions('uni_modules/' + module + '/' + assetsDir)
)
})
return copyOptions
}
function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
const copyOptions = getAssetsCopyOptions(assetsDir).concat(getUniModulesAssetsCopyOptions(assetsDir))
const copyOptions = getAssetsCopyOptions(assetsDir).concat(
getUniModulesAssetsCopyOptions(assetsDir)
)
global.uniPlugin.copyWebpackOptions.forEach(copyWebpackOptions => {
const platformCopyOptions = copyWebpackOptions(platformOptions, vueOptions, copyOptions) || []
const platformCopyOptions =
copyWebpackOptions(platformOptions, vueOptions, copyOptions) || []
platformCopyOptions.forEach(copyOption => {
if (typeof copyOption === 'string') {
copyOption = getAssetsCopyOption(copyOption)
......@@ -76,6 +92,21 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
to: '[name].[ext]',
globOptions: {
ignored: require('./util').getWatchOptions().ignored
},
transform (content, path) {
if (path.endsWith('androidPrivacy.json')) {
const options = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
false,
true
)
if (!options) {
return content
}
return compileI18nJsonStr(content.toString(), options)
}
return content
}
})
}
......@@ -85,4 +116,4 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
module.exports = {
assetsDir,
getCopyWebpackPluginOptions
}
}
const fs = require('fs')
const path = require('path')
const fs = require("fs");
const path = require("path");
const loaderUtils = require('loader-utils')
const loaderUtils = require("loader-utils");
const {
parsePages,
normalizePath,
parsePagesJson,
parseManifestJson
} = require('@dcloudio/uni-cli-shared')
} = require("@dcloudio/uni-cli-shared");
const {
updateAppJson,
updatePageJson,
updateProjectJson
} = require('@dcloudio/uni-cli-shared/lib/cache')
} = require("@dcloudio/uni-cli-shared/lib/cache");
const {
initTheme,
parseTheme
} = require('@dcloudio/uni-cli-shared/lib/theme')
const { initTheme, parseTheme } = require("@dcloudio/uni-cli-shared/lib/theme");
const {
// pagesJsonJsFileName,
initAutoImportComponents
} = require('@dcloudio/uni-cli-shared/lib/pages')
} = require("@dcloudio/uni-cli-shared/lib/pages");
const uniI18n = require("@dcloudio/uni-cli-i18n");
const uniI18n = require('@dcloudio/uni-cli-i18n')
const parseStyle = require("./util").parseStyle;
const parseStyle = require('./util').parseStyle
const { initI18nOptions } = require("@dcloudio/uni-cli-shared/lib/i18n");
const { parseI18nJson } = require("@dcloudio/uni-i18n");
// 将开发者手动设置的 usingComponents 调整名称,方便与自动解析到的 usingComponents 做最后合并
function renameUsingComponents (jsonObj) {
function renameUsingComponents(jsonObj) {
if (jsonObj.usingComponents) {
jsonObj.customUsingComponents = jsonObj.usingComponents
delete jsonObj.usingComponents
jsonObj.customUsingComponents = jsonObj.usingComponents;
delete jsonObj.usingComponents;
}
return jsonObj
return jsonObj;
}
module.exports = function (content, map) {
this.cacheable && this.cacheable()
module.exports = function(content, map) {
this.cacheable && this.cacheable();
initTheme()
initTheme();
let isAppView = false
let isAppView = false;
if (this.resourceQuery) {
const params = loaderUtils.parseQuery(this.resourceQuery)
isAppView = params.type === 'view'
const params = loaderUtils.parseQuery(this.resourceQuery);
isAppView = params.type === "view";
}
// const pagesJsonJsPath = path.resolve(process.env.UNI_INPUT_DIR, pagesJsonJsFileName)
const manifestJsonPath = path.resolve(process.env.UNI_INPUT_DIR, 'manifest.json')
const manifestJson = parseManifestJson(fs.readFileSync(manifestJsonPath, 'utf8'))
const manifestJsonPath = path.resolve(
process.env.UNI_INPUT_DIR,
"manifest.json"
);
const manifestJson = parseManifestJson(
fs.readFileSync(manifestJsonPath, "utf8")
);
// this.addDependency(pagesJsonJsPath)
this.addDependency(manifestJsonPath)
this.addDependency(manifestJsonPath);
let pagesJson = parsePagesJson(content, {
addDependency: (file) => {
(process.UNI_PAGES_DEPS || (process.UNI_PAGES_DEPS = new Set())).add(normalizePath(file))
this.addDependency(file)
addDependency: file => {
(process.UNI_PAGES_DEPS || (process.UNI_PAGES_DEPS = new Set())).add(
normalizePath(file)
);
this.addDependency(file);
}
})
});
if (!pagesJson.pages || pagesJson.pages.length === 0) {
console.error(uniI18n.__('pagesLoader.pagesNodeCannotNull'))
process.exit(0)
console.error(uniI18n.__("pagesLoader.pagesNodeCannotNull"));
process.exit(0);
}
if (global.uniPlugin.defaultTheme) {
pagesJson = parseTheme(pagesJson)
this.addDependency(path.resolve(process.env.UNI_INPUT_DIR, 'theme.json'))
pagesJson = parseTheme(pagesJson);
this.addDependency(path.resolve(process.env.UNI_INPUT_DIR, "theme.json"));
}
// 组件自动导入配置
process.UNI_AUTO_SCAN_COMPONENTS = !(pagesJson.easycom && pagesJson.easycom.autoscan === false)
initAutoImportComponents(pagesJson.easycom)
process.UNI_AUTO_SCAN_COMPONENTS = !(
pagesJson.easycom && pagesJson.easycom.autoscan === false
);
initAutoImportComponents(pagesJson.easycom);
// TODO 与 usingComponents 放在一块读取设置
if (manifestJson.transformPx === false) {
process.UNI_TRANSFORM_PX = false
process.UNI_TRANSFORM_PX = false;
} else {
process.UNI_TRANSFORM_PX = true
process.UNI_TRANSFORM_PX = true;
}
if (process.env.UNI_PLATFORM === 'h5') {
return this.callback(null, require('./platforms/h5')(pagesJson, manifestJson, this), map)
if (process.env.UNI_PLATFORM === "h5") {
return this.callback(
null,
require("./platforms/h5")(pagesJson, manifestJson, this),
map
);
}
if (process.env.UNI_PLATFORM === 'quickapp-native') {
return this.callback(null, require('./platforms/quickapp-native')(pagesJson, manifestJson, this), map)
if (process.env.UNI_PLATFORM === "quickapp-native") {
return this.callback(
null,
require("./platforms/quickapp-native")(pagesJson, manifestJson, this),
map
);
}
// 仅限小程序
if (process.env.UNI_PLATFORM !== "app-plus") {
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
true,
true
);
if (i18nOptions) {
const { locale, locales, delimiters } = i18nOptions;
parseI18nJson(pagesJson, locales[locale], delimiters);
}
}
if (!process.env.UNI_USING_V3) {
parsePages(pagesJson, function (page) {
updatePageJson(page.path, renameUsingComponents(parseStyle(page.style)))
}, function (root, page) {
updatePageJson(normalizePath(path.join(root, page.path)), renameUsingComponents(
parseStyle(page.style, root)
))
})
parsePages(
pagesJson,
function(page) {
updatePageJson(
page.path,
renameUsingComponents(parseStyle(page.style))
);
},
function(root, page) {
updatePageJson(
normalizePath(path.join(root, page.path)),
renameUsingComponents(parseStyle(page.style, root))
);
}
);
}
const jsonFiles = require('./platforms/' + process.env.UNI_PLATFORM)(pagesJson, manifestJson, isAppView)
const jsonFiles = require("./platforms/" + process.env.UNI_PLATFORM)(
pagesJson,
manifestJson,
isAppView
);
if (jsonFiles && jsonFiles.length) {
if (process.env.UNI_USING_V3) {
let appConfigContent = ''
let appConfigContent = "";
jsonFiles.forEach(jsonFile => {
if (jsonFile) {
if (!isAppView && jsonFile.name === 'manifest.json') {
const content = JSON.parse(jsonFile.content)
if (!content.launch_path && content.plus['uni-app'].nvueLaunchMode === 'fast') {
console.log(uniI18n.__('pagesLoader.nvueFirstPageStartModeIsFast', { 0: 'https://ask.dcloud.net.cn/article/36749' }))
if (!isAppView && jsonFile.name === "manifest.json") {
const content = JSON.parse(jsonFile.content);
if (
!content.launch_path &&
content.plus["uni-app"].nvueLaunchMode === "fast"
) {
console.log(
uniI18n.__("pagesLoader.nvueFirstPageStartModeIsFast", {
0: "https://ask.dcloud.net.cn/article/36749"
})
);
}
}
if (jsonFile.name === 'define-pages.js') {
appConfigContent = jsonFile.content
if (jsonFile.name === "define-pages.js") {
appConfigContent = jsonFile.content;
} else {
// app-view 不需要生成 app-config-service.js,manifest.json
!isAppView && this.emitFile(jsonFile.name, jsonFile.content)
!isAppView && this.emitFile(jsonFile.name, jsonFile.content);
}
}
})
return this.callback(null, appConfigContent, map)
});
return this.callback(null, appConfigContent, map);
}
if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
let appConfigContent = ''
let appConfigContent = "";
jsonFiles.forEach(jsonFile => {
if (jsonFile) {
if (jsonFile.name === 'app-config.js' || jsonFile.name === 'define-pages.js') {
appConfigContent = jsonFile.content
if (
jsonFile.name === "app-config.js" ||
jsonFile.name === "define-pages.js"
) {
appConfigContent = jsonFile.content;
} else {
this.emitFile(jsonFile.name, jsonFile.content)
this.emitFile(jsonFile.name, jsonFile.content);
}
}
})
return this.callback(null, appConfigContent, map)
});
return this.callback(null, appConfigContent, map);
}
jsonFiles.forEach(jsonFile => {
if (jsonFile) {
if (jsonFile.name === 'app') {
updateAppJson(jsonFile.name, renameUsingComponents(jsonFile.content))
if (jsonFile.name === "app") {
updateAppJson(jsonFile.name, renameUsingComponents(jsonFile.content));
} else {
updateProjectJson(jsonFile.name, jsonFile.content)
updateProjectJson(jsonFile.name, jsonFile.content);
}
}
})
});
}
this.callback(null, '', map)
}
this.callback(null, "", map);
};
const {
initI18nOptions
} = require('@dcloudio/uni-cli-shared/lib/i18n')
function parseRoutes (config) {
const __uniRoutes = []
/* eslint-disable no-mixed-operators */
const tabBarList = (config.tabBar && config.tabBar.list || []).map(item => item.pagePath)
const tabBarList = ((config.tabBar && config.tabBar.list) || []).map(
item => item.pagePath
)
Object.keys(config.page).forEach(function (pagePath) {
const isTabBar = tabBarList.indexOf(pagePath) !== -1
const isQuit = isTabBar || (config.pages[0] === pagePath)
const isQuit = isTabBar || config.pages[0] === pagePath
const isNVue = !!config.page[pagePath].nvue
const route = {
path: '/' + pagePath,
......@@ -64,16 +70,27 @@ module.exports = function definePages (appJson) {
if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
appJson.automator = true
}
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
false,
true
)
if (i18nOptions) {
appJson.locale = ''
appJson.fallbackLocale = i18nOptions.locale
appJson.locales = i18nOptions.locales
}
return {
name: 'app-config-service.js',
content: `
var isReady=false;var onReadyCallbacks=[];
var isReady=false;var onReadyCallbacks=[];
var isServiceReady=false;var onServiceReadyCallbacks=[];
var __uniConfig = ${JSON.stringify(appJson, null)};
var __uniRoutes = ${JSON.stringify(__uniRoutes)};
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
__uniConfig.onServiceReady=function(callback){if(__uniConfig.serviceReady){callback()}else{onServiceReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"serviceReady",{get:function(){return isServiceReady},set:function(val){isServiceReady=val;if(!isServiceReady){return}const callbacks=onServiceReadyCallbacks.slice(0);onServiceReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
service.register("uni-app-config",{create(a,b,c){if(!__uniConfig.viewport){var d=b.weex.config.env.scale,e=b.weex.config.env.deviceWidth,f=Math.ceil(e/d);Object.assign(__uniConfig,{viewport:f,defaultFontSize:Math.round(f/20)})}return{instance:{__uniConfig:__uniConfig,__uniRoutes:__uniRoutes,${globalStatement}}}}});
`
}
}
}
......@@ -3,18 +3,18 @@ const fsExtra = require('fs-extra')
const path = require('path')
const merge = require('merge')
const {
normalizePath,
getFlexDirection
} = require('@dcloudio/uni-cli-shared')
const {
hasOwn,
parseStyle
} = require('../../util')
const { normalizePath, getFlexDirection } = require('@dcloudio/uni-cli-shared')
const { compileI18nJsonStr } = require('@dcloudio/uni-i18n')
const { initI18nOptions } = require('@dcloudio/uni-cli-shared/lib/i18n')
const { hasOwn, parseStyle } = require('../../util')
const wxPageOrientationMapping = {
auto: ['portrait-primary', 'portrait-secondary', 'landscape-primary', 'landscape-secondary'],
auto: [
'portrait-primary',
'portrait-secondary',
'landscape-primary',
'landscape-secondary'
],
portrait: ['portrait-primary', 'portrait-secondary'],
landscape: ['landscape-primary', 'landscape-secondary']
}
......@@ -58,13 +58,13 @@ function normalizeNetworkTimeout (appJson) {
function updateFileFlag (appJson) {
// 已经不再根据文件识别,理论可废弃此处的逻辑
if (
process.env.UNI_USING_V3 ||
process.env.UNI_USING_V3_NATIVE
) {
if (process.env.UNI_USING_V3 || process.env.UNI_USING_V3_NATIVE) {
return
}
const nvueCompilerFilePath = path.resolve(process.env.UNI_OUTPUT_DIR, '__uniappnvuecompiler.js')
const nvueCompilerFilePath = path.resolve(
process.env.UNI_OUTPUT_DIR,
'__uniappnvuecompiler.js'
)
const nvueCompilerExists = fs.existsSync(nvueCompilerFilePath)
if (appJson.nvueCompiler === 'uni-app') {
......@@ -77,7 +77,10 @@ function updateFileFlag (appJson) {
}
}
const rendererFilePath = path.resolve(process.env.UNI_OUTPUT_DIR, '__uniapprenderer.js')
const rendererFilePath = path.resolve(
process.env.UNI_OUTPUT_DIR,
'__uniapprenderer.js'
)
const rendererExists = fs.existsSync(rendererFilePath)
if (appJson.renderer === 'native') {
......@@ -92,9 +95,7 @@ function updateFileFlag (appJson) {
}
module.exports = function (pagesJson, userManifestJson, isAppView) {
const {
app
} = require('../mp')(pagesJson, userManifestJson)
const { app } = require('../mp')(pagesJson, userManifestJson)
const manifest = {
name: 'manifest'
......@@ -109,7 +110,9 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
const TABBAR_HEIGHT = 50
let manifestJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, './manifest.json'), 'utf8'))
let manifestJson = JSON.parse(
fs.readFileSync(path.resolve(__dirname, './manifest.json'), 'utf8')
)
// 状态栏
manifestJson.plus.statusbar = {
......@@ -120,7 +123,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
// 用户配置覆盖默认配置
manifestJson = merge.recursive(
true,
manifestJson, {
manifestJson,
{
id: userManifestJson.appid || '',
name: userManifestJson.name || '',
description: userManifestJson.description || '',
......@@ -129,14 +133,18 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
code: userManifestJson.versionCode
},
language: userManifestJson.locale
}, {
},
{
plus: userManifestJson['app-plus']
}
)
const splashscreenOptions = userManifestJson['app-plus'] && userManifestJson['app-plus'].splashscreen
const splashscreenOptions =
userManifestJson['app-plus'] && userManifestJson['app-plus'].splashscreen
const hasAlwaysShowBeforeRender = splashscreenOptions && hasOwn(splashscreenOptions, 'alwaysShowBeforeRender')
const hasAlwaysShowBeforeRender =
splashscreenOptions &&
hasOwn(splashscreenOptions, 'alwaysShowBeforeRender')
// 转换为老版本配置
if (manifestJson.plus.modules) {
......@@ -162,11 +170,14 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
}
// 屏幕启动方向
if (manifestJson.plus.screenOrientation) { // app平台优先使用 manifest 配置
if (manifestJson.plus.screenOrientation) {
// app平台优先使用 manifest 配置
manifestJson.screenOrientation = manifestJson.plus.screenOrientation
delete manifestJson.plus.screenOrientation
} else if (appJson.window && appJson.window.pageOrientation) { // 兼容微信小程序
const pageOrientationValue = wxPageOrientationMapping[appJson.window.pageOrientation]
} else if (appJson.window && appJson.window.pageOrientation) {
// 兼容微信小程序
const pageOrientationValue =
wxPageOrientationMapping[appJson.window.pageOrientation]
if (pageOrientationValue) {
manifestJson.screenOrientation = pageOrientationValue
}
......@@ -184,14 +195,13 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.permissions = {}
}
const nvuePages = process.env.UNI_USING_V3_NATIVE ? pagesJson.pages : (pagesJson.nvue && pagesJson.nvue.pages)
const nvuePages = process.env.UNI_USING_V3_NATIVE
? pagesJson.pages
: pagesJson.nvue && pagesJson.nvue.pages
if (nvuePages && nvuePages.length) {
const pages = {}
nvuePages.forEach(({
path,
style
}) => {
nvuePages.forEach(({ path, style }) => {
pages[path] = {
window: parseStyle(style),
nvue: true
......@@ -259,7 +269,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
}
}
}
if (!process.env.UNI_USING_COMPONENTS) { // 非自定义组件模式下,仍旧添加 render always
if (!process.env.UNI_USING_COMPONENTS) {
// 非自定义组件模式下,仍旧添加 render always
addRenderAlways()
}
} else {
......@@ -275,7 +286,9 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
appJson.nvueCompiler = 'weex'
}
appJson.nvueStyleCompiler = process.env.UNI_USING_NVUE_STYLE_COMPILER ? 'uni-app' : 'weex'
appJson.nvueStyleCompiler = process.env.UNI_USING_NVUE_STYLE_COMPILER
? 'uni-app'
: 'weex'
if (manifestJson.plus.renderer === 'native') {
appJson.renderer = 'native'
......@@ -292,10 +305,15 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
// 强制白屏检测
if (manifestJson.plus.splashscreen) {
if (!hasAlwaysShowBeforeRender && manifestJson.plus.splashscreen.autoclose === false) { // 兼容旧版本仅配置了 autoclose 为 false
if (
!hasAlwaysShowBeforeRender &&
manifestJson.plus.splashscreen.autoclose === false
) {
// 兼容旧版本仅配置了 autoclose 为 false
manifestJson.plus.splashscreen.alwaysShowBeforeRender = false
}
if (manifestJson.plus.splashscreen.alwaysShowBeforeRender) { // 白屏检测
if (manifestJson.plus.splashscreen.alwaysShowBeforeRender) {
// 白屏检测
if (!manifestJson.plus.splashscreen.target) {
manifestJson.plus.splashscreen.target = 'id:1'
}
......@@ -303,10 +321,12 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.plus.splashscreen.delay = 0
appJson.splashscreen.alwaysShowBeforeRender = true
} else { // 不启用白屏检测
} else {
// 不启用白屏检测
delete manifestJson.plus.splashscreen.target
if (manifestJson.plus.splashscreen.autoclose) { // 启用 uni-app 框架关闭 splash
if (manifestJson.plus.splashscreen.autoclose) {
// 启用 uni-app 框架关闭 splash
manifestJson.plus.splashscreen.autoclose = false // 原 5+ autoclose 改为 false
appJson.splashscreen.autoclose = true
}
......@@ -344,9 +364,14 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
const resources = {}
const nvuePages = (appJson.nvue && appJson.nvue.pages) || {}
for (const key in confusion.resources) {
if (path.extname(key) === '.js') { // 支持 js 混淆,过滤掉
if (path.extname(key) === '.js') {
// 支持 js 混淆,过滤掉
// 静态 js 文件
if (key.indexOf('hybrid/html') === 0 || key.indexOf('static/') === 0 || key.indexOf('/static/') !== -1) {
if (
key.indexOf('hybrid/html') === 0 ||
key.indexOf('static/') === 0 ||
key.indexOf('/static/') !== -1
) {
resources[key] = confusion.resources[key]
}
continue
......@@ -356,22 +381,24 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
} else {
resources[key.replace(/\.nvue$/, '.js')] = confusion.resources[key]
}
if (!Object.keys(nvuePages).find(path => {
const subNVues = nvuePages[path].window.subNVues || []
// TODO
return (path.replace(/\.html$/, '.nvue') === key || path.replace(/\.html$/, '.nvue') + '.nvue' === key) ||
subNVues.find(({
path
}) => path === key.replace(/\.nvue$/, ''))
}) && !pagesJson.pages.find(({
style = {}
}) => {
style = Object.assign(style, style['app-plus'])
const subNVues = style.subNVues || []
return subNVues.find(({
path
}) => path === key.replace(/\.nvue$/, ''))
})) {
if (
!Object.keys(nvuePages).find(path => {
const subNVues = nvuePages[path].window.subNVues || []
// TODO
return (
path.replace(/\.html$/, '.nvue') === key ||
path.replace(/\.html$/, '.nvue') + '.nvue' === key ||
subNVues.find(({ path }) => path === key.replace(/\.nvue$/, ''))
)
}) &&
!pagesJson.pages.find(({ style = {} }) => {
style = Object.assign(style, style['app-plus'])
const subNVues = style.subNVues || []
return subNVues.find(
({ path }) => path === key.replace(/\.nvue$/, '')
)
})
) {
throw new Error(`原生混淆页面未在项目内使用,错误的页面路径:${key}`)
}
}
......@@ -382,9 +409,12 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
const uniApp = require('../../../package.json')['uni-app']
manifestJson.plus['uni-app'] = uniApp
// 控制页类型
const control = (process.env.UNI_USING_V3 || process.env.UNI_USING_V3_NATIVE)
? 'uni-v3'
: (process.env.UNI_USING_V8 ? 'v8' : 'webview')
const control =
process.env.UNI_USING_V3 || process.env.UNI_USING_V3_NATIVE
? 'uni-v3'
: process.env.UNI_USING_V8
? 'v8'
: 'webview'
manifestJson.plus['uni-app'].control = control
manifestJson.plus['uni-app'].nvueCompiler = appJson.nvueCompiler
......@@ -415,7 +445,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
}
let isNVueEntryPage = appJson.nvue && appJson.nvue.entryPagePath
conditionPagePath = process.env.UNI_CLI_LAUNCH_PAGE_PATH || conditionPagePath
conditionPagePath =
process.env.UNI_CLI_LAUNCH_PAGE_PATH || conditionPagePath
if (conditionPagePath && appJson.nvue) {
isNVueEntryPage = `${conditionPagePath}.html` in appJson.nvue.pages
}
......@@ -455,8 +486,15 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.plus.launchwebview.render = 'always'
}
// 带 tab
if (pagesJson.tabBar && pagesJson.tabBar.list && pagesJson.tabBar.list.length) {
const tabBar = manifestJson.plus.tabBar = Object.assign({}, pagesJson.tabBar)
if (
pagesJson.tabBar &&
pagesJson.tabBar.list &&
pagesJson.tabBar.list.length
) {
const tabBar = (manifestJson.plus.tabBar = Object.assign(
{},
pagesJson.tabBar
))
const borderStyles = {
black: 'rgba(0,0,0,0.4)',
white: 'rgba(255,255,255,0.4)'
......@@ -477,13 +515,31 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.plus.launchwebview.id = '2'
} else {
// 首页是 tabBar 页面
const item = tabBar.list.find(page => page.pagePath === (process.env.UNI_USING_NATIVE ? appJson.entryPagePath
: entryPagePath))
const item = tabBar.list.find(
page =>
page.pagePath ===
(process.env.UNI_USING_NATIVE
? appJson.entryPagePath
: entryPagePath)
)
if (item) {
tabBar.child = ['lauchwebview']
tabBar.selected = tabBar.list.indexOf(item)
}
}
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
true,
true
)
if (i18nOptions) {
manifestJson.plus.tabBar = JSON.parse(
compileI18nJsonStr(JSON.stringify(tabBar), i18nOptions)
)
manifestJson.fallbackLocale = i18nOptions.locale
}
}
}
......@@ -521,11 +577,16 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
if (process.env.UNI_USING_V3 && process.env.UNI_OPT_SUBPACKAGES) {
appJson.subPackages = subPackages
}
return require('./index.v3')(appJson, manifestJson, {
manifest,
pagesJson,
normalizeNetworkTimeout
}, isAppView)
return require('./index.v3')(
appJson,
manifestJson,
{
manifest,
pagesJson,
normalizeNetworkTimeout
},
isAppView
)
}
return [app, manifest]
}
......@@ -444,7 +444,7 @@ module.exports = function (pagesJson, manifestJson, loader) {
return `
import Vue from 'vue'
${genLayoutComponentsCode(pagesJson)}
const locales = ${fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'locale')) ? 'require.context(\'./locale\', false, /\.json$/)' : '{keys(){return []}}'}
const locales = ${fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'locale')) ? 'require.context(\'./locale\', false, /.json$/)' : '{keys(){return []}}'}
global['____${h5.appid}____'] = true;
delete global['____${h5.appid}____'];
global.__uniConfig = ${JSON.stringify(pagesJson)};
......@@ -465,4 +465,4 @@ ${genRegisterPageVueComponentsCode(pageComponents)}
global.__uniRoutes=[${genPageRoutes(pageComponents).concat(genSystemRoutes()).join(',')}]
global.UniApp && new global.UniApp();
`
}
}
......@@ -12,16 +12,9 @@ const {
updateAppJsonUsingComponents
} = require('@dcloudio/uni-cli-shared/lib/cache')
const {
darkmode,
hasTheme
} = require('@dcloudio/uni-cli-shared/lib/theme')
const { darkmode, hasTheme } = require('@dcloudio/uni-cli-shared/lib/theme')
const {
hasOwn,
parseStyle,
trimMPJson
} = require('../util')
const { hasOwn, parseStyle, trimMPJson } = require('../util')
const uniI18n = require('@dcloudio/uni-cli-i18n')
......@@ -42,7 +35,9 @@ const pagesJson2AppJson = {
tabBar: function (name, value, json, fromJson) {
if (value && value.list && value.list.length) {
if (value.list.length < 2) {
console.error(uniI18n.__('pagesLoader.pagesTabbarMinItem2', { 0: 'tabBar.list' }))
console.error(
uniI18n.__('pagesLoader.pagesTabbarMinItem2', { 0: 'tabBar.list' })
)
}
const pages = json.pages
value.list.forEach((page, index) => {
......@@ -52,12 +47,16 @@ const pagesJson2AppJson = {
fromJson &&
fromJson.nvue &&
fromJson.nvue.pages &&
fromJson.nvue.pages.find(({
path
}) => path === (page.pagePath + '.html'))
fromJson.nvue.pages.find(
({ path }) => path === page.pagePath + '.html'
)
)
) {
console.error(uniI18n.__('pagesLoader.needInPagesNode', { 0: `pages.json tabBar['list'][${index}]['pagePath'] "${page.pagePath}"` }))
console.error(
uniI18n.__('pagesLoader.needInPagesNode', {
0: `pages.json tabBar['list'][${index}]['pagePath'] "${page.pagePath}"`
})
)
}
}
})
......@@ -74,7 +73,8 @@ const manifestJson2AppJson = {
}
function parseCondition (projectJson, pagesJson) {
if (process.env.NODE_ENV === 'development') { // 仅开发期间 condition 生效
if (process.env.NODE_ENV === 'development') {
// 仅开发期间 condition 生效
// 启动Condition
const condition = getCondition(pagesJson)
if (condition) {
......@@ -89,7 +89,6 @@ function parseCondition (projectJson, pagesJson) {
const pagesJson2ProjectJson = {}
const manifestJson2ProjectJson = {
name: function (name, value, json) {
if (!value) {
value = path.basename(process.env.UNI_INPUT_DIR)
......@@ -146,18 +145,26 @@ function getCondition (pagesJson) {
delete item.path
}
if (launchPagePath) {
if (item.pathName === launchPagePath && item.query === launchPageQuery) { // 指定了入口页
if (
item.pathName === launchPagePath &&
item.query === launchPageQuery
) {
// 指定了入口页
current = index
}
}
})
if (launchPagePath) {
if (current !== -1) { // 已存在
if (current !== -1) {
// 已存在
condition.current = current
} else { // 不存在
condition.list.push(Object.assign(launchPageOptions, {
id: condition.list.length
}))
} else {
// 不存在
condition.list.push(
Object.assign(launchPageOptions, {
id: condition.list.length
})
)
condition.current = condition.list.length - 1
}
}
......@@ -182,26 +189,31 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
const subPackages = {}
parsePages(pagesJson, function (page) {
app.pages.push(page.path)
}, function (root, page, subPackage) {
if (!isSupportSubPackages()) { // 不支持分包
app.pages.push(normalizePath(path.join(root, page.path)))
} else {
if (!subPackages[root]) {
subPackages[root] = {
root,
pages: []
}
Object.keys(subPackage).forEach(name => {
if (['root', 'pages'].indexOf(name) === -1) {
subPackages[root][name] = subPackage[name]
parsePages(
pagesJson,
function (page) {
app.pages.push(page.path)
},
function (root, page, subPackage) {
if (!isSupportSubPackages()) {
// 不支持分包
app.pages.push(normalizePath(path.join(root, page.path)))
} else {
if (!subPackages[root]) {
subPackages[root] = {
root,
pages: []
}
})
Object.keys(subPackage).forEach(name => {
if (['root', 'pages'].indexOf(name) === -1) {
subPackages[root][name] = subPackage[name]
}
})
}
subPackages[root].pages.push(page.path)
}
subPackages[root].pages.push(page.path)
}
})
)
Object.keys(subPackages).forEach(root => {
app.subPackages.push(subPackages[root])
......@@ -222,9 +234,12 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
const projectName = getPlatformProject()
const projectPath = projectName && path.resolve(process.env.VUE_CLI_CONTEXT || process.cwd(), projectName)
const projectPath =
projectName &&
path.resolve(process.env.VUE_CLI_CONTEXT || process.cwd(), projectName)
if (projectPath && fs.existsSync(projectPath)) { // 自定义 project.config.json
if (projectPath && fs.existsSync(projectPath)) {
// 自定义 project.config.json
const platform = process.env.UNI_PLATFORM
// app-plus时不需要处理平台配置到 app 中
......@@ -235,7 +250,8 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
Object.keys(platformJson).forEach(key => {
if (
!projectKeys.includes(key) && ['usingComponents', 'optimization'].indexOf(key) === -1
!projectKeys.includes(key) &&
['usingComponents', 'optimization'].indexOf(key) === -1
) {
// usingComponents 是编译模式开关,需要过滤,不能拷贝到 app
app[key] = platformJson[key]
......@@ -243,7 +259,11 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
})
}
if (process.env.UNI_PLATFORM === 'mp-weixin' || process.env.UNI_PLATFORM === 'mp-qq') { // 微信不需要生成,其他平台做拷贝
if (
process.env.UNI_PLATFORM === 'mp-weixin' ||
process.env.UNI_PLATFORM === 'mp-qq'
) {
// 微信不需要生成,其他平台做拷贝
return {
app: {
name: 'app',
......@@ -279,7 +299,10 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
const projectKeys = Object.keys(platformJson2ProjectJson)
Object.keys(platformJson).forEach(key => {
if (!projectKeys.includes(key) && ['usingComponents', 'optimization'].indexOf(key) === -1) {
if (
!projectKeys.includes(key) &&
['usingComponents', 'optimization'].indexOf(key) === -1
) {
// usingComponents 是编译模式开关,需要过滤,不能拷贝到 app
app[key] = platformJson[key]
}
......@@ -287,7 +310,10 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
}
// 引用了原生小程序组件,自动开启 ES6=>ES5
const wxcomponentsPath = path.resolve(process.env.UNI_INPUT_DIR, './wxcomponents')
const wxcomponentsPath = path.resolve(
process.env.UNI_INPUT_DIR,
'./wxcomponents'
)
if (fs.existsSync(wxcomponentsPath)) {
const wxcomponentsFiles = fs.readdirSync(wxcomponentsPath)
if (wxcomponentsFiles.length) {
......
import {
initVueI18n,
isI18nStr
} from '@dcloudio/uni-i18n'
import {
isStr
} from 'uni-shared'
import { initVueI18n, isI18nStr } from '@dcloudio/uni-i18n'
import { isStr } from 'uni-shared'
import en from './en.json'
import es from './es.json'
......@@ -23,7 +18,7 @@ const messages = {
let locale
if (__PLATFORM__ === 'h5') {
locale = (__uniConfig.locale || navigator.language)
locale = __uniConfig.locale || navigator.language
} else if (__PLATFORM__ === 'app-plus') {
if (typeof weex === 'object') {
locale = weex.requireModule('plus').getLanguage()
......@@ -32,9 +27,12 @@ if (__PLATFORM__ === 'h5') {
locale = __GLOBAL__.getSystemInfoSync().language
}
export const i18n = initVueI18n(locale, __PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {})
export const i18n = initVueI18n(
locale,
__PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {}
)
export const t = i18n.t
export const i18nMixin = i18n.mixin = {
export const i18nMixin = (i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate()
......@@ -48,7 +46,7 @@ export const i18nMixin = i18n.mixin = {
return t(key, values)
}
}
}
})
export const setLocale = i18n.setLocale
export const getLocale = i18n.getLocale
......@@ -57,7 +55,7 @@ export function initAppLocale (Vue, appVm, locale) {
locale: locale || i18n.getLocale()
})
const localeWatchers = []
appVm.$watchLocale = (fn) => {
appVm.$watchLocale = fn => {
localeWatchers.push(fn)
}
Object.defineProperty(appVm, '$locale', {
......@@ -88,10 +86,7 @@ export function formatI18n (message) {
return message
}
function resolveJsonObj (
jsonObj,
names
) {
function resolveJsonObj (jsonObj, names) {
if (names.length === 1) {
if (jsonObj) {
const value = jsonObj[names[0]]
......@@ -105,11 +100,8 @@ function resolveJsonObj (
return resolveJsonObj(jsonObj && jsonObj[name], names)
}
export function defineI18nProperties (
obj,
names
) {
return names.map((name) => defineI18nProperty(obj, name))
export function defineI18nProperties (obj, names) {
return names.map(name => defineI18nProperty(obj, name))
}
export function defineI18nProperty (obj, names) {
......@@ -143,9 +135,7 @@ export function initNavigationBarI18n (navigationBar) {
}
}
export function initPullToRefreshI18n (
pullToRefresh
) {
export function initPullToRefreshI18n (pullToRefresh) {
if (isEnableLocale()) {
const CAPTION = 'caption'
return defineI18nProperties(pullToRefresh, [
......@@ -154,4 +144,13 @@ export function initPullToRefreshI18n (
['contentrefresh', CAPTION]
])
}
}
}
export function initTabBarI18n (tabBar) {
if (isEnableLocale()) {
tabBar.list.forEach(item => {
defineI18nProperty(item, ['text'])
})
}
return tabBar
}
import {
isPlainObject
}
from 'uni-shared'
import { isPlainObject } from 'uni-shared'
import { initNavigationBarI18n } from 'uni-helpers/i18n'
function createButtonOnClick (index) {
return function onClick (btn) {
......@@ -28,20 +27,18 @@ function parseTitleNViewButtons (titleNView) {
return titleNView
}
export function parseTitleNView (routeOptions) {
export function parseTitleNView (id, routeOptions) {
const windowOptions = routeOptions.window
const titleNView = windowOptions.titleNView
routeOptions.meta.statusBarStyle = windowOptions.navigationBarTextStyle === 'black' ? 'dark' : 'light'
if ( // 无头
routeOptions.meta.statusBarStyle =
windowOptions.navigationBarTextStyle === 'black' ? 'dark' : 'light'
if (
// 无头
titleNView === false ||
titleNView === 'false' ||
(
windowOptions.navigationStyle === 'custom' &&
!isPlainObject(titleNView)
) || (
windowOptions.transparentTitle === 'always' &&
!isPlainObject(titleNView)
)
(windowOptions.navigationStyle === 'custom' &&
!isPlainObject(titleNView)) ||
(windowOptions.transparentTitle === 'always' && !isPlainObject(titleNView))
) {
return false
}
......@@ -54,28 +51,74 @@ export function parseTitleNView (routeOptions) {
always: 'float'
}
const navigationBarBackgroundColor = windowOptions.navigationBarBackgroundColor
const navigationBarBackgroundColor =
windowOptions.navigationBarBackgroundColor
const ret = {
autoBackButton: !routeOptions.meta.isQuit,
titleText: titleImage === '' ? windowOptions.navigationBarTitleText || '' : '',
titleColor: windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff',
titleText:
titleImage === '' ? windowOptions.navigationBarTitleText || '' : '',
titleColor:
windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff',
type: titleNViewTypeList[transparentTitle],
backgroundColor: (/^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) || navigationBarBackgroundColor === 'transparent') ? navigationBarBackgroundColor : '#f7f7f7',
tags: titleImage === '' ? [] : [{
tag: 'img',
src: titleImage,
position: {
left: 'auto',
top: 'auto',
width: 'auto',
height: '26px'
}
}]
backgroundColor:
/^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) ||
navigationBarBackgroundColor === 'transparent'
? navigationBarBackgroundColor
: '#f7f7f7',
tags:
titleImage === ''
? []
: [
{
tag: 'img',
src: titleImage,
position: {
left: 'auto',
top: 'auto',
width: 'auto',
height: '26px'
}
}
]
}
if (isPlainObject(titleNView)) {
return Object.assign(ret, parseTitleNViewButtons(titleNView))
return initTitleNViewI18n(
id,
Object.assign(ret, parseTitleNViewButtons(titleNView))
)
}
return initTitleNViewI18n(id, ret)
}
return ret
function initTitleNViewI18n (id, titleNView) {
const i18nResult = initNavigationBarI18n(titleNView)
if (!i18nResult) {
return titleNView
}
const [titleTextI18n, searchInputPlaceholderI18n] = i18nResult
if (titleTextI18n || searchInputPlaceholderI18n) {
uni.onLocaleChange(() => {
const webview = plus.webview.getWebviewById(id + '')
if (!webview) {
return
}
const newTitleNView = {}
if (titleTextI18n) {
newTitleNView.titleText = titleNView.titleText
}
if (searchInputPlaceholderI18n) {
newTitleNView.searchInput = {
placeholder: titleNView.searchInput.placeholder
}
}
if (process.env.NODE_ENV !== 'production') {
console.log('[uni-app] updateWebview', webview.id, newTitleNView)
}
webview.setStyle({
titleNView: newTitleNView
})
})
}
return titleNView
}
import {
parseTitleNView
} from './title-nview-parser'
import { parseTitleNView } from './title-nview-parser'
import {
parsePullToRefresh
} from './pull-to-refresh-parser'
import { parsePullToRefresh } from './pull-to-refresh-parser'
import {
parseStyleUnit
} from './style-unit-parser'
import { parseStyleUnit } from './style-unit-parser'
const WEBVIEW_STYLE_BLACKLIST = [
'navigationBarBackgroundColor',
......@@ -33,10 +27,12 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
}
// 合并
routeOptions.window = parseStyleUnit(Object.assign(
JSON.parse(JSON.stringify(__uniConfig.window || {})),
routeOptions.window || {}
))
routeOptions.window = parseStyleUnit(
Object.assign(
JSON.parse(JSON.stringify(__uniConfig.window || {})),
routeOptions.window || {}
)
)
Object.keys(routeOptions.window).forEach(name => {
if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) {
......@@ -45,7 +41,10 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
})
const backgroundColor = routeOptions.window.backgroundColor
if (/^#[a-z0-9]{6}$/i.test(backgroundColor) || backgroundColor === 'transparent') {
if (
/^#[a-z0-9]{6}$/i.test(backgroundColor) ||
backgroundColor === 'transparent'
) {
if (!webviewStyle.background) {
webviewStyle.background = backgroundColor
}
......@@ -54,7 +53,7 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
}
}
const titleNView = parseTitleNView(routeOptions)
const titleNView = parseTitleNView(id, routeOptions)
if (titleNView) {
if (
id === 1 &&
......@@ -79,7 +78,8 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
delete webviewStyle.popGesture
}
if (routeOptions.meta.isQuit) { // 退出
if (routeOptions.meta.isQuit) {
// 退出
webviewStyle.popGesture = plus.os.name === 'iOS' ? 'appback' : 'none'
}
......
import Vue from 'vue'
__uniConfig.tabBar = Vue.observable(__uniConfig.tabBar || {})
export const tabBar = __uniConfig.tabBar
import { initTabBarI18n } from 'uni-helpers/i18n'
__uniConfig.tabBar = Vue.observable(initTabBarI18n(__uniConfig.tabBar || {}))
export const tabBar = __uniConfig.tabBar
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册