Merge branch 'master' of github.com:NativeScript/NativeScript

This commit is contained in:
Martin Guillon
2021-06-09 09:51:06 +02:00
47 changed files with 1133 additions and 800 deletions

View File

@ -1,15 +1,15 @@
{
"extends": ["plugin:prettier/recommended"],
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"parser": "@typescript-eslint/parser",
"project": "tsconfig.eslint.json",
"warnOnUnsupportedTypeScriptVersion": false
"project": "tsconfig.eslint.json"
},
"plugins": ["prettier", "@nativescript"],
"plugins": ["@nativescript", "prettier"],
"extends": ["plugin:@nativescript/recommended", "prettier"],
"rules": {
"prettier/prettier": 2,
"@nativescript/no-nativescript-angular-imports": "warn",
"@nativescript/no-tns-core-modules-imports": "warn",
"@nativescript/no-duplicate-ns-imports": "warn"

View File

@ -1,3 +1,68 @@
## [8.0.7](https://github.com/NativeScript/NativeScript/compare/8.0.6-core...8.0.7) (2021-06-02)
### Bug Fixes
* **animations:** stop keyframe animations after View unloaded ([#9421](https://github.com/NativeScript/NativeScript/issues/9421)) ([04381fa](https://github.com/NativeScript/NativeScript/commit/04381fa3e74e9c277970fb282223abedd937b4c1))
* **box-shadow:** support for 'none' ([#9418](https://github.com/NativeScript/NativeScript/issues/9418)) ([263c920](https://github.com/NativeScript/NativeScript/commit/263c920cb8a4b22e257033006ce585ec32ca2605))
* **core:** guard unstable page/frame init contexts under async conditions ([#9428](https://github.com/NativeScript/NativeScript/issues/9428)) ([d3bc4d5](https://github.com/NativeScript/NativeScript/commit/d3bc4d5b82879ccb83483f99585127d981b43b38))
* **core:** typings for Utils.queueMacrotask and static methods on Observable ([#9425](https://github.com/NativeScript/NativeScript/issues/9425)) ([d589ac6](https://github.com/NativeScript/NativeScript/commit/d589ac600063416f3725c0abf8dfc88f556166db))
### Features
* **WebView:** allow JS bound window frame navigation to be intercepted through loadStarted ([#9430](https://github.com/NativeScript/NativeScript/issues/9430)) ([3806b85](https://github.com/NativeScript/NativeScript/commit/3806b85fcef01ad34327dda9cc2c88619b522c74))
## [8.0.6](https://github.com/NativeScript/NativeScript/compare/8.0.5-core...8.0.6) (2021-05-20)
### Bug Fixes
* **a11y:** add missing application event for fontScaleChanged ([#9396](https://github.com/NativeScript/NativeScript/issues/9396)) ([dac36c6](https://github.com/NativeScript/NativeScript/commit/dac36c68015512553689f6803d147da92f89cd93))
* **a11y:** font size ([#9395](https://github.com/NativeScript/NativeScript/issues/9395)) ([7a92c16](https://github.com/NativeScript/NativeScript/commit/7a92c1646f92f8afb9f8a87306cc90e8d2043e91))
* **Device:** don't cache device language & region ([#9394](https://github.com/NativeScript/NativeScript/issues/9394)) ([95596e8](https://github.com/NativeScript/NativeScript/commit/95596e82302bb945e6bf2126f19d9245e358cb79)), closes [#6082](https://github.com/NativeScript/NativeScript/issues/6082)
* **ios:** image with alpha resize ([#9386](https://github.com/NativeScript/NativeScript/issues/9386)) ([f380782](https://github.com/NativeScript/NativeScript/commit/f380782766b7034e4f776ad78e941fd9ac405c0b)), closes [#9385](https://github.com/NativeScript/NativeScript/issues/9385)
* **RootLayout:** prevent android touch event to pass through views underneath ([#9389](https://github.com/NativeScript/NativeScript/issues/9389)) ([0b2c190](https://github.com/NativeScript/NativeScript/commit/0b2c190662ceb63524049ac7792643414510858d))
### Features
* **text-view:** add returnPress ([#9390](https://github.com/NativeScript/NativeScript/issues/9390)) ([64adf5e](https://github.com/NativeScript/NativeScript/commit/64adf5ecfce5cae1582cbbf7d704e2ef9b75dd01)), closes [#4882](https://github.com/NativeScript/NativeScript/issues/4882)
* **Utils:** add dismissSoftInput helper ([#9392](https://github.com/NativeScript/NativeScript/issues/9392)) ([6cf4c59](https://github.com/NativeScript/NativeScript/commit/6cf4c5981b866c8a164eea0d53fd4c93875e8ba0)), closes [#4594](https://github.com/NativeScript/NativeScript/issues/4594)
* **web-view:** disableZoom property ([#9391](https://github.com/NativeScript/NativeScript/issues/9391)) ([7e878f8](https://github.com/NativeScript/NativeScript/commit/7e878f83a39478a7a33d89f08579df97db70fe00))
## [8.0.5](https://github.com/NativeScript/NativeScript/compare/8.0.4-core...8.0.5) (2021-05-10)
### Bug Fixes
* **android:** image asset handling regarding requestLegacyExternalStorage ([#9373](https://github.com/NativeScript/NativeScript/issues/9373)) ([f311151](https://github.com/NativeScript/NativeScript/commit/f3111514960ada615a69418b906620a638f8f476))
### Features
* **docs:** typedoc api reference ([#9378](https://github.com/NativeScript/NativeScript/issues/9378)) ([6d91c2a](https://github.com/NativeScript/NativeScript/commit/6d91c2a0195e07c182d2fccfb9c6f7d783acc4b7))
## [8.0.4](https://github.com/NativeScript/NativeScript/compare/8.0.3-core...8.0.4) (2021-05-05)
### Bug Fixes
* **core:** typings for showModal correction ([#9374](https://github.com/NativeScript/NativeScript/issues/9374)) ([9ec4042](https://github.com/NativeScript/NativeScript/commit/9ec404225ef0cff5f82d759fcdc7b85952e65c0d))
### Features
* add additional android global methods ([#9365](https://github.com/NativeScript/NativeScript/issues/9365)) ([a6cb46d](https://github.com/NativeScript/NativeScript/commit/a6cb46dac2d671221d9c0e972e8db89961b3e7c2))
## [8.0.3](https://github.com/NativeScript/NativeScript/compare/8.0.2-core...8.0.3) (2021-04-24)

View File

@ -1,76 +1,78 @@
# Contributor Covenant Code of Conduct
## Contributor Covenant Code of Conduct
## Our Pledge
### Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
Examples of behavior that contributes to creating a positive environment
include:
### Our Standards
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of behavior that contributes to a positive environment for our community include:
Examples of unacceptable behavior by participants include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
### Enforcement Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
### Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at . All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at the email addresses listed above in the [Reporting](#reporting) and [Escalation](#escalation) sections. All complaints will be reviewed and investigated promptly and fairly.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Attribution
### Enforcement Guidelines
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
[homepage]: https://www.contributor-covenant.org
#### 1. Correction
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
#### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
#### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
#### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the project community.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.0, available at [contributor-covenant.org/version/2/0/code_of_conduct](https://www.contributor-covenant.org/version/2/0/code_of_conduct).
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
For answers to common questions about this code of conduct, see the FAQ at
[contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are available at [contributor-covenant.org/translations](https://www.contributor-covenant.org/translations).

214
LICENSE
View File

@ -1,201 +1,19 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright OpenJS Foundation and other contributors, https://openjsf.org
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2020, nStudio, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,6 +1,6 @@
{
"name": "nativescript",
"version": "8.0.3",
"version": "8.0.7",
"license": "MIT",
"config": {
"npm_alias": "npm"
@ -83,6 +83,7 @@
"mocha-typescript": "^1.1.17",
"module-alias": "^2.2.2",
"nativescript": "~7.2.0",
"nativescript-typedoc-theme": "1.0.0",
"parse-css": "git+https://github.com/tabatkins/parse-css.git",
"parserlib": "^1.1.1",
"prettier": "~2.2.1",
@ -97,6 +98,7 @@
"ts-patch": "^1.3.0",
"tslib": "2.1.0",
"tslint": "6.1.3",
"typedoc": "^0.20.14",
"typescript": "4.1.4",
"webpack": "~4.44.1",
"webpack-cli": "~3.3.12"

View File

@ -1,7 +1,7 @@
{
"extends": "../../.eslintrc.json",
"rules": {},
"ignorePatterns": ["!**/*", "**/node_modules/**/*", "**/__tests__/**/*"],
"ignorePatterns": ["!**/*", "**/global-types.d.ts", "**/node_modules/**/*", "**/__tests__/**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],

11
packages/core/README.md Normal file
View File

@ -0,0 +1,11 @@
<p align="center">
<a href="http://www.nativescript.org">
<img alt="NativeScript" src="https://d1lfyz5kwt8vu9.cloudfront.net/nativescript-logo-2021.png" width="100"/>
</a>
</p>
## @nativescript/core
A JavaScript library providing an easy to use api for interacting with iOS and Android platform APIs.
[Learn more at docs.nativescript.org](https://docs.nativescript.org/)

View File

@ -92,7 +92,7 @@ function updateCurrentHelperClasses(): void {
const oldActiveFontScaleCategory = currentFontScaleCategory;
switch (fontScaleCategory) {
case FontScaleCategory.ExtraSmall: {
currentFontScaleCategory = fontScaleMediumCategoryClass;
currentFontScaleCategory = fontScaleExtraSmallCategoryClass;
break;
}
case FontScaleCategory.Medium: {

View File

@ -5,7 +5,7 @@ export const VALID_FONT_SCALES = global.isIOS // iOS supports a wider number of
export function getClosestValidFontScale(fontScale: number): number {
fontScale = Number(fontScale) || 1;
return VALID_FONT_SCALES.sort((a, b) => Math.abs(fontScale - a) - Math.abs(fontScale - b)).shift();
return VALID_FONT_SCALES.sort((a, b) => Math.abs(fontScale - a) - Math.abs(fontScale - b))[0];
}
export enum FontScaleCategory {

View File

@ -11,6 +11,7 @@ function fontScaleChanged(origFontScale: number) {
Application.notify({
eventName: Application.fontScaleChangedEvent,
object: Application,
newValue: currentFontScale,
});
}
}

View File

@ -11,6 +11,7 @@ function fontScaleChanged(origFontScale: number) {
Application.notify({
eventName: Application.fontScaleChangedEvent,
object: Application,
newValue: currentFontScale,
});
}
}

View File

@ -135,6 +135,16 @@ export interface SystemAppearanceChangedEventData extends ApplicationEventData {
newValue: 'light' | 'dark';
}
/**
* Event data containing information for font scale changed event.
*/
export interface FontScaleChangedEventData extends ApplicationEventData {
/**
* New font scale value.
*/
newValue: number;
}
/**
* Event data containing information about unhandled application errors.
*/
@ -328,6 +338,8 @@ export function on(event: 'orientationChanged', callback: (args: OrientationChan
*/
export function on(event: 'systemAppearanceChanged', callback: (args: SystemAppearanceChangedEventData) => void, thisArg?: any);
export function on(event: 'fontScaleChanged', callback: (args: FontScaleChangedEventData) => void, thisArg?: any);
/**
* Gets the orientation of the application.
* Available values: "portrait", "landscape", "unknown".

View File

@ -78,7 +78,7 @@ export class Observable {
/**
* String value used when hooking to propertyChange event.
*/
public static propertyChangeEvent: string;
static propertyChangeEvent: string;
/**
* A basic method signature to hook an event listener (shortcut alias to the addEventListener method).
@ -88,6 +88,8 @@ export class Observable {
*/
on(eventNames: string, callback: (data: EventData) => void, thisArg?: any);
static on(eventName: string, callback: any, thisArg?: any): void;
/**
* Raised when a propertyChange occurs.
*/
@ -101,11 +103,15 @@ export class Observable {
*/
once(event: string, callback: (data: EventData) => void, thisArg?: any);
static once(eventName: string, callback: any, thisArg?: any): void;
/**
* Shortcut alias to the removeEventListener method.
*/
off(eventNames: string, callback?: any, thisArg?: any);
static off(eventName: string, callback?: any, thisArg?: any): void;
/**
* Adds a listener for the specified event name.
* @param eventNames Comma delimited names of the events to attach the listener to.
@ -114,6 +120,8 @@ export class Observable {
*/
addEventListener(eventNames: string, callback: (data: EventData) => void, thisArg?: any);
static addEventListener(eventName: string, callback: any, thisArg?: any): void;
/**
* Removes listener(s) for the specified event name.
* @param eventNames Comma delimited names of the events the specified listener is associated with.
@ -122,6 +130,8 @@ export class Observable {
*/
removeEventListener(eventNames: string, callback?: any, thisArg?: any);
static removeEventListener(eventName: string, callback?: any, thisArg?: any): void;
/**
* Updates the specified property with the provided value.
*/

View File

@ -1,6 +1,7 @@
import { ImageAssetBase, getRequestedImageSize } from './image-asset-common';
import { path as fsPath, knownFolders } from '../file-system';
import { ad } from '../utils';
import { Screen } from '../platform';
export * from './image-asset-common';
export class ImageAsset extends ImageAssetBase {
@ -25,66 +26,20 @@ export class ImageAsset extends ImageAssetBase {
}
public getImageAsync(callback: (image, error) => void) {
const bitmapOptions = new android.graphics.BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
// read only the file size
let bitmap = android.graphics.BitmapFactory.decodeFile(this.android, bitmapOptions);
const sourceSize = {
width: bitmapOptions.outWidth,
height: bitmapOptions.outHeight,
};
const requestedSize = getRequestedImageSize(sourceSize, this.options);
const sampleSize = org.nativescript.widgets.image.Fetcher.calculateInSampleSize(bitmapOptions.outWidth, bitmapOptions.outHeight, requestedSize.width, requestedSize.height);
const finalBitmapOptions = new android.graphics.BitmapFactory.Options();
finalBitmapOptions.inSampleSize = sampleSize;
try {
let error = null;
// read as minimum bitmap as possible (slightly bigger than the requested size)
bitmap = android.graphics.BitmapFactory.decodeFile(this.android, finalBitmapOptions);
if (bitmap) {
if (requestedSize.width !== bitmap.getWidth() || requestedSize.height !== bitmap.getHeight()) {
// scale to exact size
bitmap = android.graphics.Bitmap.createScaledBitmap(bitmap, requestedSize.width, requestedSize.height, true);
}
const rotationAngle = calculateAngleFromFile(this.android);
if (rotationAngle !== 0) {
const matrix = new android.graphics.Matrix();
matrix.postRotate(rotationAngle);
bitmap = android.graphics.Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
}
if (!bitmap) {
error = "Asset '" + this.android + "' cannot be found.";
}
callback(bitmap, error);
} catch (ex) {
org.nativescript.widgets.Utils.loadImageAsync(
ad.getApplicationContext(),
this.android,
JSON.stringify(this.options || {}),
Screen.mainScreen.widthPixels,
Screen.mainScreen.heightPixels,
new org.nativescript.widgets.Utils.AsyncImageCallback({
onSuccess(bitmap) {
callback(bitmap, null);
},
onError(ex) {
callback(null, ex);
},
})
);
}
}
}
function calculateAngleFromFile(filename: string) {
let rotationAngle = 0;
const ei = new android.media.ExifInterface(filename);
const orientation = ei.getAttributeInt(android.media.ExifInterface.TAG_ORIENTATION, android.media.ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case android.media.ExifInterface.ORIENTATION_ROTATE_90:
rotationAngle = 90;
break;
case android.media.ExifInterface.ORIENTATION_ROTATE_180:
rotationAngle = 180;
break;
case android.media.ExifInterface.ORIENTATION_ROTATE_270:
rotationAngle = 270;
break;
}
return rotationAngle;
}

View File

@ -340,7 +340,8 @@ export class ImageSource implements ImageSourceDefinition {
const dim = getScaledDimensions(size.width, size.height, maxSize);
const newSize: CGSize = CGSizeMake(dim.width, dim.height);
UIGraphicsBeginImageContextWithOptions(newSize, true, this.ios.scale);
UIGraphicsBeginImageContextWithOptions(newSize, options?.opaque ?? false, this.ios.scale);
this.ios.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
const resizedImage = UIGraphicsGetImageFromCurrentImageContext();

View File

@ -20,6 +20,7 @@ export declare const Application: {
lowMemoryEvent: string;
orientationChangedEvent: string;
systemAppearanceChangedEvent: string;
fontScaleChangedEvent: string;
systemAppearanceChanged: typeof systemAppearanceChanged;
getMainEntry: typeof getMainEntry;
getRootView: typeof getRootView;
@ -100,12 +101,13 @@ export type { InstrumentationMode, TimerInfo } from './profiling';
export { encoding } from './text';
export * from './trace';
export * from './ui';
import { GC, isFontIconURI, isDataURI, isFileOrResourcePath, executeOnMainThread, mainThreadify, isMainThread, dispatchToMainThread, releaseNativeObject, getModuleName, openFile, openUrl, isRealDevice, layout, ad as androidUtils, iOSNativeHelper as iosUtils, Source, escapeRegexSymbols, convertString } from './utils';
import { GC, isFontIconURI, isDataURI, isFileOrResourcePath, executeOnMainThread, mainThreadify, isMainThread, dispatchToMainThread, releaseNativeObject, getModuleName, openFile, openUrl, isRealDevice, layout, ad as androidUtils, iOSNativeHelper as iosUtils, Source, escapeRegexSymbols, convertString, dismissSoftInput, queueMacrotask } from './utils';
import { ClassInfo, getClass, getBaseClasses, getClassInfo, isBoolean, isDefined, isFunction, isNullOrUndefined, isNumber, isObject, isString, isUndefined, toUIString, verifyCallback } from './utils/types';
export declare const Utils: {
GC: typeof GC;
RESOURCE_PREFIX: string;
FILE_PREFIX: string;
queueMacrotask: typeof queueMacrotask;
isFontIconURI: typeof isFontIconURI;
isDataURI: typeof isDataURI;
isFileOrResourcePath: typeof isFileOrResourcePath;
@ -143,5 +145,6 @@ export declare const Utils: {
isUndefined: typeof isUndefined;
toUIString: typeof toUIString;
verifyCallback: typeof verifyCallback;
dismissSoftInput: typeof dismissSoftInput;
};
export { XmlParser, ParserEventType, ParserEvent } from './xml';

View File

@ -5,7 +5,7 @@ import './globals';
export { iOSApplication, AndroidApplication } from './application';
export type { ApplicationEventData, LaunchEventData, OrientationChangedEventData, UnhandledErrorEventData, DiscardedErrorEventData, CssChangedEventData, LoadAppCSSEventData, AndroidActivityEventData, AndroidActivityBundleEventData, AndroidActivityRequestPermissionsEventData, AndroidActivityResultEventData, AndroidActivityNewIntentEventData, AndroidActivityBackPressedEventData, SystemAppearanceChangedEventData } from './application';
import { launchEvent, displayedEvent, uncaughtErrorEvent, discardedErrorEvent, suspendEvent, resumeEvent, exitEvent, lowMemoryEvent, orientationChangedEvent, systemAppearanceChanged, systemAppearanceChangedEvent, getMainEntry, getRootView, _resetRootView, getResources, setResources, setCssFileName, getCssFileName, loadAppCss, addCss, on, off, notify, hasListeners, run, orientation, getNativeApplication, hasLaunched, android as appAndroid, ios as iosApp, systemAppearance } from './application';
import { fontScaleChangedEvent, launchEvent, displayedEvent, uncaughtErrorEvent, discardedErrorEvent, suspendEvent, resumeEvent, exitEvent, lowMemoryEvent, orientationChangedEvent, systemAppearanceChanged, systemAppearanceChangedEvent, getMainEntry, getRootView, _resetRootView, getResources, setResources, setCssFileName, getCssFileName, loadAppCss, addCss, on, off, notify, hasListeners, run, orientation, getNativeApplication, hasLaunched, android as appAndroid, ios as iosApp, systemAppearance } from './application';
export const Application = {
launchEvent,
displayedEvent,
@ -18,6 +18,7 @@ export const Application = {
orientationChangedEvent,
systemAppearanceChangedEvent,
systemAppearanceChanged,
fontScaleChangedEvent,
getMainEntry,
getRootView,
@ -121,7 +122,7 @@ export * from './trace';
export * from './ui';
import { GC, isFontIconURI, isDataURI, isFileOrResourcePath, executeOnMainThread, mainThreadify, isMainThread, dispatchToMainThread, queueMacrotask, releaseNativeObject, getModuleName, openFile, openUrl, isRealDevice, layout, ad as androidUtils, iOSNativeHelper as iosUtils, Source, RESOURCE_PREFIX, FILE_PREFIX, escapeRegexSymbols, convertString } from './utils';
import { GC, isFontIconURI, isDataURI, isFileOrResourcePath, executeOnMainThread, mainThreadify, isMainThread, dispatchToMainThread, queueMacrotask, releaseNativeObject, getModuleName, openFile, openUrl, isRealDevice, layout, ad as androidUtils, iOSNativeHelper as iosUtils, Source, RESOURCE_PREFIX, FILE_PREFIX, escapeRegexSymbols, convertString, dismissSoftInput } from './utils';
import { ClassInfo, getClass, getBaseClasses, getClassInfo, isBoolean, isDefined, isFunction, isNullOrUndefined, isNumber, isObject, isString, isUndefined, toUIString, verifyCallback } from './utils/types';
export const Utils = {
@ -169,6 +170,7 @@ export const Utils = {
isUndefined,
toUIString,
verifyCallback,
dismissSoftInput,
};
export { XmlParser, ParserEventType, ParserEvent } from './xml';

View File

@ -2,8 +2,8 @@
"name": "@akylas/nativescript",
"main": "index",
"types": "index.d.ts",
"description": "NativeScript Core Modules",
"version": "8.0.3",
"description": "A JavaScript library providing an easy to use api for interacting with iOS and Android platform APIs.",
"version": "8.0.7",
"homepage": "https://nativescript.org",
"repository": {
"type": "git",

View File

@ -67,8 +67,6 @@ class DeviceRef {
private _sdkVersion: string;
private _deviceType: 'Phone' | 'Tablet';
private _uuid: string;
private _language: string;
private _region: string;
get manufacturer(): string {
if (!this._manufacturer) {
@ -130,19 +128,11 @@ class DeviceRef {
}
get language(): string {
if (!this._language) {
this._language = java.util.Locale.getDefault().getLanguage().replace('_', '-');
}
return this._language;
return java.util.Locale.getDefault().getLanguage().replace('_', '-');
}
get region(): string {
if (!this._region) {
this._region = java.util.Locale.getDefault().getCountry();
}
return this._region;
return java.util.Locale.getDefault().getCountry();
}
}

View File

@ -10,8 +10,6 @@ class DeviceRef {
private _osVersion: string;
private _sdkVersion: string;
private _deviceType: 'Phone' | 'Tablet';
private _language: string;
private _region: string;
get manufacturer(): string {
return 'Apple';
@ -72,20 +70,11 @@ class DeviceRef {
}
get language(): string {
if (!this._language) {
const languages = NSLocale.preferredLanguages;
this._language = languages[0];
}
return this._language;
return NSLocale.preferredLanguages[0];
}
get region(): string {
if (!this._region) {
this._region = NSLocale.currentLocale.objectForKey(NSLocaleCountryCode);
}
return this._region;
return NSLocale.currentLocale.objectForKey(NSLocaleCountryCode);
}
}

View File

@ -353,6 +353,9 @@ export class ActionBar extends ActionBarBase {
}
private setColor(navBar: UINavigationBar, color?: Color) {
if (!navBar) {
return;
}
if (color) {
navBar.titleTextAttributes = <any>{
[NSForegroundColorAttributeName]: color.ios,
@ -443,13 +446,12 @@ export class ActionBar extends ActionBarBase {
}
private get navBar(): UINavigationBar {
const page = this.page;
// Page should be attached to frame to update the action bar.
if (!page || !page.frame) {
if (this.page?.frame?.ios?.controller) {
return (<UINavigationController>this.page.frame.ios.controller).navigationBar;
} else {
return undefined;
}
return (<UINavigationController>page.frame.ios.controller).navigationBar;
}
[colorProperty.getDefault](): UIColor {

View File

@ -224,7 +224,7 @@ export class Frame extends FrameBase {
this._ios._disableNavBarAnimation = disableNavBarAnimationCache;
}
if (this._ios.controller.navigationBar) {
if (this._ios.controller?.navigationBar) {
this._ios.controller.navigationBar.userInteractionEnabled = this.navigationQueueIsEmpty();
}
@ -666,8 +666,10 @@ class iOSFrame implements iOSFrameDefinition {
}
public set showNavigationBar(value: boolean) {
this._showNavigationBar = value;
if (this._controller) {
this._controller.setNavigationBarHiddenAnimated(!value, !this._disableNavBarAnimation);
}
}
public get navBarVisibility(): 'auto' | 'never' | 'always' {
return this._navBarVisibility;

View File

@ -10,6 +10,26 @@ export class RootLayout extends RootLayoutBase {
super();
}
insertChild(view: View, atIndex: number): void {
super.insertChild(view, atIndex);
if (!view.hasGestureObservers()) {
// block tap events from going through to layers behind the view
view.nativeViewProtected.setOnTouchListener(
new android.view.View.OnTouchListener({
onTouch: function (view, event) {
return true;
},
})
);
}
}
removeChild(view: View): void {
if (view.hasGestureObservers()) {
view.nativeViewProtected.setOnTouchListener(null);
}
super.removeChild(view);
}
protected _bringToFront(view: View) {
(<android.view.View>view.nativeViewProtected).bringToFront();
}

View File

@ -177,7 +177,9 @@ class UIViewControllerImpl extends UIViewController {
}
// If page was shown with custom animation - we need to set the navigationController.delegate to the animatedDelegate.
if (frame.ios?.controller) {
frame.ios.controller.delegate = this[DELEGATE];
}
frame._processNavigationQueue(owner);

View File

@ -40,6 +40,10 @@ export function parseCSSShadow(value: string): CSSShadow {
const first = parts[0];
const last = parts[parts.length - 1];
if (first === 'none') {
return null;
}
let colorRaw = 'black';
if (!isLength(first) && first !== 'inset') {
colorRaw = first;

View File

@ -452,6 +452,7 @@ export class CssState {
public onUnloaded(): void {
this.unsubscribeFromDynamicUpdates();
this.stopKeyframeAnimations();
}
@profile

View File

@ -447,6 +447,16 @@ export class TextBase extends TextBaseCommon {
org.nativescript.widgets.ViewHelper.setPaddingLeft(this.nativeTextViewProtected, Length.toDevicePixels(value, 0) + Length.toDevicePixels(this.style.borderLeftWidth, 0));
}
[accessibilityIdentifierProperty.setNative](value: string): void {
// we override the default setter to apply it on nativeTextViewProtected
const id = Utils.ad.resources.getId(':id/nativescript_accessibility_id');
if (id) {
this.nativeTextViewProtected.setTag(id, value);
this.nativeTextViewProtected.setTag(value);
}
}
_setNativeText(reset = false): void {
if (reset) {
this.nativeTextViewProtected.setText(null);

View File

@ -28,6 +28,10 @@ export class TextView extends TextViewBaseCommon {
this.nativeTextViewProtected.setMaxLines(value);
}
public _onReturnPress() {
this.notify({ eventName: TextView.returnPressEvent, object: this });
}
}
TextView.prototype.recycleNativeView = 'auto';

View File

@ -167,6 +167,10 @@ export class TextView extends TextViewBaseCommon {
}
}
if (replacementString === '\n') {
this.notify({ eventName: TextView.returnPressEvent, object: this });
}
if (this.formattedText) {
_updateCharactersInRangeReplacementString(this.formattedText, range.location, range.length, replacementString);
}

View File

@ -3,6 +3,7 @@ import { EditableTextBase } from '../editable-text-base';
import { Property } from '../core/properties';
export class TextViewBase extends EditableTextBase implements TextViewDefinition {
public static returnPressEvent = 'returnPress';
public maxLines: number;
}

View File

@ -1,4 +1,4 @@
import { WebViewBase, WebViewClient } from './web-view-common';
import { disableZoomProperty, WebViewBase, WebViewClient } from './web-view-common';
import { Trace } from '../../trace';
import { knownFolders } from '../../file-system';
@ -107,6 +107,7 @@ export class WebView extends WebViewBase {
const client = new WebViewClient(<any>this);
nativeView.setWebViewClient(client);
(<any>nativeView).client = client;
this._disableZoom(this.disableZoom);
}
public disposeNativeView() {
@ -119,6 +120,19 @@ export class WebView extends WebViewBase {
super.disposeNativeView();
}
private _disableZoom(value: boolean) {
if (this.nativeView && value) {
const settings = this.nativeView.getSettings();
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(false);
settings.setDisplayZoomControls(false);
}
}
[disableZoomProperty.setNative](value: boolean) {
this._disableZoom(value);
}
public _loadUrl(src: string) {
const nativeView = this.nativeViewProtected;
if (!nativeView) {

View File

@ -1,5 +1,5 @@
import { WebViewNavigationType } from '.';
import { WebViewBase } from './web-view-common';
import { disableZoomProperty, WebViewBase } from './web-view-common';
import { profile } from '../../profiling';
import { Trace } from '../../trace';
export * from './web-view-common';
@ -96,9 +96,73 @@ class WKNavigationDelegateImpl extends NSObject implements WKNavigationDelegate
}
}
@NativeClass
class WKUIDelegateImpl extends NSObject implements WKUIDelegate {
public static ObjCProtocols = [WKUIDelegate];
public static initWithOwner(owner: WeakRef<WebView>): WKUIDelegateImpl {
const handler = <WKUIDelegateImpl>WKUIDelegateImpl.new();
handler._owner = owner;
return handler;
}
private _owner: WeakRef<WebView>;
webViewCreateWebViewWithConfigurationForNavigationActionWindowFeatures(webView: WKWebView, configuration: WKWebViewConfiguration, navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures): WKWebView {
if (navigationAction && (!navigationAction.targetFrame || (navigationAction.targetFrame && !navigationAction.targetFrame.mainFrame))) {
webView.loadRequest(navigationAction.request);
}
return null;
}
}
@NativeClass
@ObjCClass(UIScrollViewDelegate)
class UIScrollViewDelegateImpl extends NSObject implements UIScrollViewDelegate {
public static initWithOwner(owner: WeakRef<WebView>): UIScrollViewDelegateImpl {
const handler = <UIScrollViewDelegateImpl>UIScrollViewDelegateImpl.new();
handler._owner = owner;
return handler;
}
private _owner: WeakRef<WebView>;
private _initCurrentValues(scrollView: UIScrollView) {
const owner = this._owner.get();
if (owner && (owner._minimumZoomScale === undefined || owner._maximumZoomScale === undefined || owner._zoomScale === undefined)) {
owner._minimumZoomScale = scrollView.minimumZoomScale;
owner._maximumZoomScale = scrollView.maximumZoomScale;
owner._zoomScale = scrollView.zoomScale;
}
}
private _handleDisableZoom(scrollView: UIScrollView) {
const owner = this._owner.get();
if (owner.disableZoom) {
this._initCurrentValues(scrollView);
scrollView.maximumZoomScale = 1.0;
scrollView.minimumZoomScale = 1.0;
scrollView.zoomScale = 1.0;
}
}
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView) {
this._handleDisableZoom(scrollView);
}
scrollViewDidZoom(scrollView) {
this._handleDisableZoom(scrollView);
}
}
export class WebView extends WebViewBase {
nativeViewProtected: WKWebView;
private _delegate: any;
private _delegate: WKNavigationDelegateImpl;
private _scrollDelegate: UIScrollViewDelegateImpl;
private _uiDelegate: WKUIDelegateImpl;
_maximumZoomScale;
_minimumZoomScale;
_zoomScale;
createNativeView() {
const jScript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'initial-scale=1.0'); document.getElementsByTagName('head')[0].appendChild(meta);";
@ -118,7 +182,11 @@ export class WebView extends WebViewBase {
initNativeView() {
super.initNativeView();
this._delegate = WKNavigationDelegateImpl.initWithOwner(new WeakRef(this));
this._scrollDelegate = UIScrollViewDelegateImpl.initWithOwner(new WeakRef(this));
this._uiDelegate = WKUIDelegateImpl.initWithOwner(new WeakRef(this));
this.ios.navigationDelegate = this._delegate;
this.ios.scrollView.delegate = this._scrollDelegate;
this.ios.UIDelegate = this._uiDelegate;
}
@profile
@ -171,4 +239,17 @@ export class WebView extends WebViewBase {
public reload() {
this.ios.reload();
}
[disableZoomProperty.setNative](value: boolean) {
if (!value && typeof this._minimumZoomScale === 'number' && typeof this._maximumZoomScale === 'number' && typeof this._zoomScale === 'number') {
if (this.ios.scrollView) {
this.ios.scrollView.minimumZoomScale = this._minimumZoomScale;
this.ios.scrollView.maximumZoomScale = this._maximumZoomScale;
this.ios.scrollView.zoomScale = this._zoomScale;
this._minimumZoomScale = undefined;
this._maximumZoomScale = undefined;
this._zoomScale = undefined;
}
}
}
}

View File

@ -3,11 +3,14 @@ import { ContainerView, CSSType } from '../core/view';
import { Property } from '../core/properties';
import { EventData } from '../../data/observable';
import { knownFolders } from '../../file-system';
import { booleanConverter } from '../core/view-base';
export * from './web-view-interfaces';
export const srcProperty = new Property<WebViewBase, string>({ name: 'src' });
export const disableZoomProperty = new Property<WebViewBase, boolean>({ name: 'disableZoom', defaultValue: false, valueConverter: booleanConverter });
@CSSType('WebView')
export abstract class WebViewBase extends ContainerView {
public static loadStartedEvent = 'loadStarted';
@ -15,6 +18,8 @@ export abstract class WebViewBase extends ContainerView {
public src: string;
public disableZoom: boolean;
public _onLoadFinished(url: string, error?: string) {
const args = <LoadEventData>{
eventName: WebViewBase.loadFinishedEvent,
@ -102,3 +107,4 @@ export interface WebViewBase {
}
srcProperty.register(WebViewBase);
disableZoomProperty.register(WebViewBase);

View File

@ -167,3 +167,7 @@ Please ensure you have your manifest correctly configured with the FileProvider.
export function isRealDevice(): boolean {
return ad.isRealDevice();
}
export function dismissSoftInput(nativeView?: any): void {
ad.dismissSoftInput(nativeView);
}

View File

@ -286,3 +286,8 @@ export function eliminateDuplicates(arr: Array<any>): Array<any>;
* Checks whether the application is running on real device and not on simulator/emulator.
*/
export function isRealDevice(): boolean;
/**
* Hides the soft input method, usually a soft keyboard.
*/
export function dismissSoftInput(nativeView?: any): void;

View File

@ -48,3 +48,10 @@ export function isRealDevice(): boolean {
}
export const ad = 0;
export function dismissSoftInput(nativeView?: UIView): void {
if (nativeView instanceof UIView && !nativeView.isFirstResponder) {
return;
}
UIApplication.sharedApplication.sendActionToFromForEvent('resignFirstResponder', null, null, null);
}

View File

@ -1,11 +1,6 @@
declare module org {
module nativescript {
module widgets {
export class Utils {
public static drawBoxShadow(view: android.view.View, value: string): void;
}
export class BoxShadowDrawable {
public constructor(drawable: android.graphics.drawable.Drawable, value: string);
public getWrappedDrawable(): android.graphics.drawable.Drawable;
@ -632,3 +627,34 @@
}
}
}
declare module org {
export module nativescript {
export module widgets {
export class Utils {
public static class: java.lang.Class<org.nativescript.widgets.Utils>;
public static loadImageAsync(param0: globalAndroid.content.Context, param1: string, param2: string, param3: number, param4: number, param5: org.nativescript.widgets.Utils.AsyncImageCallback): void;
public static drawBoxShadow(param0: globalAndroid.view.View, param1: string): void;
public constructor();
}
export module Utils {
export class AsyncImageCallback {
public static class: java.lang.Class<org.nativescript.widgets.Utils.AsyncImageCallback>;
/**
* Constructs a new instance of the org.nativescript.widgets.Utils$AsyncImageCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onSuccess(param0: globalAndroid.graphics.Bitmap): void;
onError(param0: java.lang.Exception): void;
});
public constructor();
public onSuccess(param0: globalAndroid.graphics.Bitmap): void;
public onError(param0: java.lang.Exception): void;
}
export class ImageAssetOptions {
public static class: java.lang.Class<org.nativescript.widgets.Utils.ImageAssetOptions>;
}
}
}
}
}

View File

@ -78,6 +78,7 @@ dependencies {
implementation 'androidx.viewpager:viewpager:' + androidxVersion
implementation 'androidx.fragment:fragment:' + androidxVersion
implementation 'androidx.transition:transition:' + androidxVersion
implementation "androidx.exifinterface:exifinterface:1.3.2"
} else {
println 'Using support library'
implementation 'com.android.support:support-v4:' + computeSupportVersion()

View File

@ -17,13 +17,17 @@
package org.nativescript.widgets.image;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Matrix;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import androidx.exifinterface.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;
import android.util.TypedValue;
@ -34,6 +38,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -257,8 +262,9 @@ public class Fetcher extends Worker {
if (debuggable > 0) {
Log.v(TAG, "process: " + uri);
}
if (uri.startsWith(FILE_PREFIX)) {
if(uri.startsWith(CONTENT_PREFIX)){
return decodeSampledBitmapFromContent(uri,mResolver , decodeWidth, decodeHeight, keepAspectRatio, getCache());
}else if (uri.startsWith(FILE_PREFIX)) {
String filename = uri.substring(FILE_PREFIX.length());
return decodeSampledBitmapFromFile(filename, decodeWidth, decodeHeight, keepAspectRatio, getCache());
} else if (uri.startsWith(RESOURCE_PREFIX)) {
@ -474,6 +480,62 @@ public class Fetcher extends Worker {
return scaleAndRotateBitmap(bitmap, ei, reqWidth, reqHeight, keepAspectRatio);
}
private static void closePfd(ParcelFileDescriptor pfd){
if(pfd != null){
try {
pfd.close();
} catch (IOException ignored) {}
}
}
/**
* Decode and sample down a bitmap from a file to the requested width and height.
*
* @param content The content uri of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @param cache The Cache used to find candidate bitmaps for use with inBitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromContent(String content, ContentResolver resolver, int reqWidth, int reqHeight,
boolean keepAspectRatio, Cache cache) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Uri uri = android.net.Uri.parse(content);
ParcelFileDescriptor pfd = null;
try {
pfd = resolver.openFileDescriptor(uri, "r");
BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, options);
} catch (FileNotFoundException e) {
Log.v(TAG, "File not found " + content);
closePfd(pfd);
return null;
}
options.inSampleSize = calculateInSampleSize(options.outWidth, options.outHeight, reqWidth, reqHeight);
// If we're running on Honeycomb or newer, try to use inBitmap
if (Utils.hasHoneycomb()) {
addInBitmapOptions(options, cache);
}
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
final Bitmap bitmap = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, options);
ExifInterface ei = getExifInterface(pfd.getFileDescriptor());
closePfd(pfd);
return scaleAndRotateBitmap(bitmap, ei, reqWidth, reqHeight, keepAspectRatio);
}
private static Bitmap scaleAndRotateBitmap(Bitmap bitmap, ExifInterface ei, int reqWidth, int reqHeight,
boolean keepAspectRatio) {
if (bitmap == null) {

View File

@ -16,6 +16,7 @@
package org.nativescript.widgets.image;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
@ -37,6 +38,7 @@ public abstract class Worker {
protected static final String RESOURCE_PREFIX = "res://";
protected static final String FILE_PREFIX = "file:///";
protected static final String CONTENT_PREFIX = "content://";
static final String TAG = "JS";
private static final int FADE_IN_TIME = 200;
@ -49,7 +51,7 @@ public abstract class Worker {
protected boolean mPauseWork = false;
protected Resources mResources;
protected ContentResolver mResolver;
private static final int MESSAGE_CLEAR = 0;
private static final int MESSAGE_INIT_DISK_CACHE = 1;
private static final int MESSAGE_FLUSH = 2;
@ -59,7 +61,7 @@ public abstract class Worker {
protected Worker(Context context) {
mResources = context.getResources();
mResolver = context.getContentResolver();
// Negative means not initialized.
if (debuggable < 0) {
try {

View File

@ -1,12 +1,33 @@
package org.nativescript.widgets;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import androidx.exifinterface.media.ExifInterface;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Utils {
public static void drawBoxShadow(View view, String value) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
@ -50,6 +71,222 @@ public class Utils {
}
}
public interface AsyncImageCallback {
void onSuccess(Bitmap bitmap);
void onError(Exception exception);
}
static class ImageAssetOptions {
int width;
int height;
boolean keepAspectRatio;
boolean autoScaleFactor;
}
private static final Executor executors = Executors.newCachedThreadPool();
private static Pair<Integer, Integer> getAspectSafeDimensions(float sourceWidth, float sourceHeight, float reqWidth, float reqHeight) {
float widthCoef = sourceWidth / reqWidth;
float heightCoef = sourceHeight / reqHeight;
float aspectCoef = Math.min(widthCoef, heightCoef);
return new Pair<>((int) Math.floor(sourceWidth / aspectCoef), (int) Math.floor(sourceHeight / aspectCoef));
}
private static Pair<Integer, Integer> getRequestedImageSize(Pair<Integer, Integer> src, Pair<Integer, Integer> maxSize, ImageAssetOptions options) {
int reqWidth = options.width;
if (reqWidth <= 0) {
reqWidth = Math.min(src.first, maxSize.first);
}
int reqHeight = options.height;
if (reqHeight <= 0) {
reqHeight = Math.min(src.second, maxSize.second);
}
if (options.keepAspectRatio) {
Pair<Integer, Integer> safeAspectSize = getAspectSafeDimensions(src.first, src.second, reqWidth, reqHeight);
reqWidth = safeAspectSize.first;
reqHeight = safeAspectSize.second;
}
return new Pair<>(reqWidth, reqHeight);
}
private static void closePfd(ParcelFileDescriptor pfd) {
if (pfd != null) {
try {
pfd.close();
} catch (IOException ignored) {
}
}
}
private static int calculateAngleFromFile(String filename) {
int rotationAngle = 0;
ExifInterface ei;
try {
ei = new ExifInterface(filename);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotationAngle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotationAngle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotationAngle = 270;
break;
}
} catch (IOException ignored) {
}
return rotationAngle;
}
private static int calculateAngleFromFileDescriptor(FileDescriptor fd) {
int rotationAngle = 0;
ExifInterface ei;
try {
ei = new ExifInterface(fd);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotationAngle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotationAngle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotationAngle = 270;
break;
}
} catch (IOException ignored) {
}
return rotationAngle;
}
private static final Handler mainHandler = new Handler(Looper.getMainLooper());
public static void loadImageAsync(final Context context, final String src, final String options, final int maxWidth, final int maxHeight, final AsyncImageCallback callback) {
executors.execute(new Runnable() {
@Override
public void run() {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
try {
Bitmap bitmap;
ParcelFileDescriptor pfd = null;
if (src.startsWith("content://")) {
Uri uri = android.net.Uri.parse(src);
ContentResolver resolver = context.getContentResolver();
try {
pfd = resolver.openFileDescriptor(uri, "r");
} catch (final FileNotFoundException e) {
mainHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(e);
}
});
closePfd(pfd);
return;
}
android.graphics.BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, bitmapOptions);
} else {
android.graphics.BitmapFactory.decodeFile(src, bitmapOptions);
}
ImageAssetOptions opts = new ImageAssetOptions();
opts.keepAspectRatio = true;
opts.autoScaleFactor = true;
try {
JSONObject object = new JSONObject(options);
opts.width = object.optInt("width", 0);
opts.height = object.optInt("height", 0);
opts.keepAspectRatio = object.optBoolean("keepAspectRatio", true);
opts.autoScaleFactor = object.optBoolean("autoScaleFactor", true);
} catch (JSONException ignored) {
}
Pair<Integer, Integer> sourceSize = new Pair<>(bitmapOptions.outWidth, bitmapOptions.outHeight);
Pair<Integer, Integer> maxSize = new Pair<>(maxWidth, maxHeight);
Pair<Integer, Integer> requestedSize = getRequestedImageSize(sourceSize, maxSize, opts);
int sampleSize = org.nativescript.widgets.image.Fetcher.calculateInSampleSize(bitmapOptions.outWidth, bitmapOptions.outHeight, requestedSize.first, requestedSize.second);
BitmapFactory.Options finalBitmapOptions = new BitmapFactory.Options();
finalBitmapOptions.inSampleSize = sampleSize;
String error = null;
// read as minimum bitmap as possible (slightly bigger than the requested size)
if (pfd != null) {
bitmap = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, finalBitmapOptions);
} else {
bitmap = android.graphics.BitmapFactory.decodeFile(src, finalBitmapOptions);
}
if (bitmap != null) {
if (requestedSize.first != bitmap.getWidth() || requestedSize.second != bitmap.getHeight()) {
// scale to exact size
bitmap = android.graphics.Bitmap.createScaledBitmap(bitmap, requestedSize.first, requestedSize.second, true);
}
int rotationAngle;
if (pfd != null) {
rotationAngle = calculateAngleFromFileDescriptor(pfd.getFileDescriptor());
closePfd(pfd);
} else {
rotationAngle = calculateAngleFromFile(src);
}
if (rotationAngle != 0) {
Matrix matrix = new android.graphics.Matrix();
matrix.postRotate(rotationAngle);
bitmap = android.graphics.Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
}
if (bitmap == null) {
error = "Asset '" + src + "' cannot be found.";
}
final String finalError = error;
final Bitmap finalBitmap = bitmap;
mainHandler.post(new Runnable() {
@Override
public void run() {
if (finalError != null) {
callback.onError(new Exception(finalError));
} else {
callback.onSuccess(finalBitmap);
}
}
});
} catch (final Exception ex) {
mainHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(ex);
}
});
}
}
});
}
// public static void clearBoxShadow(View view) {
// if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
// return;

View File

@ -32,7 +32,7 @@
* SUPPORTED TOKENS: <lookup>
* DEFAULT VALUE: "<lookup>"
*/
"projectFolder": "nativescript-core",
"projectFolder": "../../packages/core",
/**
* (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis. API Extractor
@ -62,7 +62,7 @@
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/tsconfig.json"
*/
"tsconfigFilePath": "<projectFolder>/tsconfig.json",
"tsconfigFilePath": "<projectFolder>/tsconfig.json"
/**
* Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.
@ -122,7 +122,7 @@
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/etc/"
*/
"reportFolder": "api-reports/",
"reportFolder": "api-reports/"
/**
* Specifies the folder where the temporary report file is written. The file name portion is determined by
@ -147,7 +147,7 @@
/**
* (REQUIRED) Whether to generate a doc model file.
*/
"enabled": true,
"enabled": true
/**
* The output path for the doc model file. The file extension should be ".api.json".
@ -182,7 +182,7 @@
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/dist/<unscopedPackageName>.d.ts"
*/
"untrimmedFilePath": "<projectFolder>/nativescript-core.d.ts",
"untrimmedFilePath": "<projectFolder>/nativescript-core.d.ts"
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "beta" release.
@ -196,7 +196,6 @@
*/
// "betaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-beta.d.ts",
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "public" release.
* This file will include only declarations that are marked as "@public".
@ -231,7 +230,6 @@
* DEFAULT VALUE: true
*/
// "enabled": true,
/**
* Specifies where the TSDoc metadata file should be written.
*
@ -279,7 +277,7 @@
*
* DEFAULT VALUE: "warning"
*/
"logLevel": "error", //"warning",
"logLevel": "error" //"warning",
/**
* When addToApiReportFile is true: If API Extractor is configured to write an API report file (.api.md),
@ -289,7 +287,7 @@
* DEFAULT VALUE: false
*/
// "addToApiReportFile": false
},
}
// "TS2551": {
// "logLevel": "warning",
@ -308,13 +306,13 @@
*/
"extractorMessageReporting": {
"default": {
"logLevel": "warning",
"logLevel": "warning"
// "addToApiReportFile": false
},
"ae-missing-release-tag": {
"logLevel": "none",
"addToApiReportFile": false
},
}
// "ae-extra-release-tag": {
// "logLevel": "warning",
// "addToApiReportFile": true
@ -332,7 +330,7 @@
*/
"tsdocMessageReporting": {
"default": {
"logLevel": "warning",
"logLevel": "warning"
// "addToApiReportFile": false
},
"tsdoc-param-tag-missing-hyphen": {
@ -354,7 +352,7 @@
"tsdoc-malformed-html-name": {
"logLevel": "none",
"addToApiReportFile": false
},
}
// "tsdoc-link-tag-unescaped-text": {
// "logLevel": "warning",
@ -364,5 +362,4 @@
// . . .
}
}
}

View File

@ -3,7 +3,6 @@ set -e
ENV="${ENV:-dev}"
DIST_DIR="bin/dist"
TARGET_DIR="$DIST_DIR/snippets"
PACKAGE_VERSION="${PACKAGE_VERSION:-0.0.0}"
archive_dist_dir() {
@ -13,44 +12,27 @@ archive_dist_dir() {
npm_install() {
# Don't install modules twice.
MARKER_FILE="./node_modules/installed"
if [ ! -f "$MARKER_FILE" ] ; then
# Fixes perm issue while installing
npm i -g npm@^6.13.6
npm install
npm install @types/handlebars@4.0.33
touch "$MARKER_FILE"
fi
}
extract_snippets() {
BIN="./node_modules/markdown-snippet-injector/extract.js"
npm install markdown-snippet-injector
for SNIPPET_DIR in {tests/app,apps/app,nativescript-core} ; do
echo "Extracting snippets from: $SNIPPET_DIR"
node "$BIN" --root="$SNIPPET_DIR" --target="$TARGET_DIR" \
--sourceext=".js|.ts|.xml|.html|.css"
done
archive_dist_dir "snippets"
}
extract_apiref() {
APIREF_DIR="$DIST_DIR/api-reference"
rm -rf "$APIREF_DIR"
npm_install
npm run typedoc
# npm_install
npx typedoc --tsconfig tools/scripts/tsconfig.typedoc.json
mv "$DIST_DIR/apiref" "$APIREF_DIR"
mv "dist/apiref" "$APIREF_DIR"
archive_dist_dir "api-reference"
}
rm -rf "$TARGET_DIR"
mkdir -p "$TARGET_DIR"
if [ "${BASH_SOURCE[0]}" == "$0" ] ; then
extract_snippets
extract_apiref
fi

View File

@ -1,37 +1,33 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"noEmitOnError": true,
"noEmitHelpers": true,
"outDir": "../../dist/packages/core",
"target": "es5",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"noImplicitUseStrict": true,
"experimentalDecorators": true,
"lib": [
"es6",
"dom"
]
"lib": ["es6", "dom"]
},
"include": [
"nativescript-core/**/*.d.ts"
],
"include": ["../../packages/core/**/*.d.ts"],
"exclude": [
"nativescript-core/index.d.ts",
"nativescript-core/ui/index.d.ts",
"nativescript-core/ui/layouts/index.d.ts",
// "../../packages/core/index.d.ts",
"nativescript-core/references.d.ts",
"nativescript-core/node_modules",
"nativescript-core/ui/frame/transition-definitions.android.d.ts",
"nativescript-core/platforms/*"
"../../packages/core/ui/layouts/index.d.ts",
// "../../packages/core/__tests__",
"../../packages/core/references.d.ts",
"../../packages/core/node_modules",
"../../node_modules",
"../../packages/core/ui/frame/transition-definitions.android.d.ts",
"../../packages/core/platforms/*"
],
"typedocOptions": {
"out": "bin/dist/apiref",
"includeDeclarations": true,
"entryPoints": ["../../packages/core/index.d.ts", "../../packages/core"],
"out": "dist/apiref",
"name": "NativeScript",
"theme": "./node_modules/nativescript-typedoc-theme",
"theme": "../../node_modules/nativescript-typedoc-theme",
"excludeExternals": true,
"externalPattern": "**/+(tns-core-modules|module).d.ts"
"externalPattern": "**/+(tns-core-modules|module).d.ts",
"exclude": ["../../packages/core/__tests__", "../../packages/core/**/*.ts"]
}
}

View File

@ -132,6 +132,7 @@
"./node_modules/.bin/tsc -p packages/core/tsconfig.lib.json",
"./node_modules/.bin/copyfiles -e \"packages/core/__tests__/**/*\" \"packages/core/**/*.d.ts\" dist && ./node_modules/.bin/copyfiles -e \"packages/core/__tests__/**/*\" \"packages/core/js-libs/**/*\" dist && ./node_modules/.bin/copyfiles -e \"packages/core/__tests__/**/*\" \"packages/core/cli-hooks/**/*.js\" dist && ./node_modules/.bin/copyfiles -e \"packages/core/__tests__/**/*\" \"packages/core/platforms/**/*\" dist && ./node_modules/.bin/copyfiles -e \"packages/core/__tests__/**/*\" \"packages/core/fetch/**/*\" dist && ./node_modules/.bin/copyfiles -e \"packages/core/__tests__/**/*\" \"packages/core/css/**/*\" dist && ./node_modules/.bin/copyfiles -e \"packages/core/__tests__/**/*\" \"packages/core/css-value/**/*\" dist",
"cp packages/core/package.json dist/packages/core",
"cp packages/core/README.md dist/packages/core",
"cp LICENSE dist/packages/core",
"cd dist/packages/core && npm pack && mv *.tgz .."
],