@ui5/webcomponents-base
Advanced tools
Comparing version 0.7.0 to 0.8.0
{ | ||
"name": "@ui5/webcomponents-base", | ||
"version": "0.7.0", | ||
"version": "0.8.0", | ||
"description": "UI5 Web Components: webcomponents.base", | ||
@@ -17,11 +17,21 @@ "author": "SAP SE (https://www.sap.com)", | ||
"scripts": { | ||
"clean": "rimraf dist" | ||
"build": "npm run lint --scripts-prepend-node-path ", | ||
"clean": "rimraf dist", | ||
"lint": "eslint ." | ||
}, | ||
"dependencies": { | ||
"@polymer/polymer": "^3.1.0", | ||
"@ui5/webcomponents-core": "0.7.0" | ||
"@ui5/webcomponents-core": "^0.8.0", | ||
"lit-html": "^1.0.0", | ||
"regenerator-runtime": "0.12.1", | ||
"url-search-params-polyfill": "^5.0.0" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^5.13.0", | ||
"eslint-config-airbnb-base": "^13.1.0" | ||
}, | ||
"resolutions": { | ||
"abstract-syntax-tree": "1.0.3", | ||
"dir-glob": "2.0.0" | ||
} | ||
} |
@@ -1,2 +0,2 @@ | ||
![UI5 icon](https://github.com/SAP/ui5-webcomponents/blob/master/docs/images/UI5_logo_wide.png) | ||
![UI5 icon](https://raw.githubusercontent.com/SAP/ui5-webcomponents/master/docs/images/UI5_logo_wide.png) | ||
@@ -3,0 +3,0 @@ # UI5 Web Components - Base |
@@ -5,6 +5,6 @@ import AnimationQueue from "./AnimationQueue"; | ||
export default ({ | ||
beforeStart = animationConfig.identity, | ||
duration = animationConfig.defaultDuration, | ||
element = animationConfig.element, | ||
progress: progressCallback = animationConfig.identity | ||
beforeStart = animationConfig.identity, | ||
duration = animationConfig.defaultDuration, | ||
element = animationConfig.element, | ||
progress: progressCallback = animationConfig.identity, | ||
}) => { | ||
@@ -41,3 +41,3 @@ let start = null; | ||
AnimationQueue.push(element, _ => { | ||
AnimationQueue.push(element, () => { | ||
beforeStart(); | ||
@@ -47,3 +47,3 @@ requestAnimationFrame(animate); | ||
return new Promise(resolve => { | ||
promise.then(_ => resolve()); | ||
promise.then(() => resolve()); | ||
}); | ||
@@ -53,5 +53,5 @@ }); | ||
return { | ||
promise: _=> promise, | ||
stop: _ => stop | ||
promise: () => promise, | ||
stop: () => stop, | ||
}; | ||
}; | ||
}; |
@@ -8,3 +8,3 @@ const tasks = new WeakMap(); | ||
static enqueue (element, task) { | ||
static enqueue(element, task) { | ||
if (!tasks.has(element)) { | ||
@@ -17,3 +17,3 @@ tasks.set(element, []); | ||
static run (element, task) { | ||
static run(element, task) { | ||
if (!tasks.has(element)) { | ||
@@ -23,3 +23,3 @@ tasks.set(element, []); | ||
return task().then(_ => { | ||
return task().then(() => { | ||
const elementTasks = tasks.get(element); | ||
@@ -29,9 +29,8 @@ | ||
return AnimationQueue.run(element, elementTasks.shift()); | ||
} else { | ||
tasks.delete(element); | ||
} | ||
tasks.delete(element); | ||
}); | ||
} | ||
static push (element, task) { | ||
static push(element, task) { | ||
const elementTasks = tasks.get(element); | ||
@@ -38,0 +37,0 @@ |
export default { | ||
defaultDuration: 400, | ||
element: document.createElement("DIV"), | ||
identity: () => {} | ||
}; | ||
identity: () => {}, | ||
}; |
@@ -1,3 +0,3 @@ | ||
import animate from './animate'; | ||
import animationConfig from './config'; | ||
import animate from "./animate"; | ||
import animationConfig from "./config"; | ||
@@ -9,3 +9,3 @@ export default ({ | ||
dx = 0, | ||
dy = 0 | ||
dy = 0, | ||
}) => { | ||
@@ -16,8 +16,8 @@ let scrollLeft; | ||
return animate({ | ||
beforeStart: _ => { | ||
beforeStart: () => { | ||
scrollLeft = element.scrollLeft; | ||
scrollTop = element.scrollTop; | ||
}, | ||
duration: duration, | ||
element: element, | ||
duration, | ||
element, | ||
progress: progress => { | ||
@@ -28,4 +28,4 @@ progressCallback(progress); | ||
element.scrollTop = scrollTop + (progress * dy); // easing - linear | ||
} | ||
}, | ||
}); | ||
}; | ||
}; |
@@ -7,9 +7,19 @@ import animationConfig from "./config"; | ||
duration = animationConfig.defaultDuration, | ||
progress: progressCallback = animationConfig.identity | ||
progress: progressCallback = animationConfig.identity, | ||
}) => { | ||
let computedStyles, paddingTop, paddingBottom, marginTop, marginBottom, height; | ||
let storedOverflow, storedPaddingTop, storedPaddingBottom, storedMarginTop, storedMarginBottom, storedHeight; | ||
let computedStyles, | ||
paddingTop, | ||
paddingBottom, | ||
marginTop, | ||
marginBottom, | ||
height; | ||
let storedOverflow, | ||
storedPaddingTop, | ||
storedPaddingBottom, | ||
storedMarginTop, | ||
storedMarginBottom, | ||
storedHeight; | ||
const animation = animate({ | ||
beforeStart: _ => { | ||
beforeStart: () => { | ||
// Show the element to measure its properties | ||
@@ -41,5 +51,5 @@ element.style.display = "block"; | ||
}, | ||
duration: duration, | ||
element: element, | ||
progress: function (progress) { | ||
duration, | ||
element, | ||
progress(progress) { | ||
progressCallback(progress); | ||
@@ -51,2 +61,3 @@ | ||
/* eslint-disable */ | ||
element.style.paddingTop = 0 + (paddingTop * progress) + "px"; | ||
@@ -57,6 +68,7 @@ element.style.paddingBottom = 0 + (paddingBottom * progress) + "px"; | ||
element.style.height = 0 + (height * progress) + "px"; | ||
} | ||
/* eslint-enable */ | ||
}, | ||
}); | ||
animation.promise().then(_ => { | ||
animation.promise().then(() => { | ||
element.style.overflow = storedOverflow; | ||
@@ -71,2 +83,2 @@ element.style.paddingTop = storedPaddingTop; | ||
return animation; | ||
}; | ||
}; |
@@ -7,12 +7,22 @@ import animationConfig from "./config"; | ||
duration = animationConfig.defaultDuration, | ||
progress: progressCallback = animationConfig.identity | ||
progress: progressCallback = animationConfig.identity, | ||
}) => { | ||
// Get Computed styles | ||
let computedStyles, paddingTop, paddingBottom, marginTop, marginBottom, height; | ||
let computedStyles, | ||
paddingTop, | ||
paddingBottom, | ||
marginTop, | ||
marginBottom, | ||
height; | ||
// Store inline styles | ||
let storedOverflow, storedPaddingTop, storedPaddingBottom, storedMarginTop, storedMarginBottom, storedHeight; | ||
let storedOverflow, | ||
storedPaddingTop, | ||
storedPaddingBottom, | ||
storedMarginTop, | ||
storedMarginBottom, | ||
storedHeight; | ||
const animation = animate({ | ||
beforeStart: _ => { | ||
beforeStart: () => { | ||
// Get Computed styles | ||
@@ -36,13 +46,13 @@ computedStyles = getComputedStyle(element); | ||
}, | ||
duration: duration, | ||
element: element, | ||
progress: function (progress) { | ||
duration, | ||
element, | ||
progress(progress) { | ||
progressCallback(progress); | ||
element.style.paddingTop = paddingTop - (paddingTop * progress) + "px"; | ||
element.style.paddingBottom = paddingBottom - (paddingBottom * progress) + "px"; | ||
element.style.marginTop = marginTop - (marginTop * progress) + "px"; | ||
element.style.marginBottom = marginBottom - (marginBottom * progress) + "px"; | ||
element.style.height = height - (height * progress) + "px"; | ||
} | ||
element.style.paddingTop = `${paddingTop - (paddingTop * progress)}px`; | ||
element.style.paddingBottom = `${paddingBottom - (paddingBottom * progress)}px`; | ||
element.style.marginTop = `${marginTop - (marginTop * progress)}px`; | ||
element.style.marginBottom = `${marginBottom - (marginBottom * progress)}px`; | ||
element.style.height = `${height - (height * progress)}px`; | ||
}, | ||
}); | ||
@@ -63,2 +73,2 @@ | ||
return animation; | ||
}; | ||
}; |
@@ -0,1 +1,2 @@ | ||
/* eslint-disable camelcase */ | ||
import ar from "@ui5/webcomponents-core/dist/sap/ui/core/cldr/ar.json"; | ||
@@ -152,16 +153,19 @@ import ar_EG from "@ui5/webcomponents-core/dist/sap/ui/core/cldr/ar_EG.json"; | ||
zh_TW, | ||
} | ||
}; | ||
const allEntriesInlined = Object.entries(cldrData).every(([_key, value]) => typeof (value) === "object"); | ||
/* eslint-disable */ | ||
if (allEntriesInlined) { | ||
console.warn(`Inefficient bundling detected: consider bundling CLDR imports as URLs instead of inlining them. | ||
console.warn(`Inefficient bundling detected: consider bundling CLDR imports as URLs instead of inlining them. | ||
See rollup-plugin-url or webpack file-loader for more information. | ||
Suggested pattern: "cldr\\\/.*\\\.json"`); | ||
} | ||
/* eslint-enable */ | ||
const M_ISO639_OLD_TO_NEW = { | ||
"iw" : "he", | ||
"ji" : "yi", | ||
"in" : "id", | ||
"sh" : "sr" | ||
"iw": "he", | ||
"ji": "yi", | ||
"in": "id", | ||
"sh": "sr", | ||
}; | ||
@@ -173,10 +177,10 @@ | ||
// Special case 1: in an SAP context, the inclusive language code "no" always means Norwegian Bokmal ("nb") | ||
if ( language === "no" ) { | ||
if (language === "no") { | ||
language = "nb"; | ||
} | ||
// Special case 2: for Chinese, derive a default region from the script (this behavior is inherited from Java) | ||
if ( language === "zh" && !region ) { | ||
if ( script === "Hans" ) { | ||
if (language === "zh" && !region) { | ||
if (script === "Hans") { | ||
region = "CN"; | ||
} else if ( script === "Hant" ) { | ||
} else if (script === "Hant") { | ||
region = "TW"; | ||
@@ -187,3 +191,3 @@ } | ||
// try language + region | ||
let localeId = language + "_" + region; | ||
let localeId = `${language}_${region}`; | ||
if (!cldrData[localeId]) { | ||
@@ -199,10 +203,10 @@ // fallback to language only | ||
return localeId; | ||
} | ||
}; | ||
const fetchCldrData = async (language, region, script) => { | ||
const fetchCldrData = async (language, region, script) => { | ||
const localeId = calcLocale(language, region, script); | ||
if (typeof(cldrData[localeId]) === "object") { | ||
if (typeof (cldrData[localeId]) === "object") { | ||
// inlined from build | ||
registerModuleContent(`sap/ui/core/cldr/${localeId}.json`, JSON.stringify(cldrData[localeId])) | ||
registerModuleContent(`sap/ui/core/cldr/${localeId}.json`, JSON.stringify(cldrData[localeId])); | ||
return cldrData[localeId]; | ||
@@ -221,2 +225,3 @@ } | ||
export { fetchCldrData, registerCldrUrl }; | ||
export { fetchCldrData, registerCldrUrl }; | ||
/* eslint-enable camelcase */ |
@@ -1,3 +0,1 @@ | ||
import WCPolyfill from '../thirdparty/webcomponents-polyfill'; | ||
const patchNodeValue = () => { | ||
@@ -13,3 +11,3 @@ if (!window.ShadyDOM) { | ||
set(text) { | ||
nativeNodeValue.set.apply(this, arguments); | ||
nativeNodeValue.set.apply(this, arguments); // eslint-disable-line | ||
@@ -21,6 +19,8 @@ // Call manually the mutation observer callback | ||
} | ||
} | ||
}, | ||
}); | ||
}; | ||
export default patchNodeValue; | ||
patchNodeValue(); | ||
export default {}; |
@@ -1,18 +0,14 @@ | ||
import WCPolyfill from '../thirdparty/webcomponents-polyfill'; | ||
import configuration from "../Configuration"; | ||
import { fetchThemeBundle } from "../ThemeBundle"; | ||
import { getTheme, getRTL, getCompactSize } from "../Configuration"; | ||
// Shorthands | ||
const d = document; | ||
import StyleInjection from "../theming/StyleInjection"; | ||
import { registerStyle } from "../theming/ThemeBundle"; | ||
import setupBrowser from "../util/setupBrowser"; | ||
import setupOS from "../util/setupOS"; | ||
import setupSystem from "../util/setupSystem"; | ||
import { getEffectiveStyle } from "../Theming"; | ||
// shadow DOM templates per tag | ||
const shadowDOMTemplates = new Map(); | ||
const styles = new Map(); | ||
const customCSSMap = new Map(); | ||
const styleTagsInHead = []; | ||
const customStyleTagsInHead = []; | ||
/** | ||
@@ -26,167 +22,59 @@ * Prepares the shadow DOM for a custom element, depending on the usage of the polyfill | ||
static setWebComponentRootOnHTML() { | ||
if (window.ShadyDOM) { | ||
document.documentElement.setAttribute("data-sap-ui-wc-root", ""); | ||
} | ||
static registerStyle(theme, styleName, styleContent) { | ||
registerStyle(theme, styleName, styleContent); | ||
} | ||
static registerStyle(theme, styleName, styleObj) { | ||
if (typeof(styleObj) === "object" && styleObj._) { | ||
if (!styles.has(theme)) { | ||
styles.set(theme, {}); | ||
} | ||
styles.get(theme)[styleName] = styleObj._; | ||
} | ||
} | ||
static async updateStyle(tag, shadowRoot, styleUrls) { | ||
const theme = getTheme(); | ||
const newStyle = await getEffectiveStyle(theme, styleUrls, tag); | ||
static async updateStyle(tag, shadowRoot, stylesUrls) { | ||
const theme = configuration.getTheme(); | ||
const cssResults = await this._fetchStyleUrls(theme, stylesUrls); | ||
const customCSS = ShadowDOM._getCustomCSS(theme, tag); | ||
const newStyle = cssResults.join(" ").concat(customCSS); | ||
shadowRoot.querySelector("style").textContent = newStyle; | ||
} | ||
static prepareShadowDOM(ElementClass) { | ||
const theme = configuration.getTheme(); | ||
const stylesUrls = ElementClass.getMetadata().getStyleUrl(); | ||
static async prepareShadowDOM(ElementClass) { | ||
const theme = getTheme(); | ||
const styleUrls = ElementClass.getMetadata().getStyleUrl(); | ||
const tag = ElementClass.getMetadata().getTag(); | ||
const cssFetchedPromise = ShadowDOM._fetchStyleUrls(theme, stylesUrls); | ||
const isRTL = configuration.getRTL(); | ||
const isCompact = configuration.getCompactSize(); | ||
const isRTL = getRTL(); | ||
const isCompact = getCompactSize(); | ||
let shadowDOM, | ||
rootSpan; | ||
return cssFetchedPromise.then(cssResults => { | ||
let shadowDOM, rootSpan; | ||
if (window.ShadyDOM) { | ||
// Create styles in the <head> for each css file | ||
cssResults.forEach((css, i) => { | ||
ShadowDOM._createStyleTag(styleTagsInHead, stylesUrls[i], css); | ||
}); | ||
if (window.ShadyDOM) { | ||
// inject the styles in the <head> | ||
const cssContent = await getEffectiveStyle(theme, styleUrls, tag); | ||
StyleInjection.createStyleTag(tag, styleUrls, cssContent); | ||
// Create styles in the <head> for added custom CSS | ||
if (ShadowDOM._hasCustomCSSForTheme(theme)) { | ||
const customStyleTagInfo = this._getCustomStyleTagInfo(theme); | ||
// Create the shadow DOM root span | ||
rootSpan = document.createElement("span"); | ||
rootSpan.setAttribute("data-sap-ui-wc-root", ""); | ||
shadowDOM = rootSpan; | ||
} else { | ||
let template = this._getTemplateFor(theme, tag); | ||
customStyleTagInfo.forEach((styleTagInfo) => { | ||
ShadowDOM._createStyleTag(customStyleTagsInHead, styleTagInfo.id, styleTagInfo.css); | ||
}); | ||
} | ||
// Create the shadow DOM root span | ||
rootSpan = d.createElement("span"); | ||
rootSpan.setAttribute("data-sap-ui-wc-placeholder", ""); | ||
shadowDOM = rootSpan; | ||
} else { | ||
let template = this._getTemplateFor(theme, tag); | ||
if (!template) { | ||
const tagCustomCSS = this._getCustomCSS(theme, tag); | ||
const cssText = cssResults.join(" ").concat(tagCustomCSS); | ||
template = this._createTemplateFor(theme, tag, cssText); | ||
} | ||
shadowDOM = template.content.cloneNode(true); | ||
rootSpan = shadowDOM.querySelector("span[data-sap-ui-wc-placeholder]"); | ||
rootSpan.setAttribute("data-sap-ui-browser", document.documentElement.getAttribute("data-sap-ui-browser")); | ||
rootSpan.setAttribute("data-sap-ui-os", document.documentElement.getAttribute("data-sap-ui-os")); | ||
if (!template) { | ||
const cssText = await getEffectiveStyle(theme, styleUrls, tag); | ||
template = this._createTemplateFor(theme, tag, cssText); | ||
} | ||
shadowDOM = template.content.cloneNode(true); | ||
if (isCompact) { | ||
rootSpan.classList.add("sapUiSizeCompact"); | ||
} | ||
if (isRTL) { | ||
rootSpan.setAttribute("dir", "rtl"); | ||
} | ||
return shadowDOM; | ||
}); | ||
} | ||
static _addCustomCSS(tag, theme, css) { | ||
let themeCustomCSS = customCSSMap.get(theme); | ||
if (!themeCustomCSS) { | ||
customCSSMap.set(theme, {}); | ||
themeCustomCSS = customCSSMap.get(theme); | ||
rootSpan = shadowDOM.querySelector("span[data-sap-ui-wc-root]"); | ||
} | ||
if (!themeCustomCSS[tag]) { | ||
themeCustomCSS[tag] = []; | ||
} | ||
setupBrowser(rootSpan); | ||
setupOS(rootSpan); | ||
setupSystem(rootSpan); | ||
themeCustomCSS[tag].push(css); | ||
} | ||
static _getCustomCSS(theme, tag) { | ||
const themeCustomCSS = customCSSMap.get(theme); | ||
return themeCustomCSS && themeCustomCSS[tag] ? themeCustomCSS[tag].join("") : ""; | ||
} | ||
static async _applyTheme() { | ||
if (!window.ShadyDOM) { | ||
return; | ||
if (isCompact) { | ||
rootSpan.classList.add("sapUiSizeCompact"); | ||
} | ||
const theme = configuration.getTheme(); | ||
const cssResults = await ShadowDOM._fetchStyleUrls(theme, styleTagsInHead); | ||
// Update style tags | ||
cssResults.forEach((css, i) => { | ||
const style = document.head.querySelector('style[data-sap-source="' + styleTagsInHead[i] + '"]'); | ||
style.innerHTML = css; | ||
}); | ||
// Update custom style tags | ||
if (ShadowDOM._hasCustomCSSForTheme(theme)) { | ||
ShadowDOM._applyCustomStyleTags(theme); // Update custom style tags (if exist) or create new ones | ||
} else { | ||
ShadowDOM._cleanCustomStyleTags(); // Clean previously added custom style tags | ||
if (isRTL) { | ||
rootSpan.setAttribute("dir", "rtl"); | ||
} | ||
} | ||
static _applyCustomStyleTags(theme) { | ||
const customStyleTagInfo = this._getCustomStyleTagInfo(theme); | ||
customStyleTagInfo.forEach(styleTagInfo => { | ||
const style = this._getStyleTag(styleTagInfo.id); | ||
if (style) { | ||
style.innerHTML = styleTagInfo.css; | ||
} else { | ||
this._createStyleTag(customStyleTagsInHead, styleTagInfo.id, styleTagInfo.css); | ||
} | ||
}); | ||
return shadowDOM; | ||
} | ||
static _cleanCustomStyleTags () { | ||
customStyleTagsInHead.forEach(styleTagId => { | ||
const style = this._getStyleTag(styleTagId); | ||
if (style) { | ||
style.innerHTML = ""; | ||
} | ||
}) | ||
} | ||
static _getCustomStyleTagInfo(theme) { | ||
return Object.keys(customCSSMap.get(theme)).map(tag => { | ||
const customCSSInfo = {}; | ||
customCSSInfo.id = tag + "--custom--css"; | ||
customCSSInfo.css = ShadowDOM._getCustomCSS(theme, tag); | ||
return customCSSInfo; | ||
}); | ||
} | ||
static _hasCustomCSSForTheme(theme) { | ||
return !!customCSSMap.get(theme); | ||
} | ||
static _getStyleTag(tagId) { | ||
return document.head.querySelector('style[data-sap-source="' + tagId + '"]'); | ||
} | ||
static _getTemplateFor(theme, tag) { | ||
@@ -203,6 +91,6 @@ const themeMap = shadowDOMTemplates.get(theme); | ||
} | ||
const template = d.createElement("template"); | ||
const template = document.createElement("template"); | ||
// Create a local <style> tag for the real shadow DOM | ||
let style = d.createElement("style"); | ||
const style = document.createElement("style"); | ||
style.innerHTML = css; | ||
@@ -212,4 +100,3 @@ template.content.appendChild(style); | ||
// Create a root span | ||
let root = d.createElement("span"); | ||
root.setAttribute("data-sap-ui-wc-placeholder", ""); | ||
const root = document.createElement("span"); | ||
root.setAttribute("data-sap-ui-wc-root", ""); | ||
@@ -222,50 +109,4 @@ | ||
} | ||
static _fetchStyleUrls(theme, urls) { | ||
const requests = urls.map(styleName => { | ||
return ShadowDOM._fetchStyleUrl(theme, styleName); | ||
}); | ||
return Promise.all(requests); | ||
} | ||
static async _fetchStyleUrl(theme, styleName) { | ||
if (!styles.has(theme)) { | ||
styles.set(theme, {}); | ||
} | ||
const themeMap = styles.get(theme); | ||
if (themeMap[styleName]) { | ||
return themeMap[styleName]; | ||
} | ||
// requested style not present | ||
const themeData = await ShadowDOM.fetchTheme(theme); | ||
Object.keys(themeData).forEach(key => { | ||
themeMap[key] = themeData[key]; | ||
}); | ||
return themeMap[styleName]; | ||
} | ||
static async fetchTheme(theme) { | ||
return fetchThemeBundle("@ui5/webcomponents", theme); | ||
} | ||
static _createStyleTag(styleTags, url, cssText) { | ||
if (styleTags.indexOf(url) !== -1) { | ||
return; | ||
} | ||
const style = d.createElement("style"); | ||
style.type = "text/css"; | ||
style.setAttribute("data-sap-source", url); | ||
style.innerHTML = cssText; | ||
d.head.appendChild(style); | ||
styleTags.push(url); | ||
} | ||
} | ||
export default ShadowDOM; | ||
export default ShadowDOM; |
@@ -1,30 +0,224 @@ | ||
import Configuration from "@ui5/webcomponents-core/dist/sap/ui/core/Configuration"; | ||
import Device from "@ui5/webcomponents-core/dist/sap/ui/Device"; | ||
import Locale from "@ui5/webcomponents-core/dist/sap/ui/core/Locale"; | ||
import CalendarType from "@ui5/webcomponents-core/dist/sap/ui/core/CalendarType"; | ||
import * as FormatSettings from "./FormatSettings"; | ||
function readConfiguration() { | ||
function normalize(o) { | ||
for (var i in o) { | ||
var v = o[i]; | ||
var il = i.toLowerCase(); | ||
if ( !o.hasOwnProperty(il) ) { | ||
o[il] = v; | ||
delete o[i]; | ||
let LocaleData; | ||
const getDesigntimePropertyAsArray = sValue => { | ||
const m = /\$([-a-z0-9A-Z._]+)(?::([^$]*))?\$/.exec(sValue); | ||
return (m && m[2]) ? m[2].split(/,/) : null; | ||
}; | ||
const supportedLanguages = getDesigntimePropertyAsArray("$core-i18n-locales:,ar,bg,ca,cs,da,de,el,en,es,et,fi,fr,hi,hr,hu,it,iw,ja,ko,lt,lv,nl,no,pl,pt,ro,ru,sh,sk,sl,sv,th,tr,uk,vi,zh_CN,zh_TW$"); | ||
const detectLanguage = () => { | ||
const browserLanguages = navigator.languages; | ||
const navigatorLanguage = () => { | ||
if (Device.os.android) { | ||
// on Android, navigator.language is hardcoded to 'en', so check UserAgent string instead | ||
const match = navigator.userAgent.match(/\s([a-z]{2}-[a-z]{2})[;)]/i); | ||
if (match) { | ||
return match[1]; | ||
} | ||
// okay, we couldn't find a language setting. It might be better to fallback to 'en' instead of having no language | ||
} | ||
return o; | ||
return navigator.language; | ||
}; | ||
const rawLocale = (browserLanguages && browserLanguages[0]) || navigatorLanguage() || navigator.userLanguage || navigator.browserLanguage; | ||
return rawLocale || "en"; | ||
}; | ||
const language = detectLanguage(); | ||
const CONFIGURATION = { | ||
theme: "sap_fiori_3", | ||
rtl: null, | ||
language: new Locale(language), | ||
compactSize: false, | ||
supportedLanguages, | ||
calendarType: null, | ||
derivedRTL: null, | ||
"xx-wc-force-default-gestures": false, | ||
"xx-wc-no-conflict": false, // no URL | ||
}; | ||
FormatSettings.setConfiguration(CONFIGURATION); | ||
/* General settings */ | ||
const getTheme = () => { | ||
return CONFIGURATION.theme; | ||
}; | ||
const getRTL = () => { | ||
return CONFIGURATION.rtl === null ? CONFIGURATION.derivedRTL : CONFIGURATION.rtl; | ||
}; | ||
const getLanguage = () => { | ||
return CONFIGURATION.language.sLocaleId; | ||
}; | ||
const getCompactSize = () => { | ||
return CONFIGURATION.compactSize; | ||
}; | ||
const getSupportedLanguages = () => { | ||
return CONFIGURATION.supportedLanguages; | ||
}; | ||
/* WC specifics */ | ||
const getWCForceDefaultGestures = () => { | ||
return CONFIGURATION["xx-wc-force-default-gestures"]; | ||
}; | ||
const getWCNoConflict = () => { | ||
return CONFIGURATION["xx-wc-no-conflict"]; | ||
}; | ||
/* Calendar stuff */ | ||
const getCalendarType = () => { | ||
if (CONFIGURATION.calendarType) { | ||
const type = Object.keys(CalendarType).filter(calType => calType === CONFIGURATION.calendarType)[0]; | ||
if (type) { | ||
return type; | ||
} | ||
} | ||
var jsonConfig = document.querySelector("[data-id='sap-ui-config']"); | ||
if (jsonConfig && jsonConfig.type === "application/json") { | ||
return normalize(JSON.parse(jsonConfig.innerHTML)); | ||
/* In order to have a locale based calendar type - LocaleData should be injected to the configuration | ||
- check #injectLocaleData | ||
*/ | ||
if (LocaleData) { | ||
return LocaleData.getInstance(getLocale()).getPreferredCalendarType(); | ||
} | ||
return {}; | ||
} | ||
window['sap-ui-config'] = readConfiguration(); | ||
const configuration = new Configuration(); | ||
return CalendarType.Gregorian; | ||
}; | ||
if (configuration.getTheme() === "base") { | ||
configuration._setTheme("sap_fiori_3"); | ||
} | ||
const getOriginInfo = () => {}; | ||
export default configuration; | ||
const getLocale = () => { | ||
return CONFIGURATION.language; | ||
}; | ||
const getFormatSettings = () => { | ||
return FormatSettings; | ||
}; | ||
const _setTheme = themeName => { | ||
CONFIGURATION.theme = themeName; | ||
}; | ||
const booleanMapping = new Map([ | ||
["true", true], | ||
["false", false], | ||
]); | ||
let runtimeConfig = {}; | ||
const convertToLocaleOrNull = lang => { | ||
try { | ||
if (lang && typeof lang === "string") { | ||
return new Locale(lang); | ||
} | ||
} catch (e) { | ||
// ignore | ||
} | ||
}; | ||
const check = (condition, sMessage) => { | ||
if (!condition) { | ||
throw new Error(sMessage); | ||
} | ||
}; | ||
const getLanguageTag = () => { | ||
return CONFIGURATION.language.toString(); | ||
}; | ||
const setLanguage = newLanguage => { | ||
const locale = convertToLocaleOrNull(newLanguage); | ||
check(locale, "Configuration.setLanguage: newLanguage must be a valid BCP47 language tag"); | ||
if (locale.toString() !== getLanguageTag()) { | ||
CONFIGURATION.language = locale; | ||
CONFIGURATION.derivedRTL = Locale._impliesRTL(locale); | ||
} | ||
return CONFIGURATION; | ||
}; | ||
const parseConfigurationScript = () => { | ||
const configScript = document.querySelector("[data-id='sap-ui-config']"); | ||
let configJSON; | ||
if (configScript) { | ||
try { | ||
configJSON = JSON.parse(configScript.innerHTML); | ||
} catch (е) { | ||
console.warn("Incorrect data-sap-ui-config format. Please use JSON"); /* eslint-disable-line */ | ||
} | ||
if (configJSON) { | ||
runtimeConfig = Object.assign({}, configJSON); | ||
} | ||
} | ||
}; | ||
const parseURLParameters = () => { | ||
const params = new URLSearchParams(window.location.search); | ||
params.forEach((value, key) => { | ||
if (!key.startsWith("sap-ui")) { | ||
return; | ||
} | ||
const lowerCaseValue = value.toLowerCase(); | ||
const param = key.split("sap-ui-")[1]; | ||
if (booleanMapping.has(value)) { | ||
value = booleanMapping.get(lowerCaseValue); | ||
} | ||
runtimeConfig[param] = value; | ||
}); | ||
}; | ||
const applyConfigurations = () => { | ||
Object.keys(runtimeConfig).forEach(key => { | ||
if (key === "language") { | ||
setLanguage(runtimeConfig[key]); | ||
} else { | ||
CONFIGURATION[key] = runtimeConfig[key]; | ||
} | ||
}); | ||
}; | ||
const injectLocaleData = localeData => { | ||
LocaleData = localeData; | ||
}; | ||
parseConfigurationScript(); | ||
parseURLParameters(); | ||
applyConfigurations(); | ||
export { | ||
getTheme, | ||
getRTL, | ||
getLanguage, | ||
getCompactSize, | ||
getWCForceDefaultGestures, | ||
getWCNoConflict, | ||
getCalendarType, | ||
getLocale, | ||
getFormatSettings, | ||
_setTheme, | ||
getSupportedLanguages, | ||
getOriginInfo, | ||
injectLocaleData, | ||
}; |
@@ -8,3 +8,2 @@ import LitRenderer from "./renderer/LitRenderer"; | ||
class ControlRenderer { | ||
static render(control) { | ||
@@ -14,3 +13,3 @@ // const oldCounter = window.renderStats.get(control.tagName) || 0; | ||
const placeholder = control._getPlaceholder(); | ||
const root = control._getRoot(); | ||
const templateContext = control._getTemplateContext(); | ||
@@ -20,32 +19,6 @@ const renderer = Object.getPrototypeOf(control).constructor.renderer.render; | ||
RendererImpl.render(renderResult, placeholder); | ||
RendererImpl.render(renderResult, root); | ||
} | ||
static storeFocus() { | ||
// let activeElement = document.activeElement; | ||
// try { | ||
// while (activeElement && activeElement.shadowRoot) { | ||
// // drill down the DOM to find the actual focused DOM element | ||
// activeElement = activeElement.shadowRoot.activeElement; | ||
// } | ||
// if (!activeElement.matches(":focus")) { | ||
// ControlRenderer._focusedControl = undefined; | ||
// return; | ||
// } | ||
// } | ||
// catch (e) { | ||
// activeElement = undefined; | ||
// } | ||
// ControlRenderer._focusedControl = activeElement; | ||
} | ||
static restoreFocus() { | ||
// if (ControlRenderer._focusedControl) { | ||
// ControlRenderer._focusedControl.focus(); | ||
// } | ||
} | ||
} | ||
export default ControlRenderer; |
@@ -5,45 +5,47 @@ import UniversalDate from "@ui5/webcomponents-core/dist/sap/ui/core/date/UniversalDate"; | ||
constructor() { | ||
var aArgs = arguments, | ||
oJSDate, oNow, sCalendarType; | ||
let aArgs = arguments, // eslint-disable-line | ||
oJSDate, | ||
oNow, | ||
sCalendarType; | ||
switch (aArgs.length) { | ||
case 0: // defaults to the current date | ||
oNow = new Date(); | ||
return this.constructor(oNow.getFullYear(), oNow.getMonth(), oNow.getDate()); | ||
case 0: // defaults to the current date | ||
oNow = new Date(); | ||
return this.constructor(oNow.getFullYear(), oNow.getMonth(), oNow.getDate()); | ||
case 1: // CalendarDate | ||
case 2: // CalendarDate, sCalendarType | ||
if (!(aArgs[0] instanceof CalendarDate)) { | ||
throw "Invalid arguments: the first argument must be of type sap.ui.unified.calendar.CalendarDate."; | ||
} | ||
sCalendarType = aArgs[1] ? aArgs[1] : aArgs[0]._oUDate.sCalendarType; | ||
//Use source.valueOf() (returns the same point of time regardless calendar type) instead of | ||
//source's getters to avoid non-gregorian Year, Month and Date may be used to construct a Gregorian date | ||
oJSDate = new Date(aArgs[0].valueOf()); | ||
case 1: // CalendarDate | ||
case 2: // CalendarDate, sCalendarType | ||
if (!(aArgs[0] instanceof CalendarDate)) { | ||
throw new Error("Invalid arguments: the first argument must be of type sap.ui.unified.calendar.CalendarDate."); | ||
} | ||
sCalendarType = aArgs[1] ? aArgs[1] : aArgs[0]._oUDate.sCalendarType; | ||
// Use source.valueOf() (returns the same point of time regardless calendar type) instead of | ||
// source's getters to avoid non-gregorian Year, Month and Date may be used to construct a Gregorian date | ||
oJSDate = new Date(aArgs[0].valueOf()); | ||
//Make this date really local. Now getters are safe. | ||
oJSDate.setFullYear(oJSDate.getUTCFullYear(), oJSDate.getUTCMonth(), oJSDate.getUTCDate()); | ||
oJSDate.setHours(oJSDate.getUTCHours(), oJSDate.getUTCMinutes(), oJSDate.getUTCSeconds(), oJSDate.getUTCMilliseconds()); | ||
// Make this date really local. Now getters are safe. | ||
oJSDate.setFullYear(oJSDate.getUTCFullYear(), oJSDate.getUTCMonth(), oJSDate.getUTCDate()); | ||
oJSDate.setHours(oJSDate.getUTCHours(), oJSDate.getUTCMinutes(), oJSDate.getUTCSeconds(), oJSDate.getUTCMilliseconds()); | ||
this._oUDate = createUniversalUTCDate(oJSDate, sCalendarType); | ||
break; | ||
this._oUDate = createUniversalUTCDate(oJSDate, sCalendarType); | ||
break; | ||
case 3: // year, month, date | ||
case 4: // year, month, date, sCalendarType | ||
checkNumericLike(aArgs[0], "Invalid year: " + aArgs[0]); | ||
checkNumericLike(aArgs[1], "Invalid month: " + aArgs[1]); | ||
checkNumericLike(aArgs[2], "Invalid date: " + aArgs[2]); | ||
case 3: // year, month, date | ||
case 4: // year, month, date, sCalendarType | ||
checkNumericLike(aArgs[0], `Invalid year: ${aArgs[0]}`); | ||
checkNumericLike(aArgs[1], `Invalid month: ${aArgs[1]}`); | ||
checkNumericLike(aArgs[2], `Invalid date: ${aArgs[2]}`); | ||
oJSDate = new Date(0, 0, 1); | ||
oJSDate.setFullYear(aArgs[0], aArgs[1], aArgs[2]); // 2 digits year is not supported. If so, it is considered as full year as well. | ||
oJSDate = new Date(0, 0, 1); | ||
oJSDate.setFullYear(aArgs[0], aArgs[1], aArgs[2]); // 2 digits year is not supported. If so, it is considered as full year as well. | ||
if (aArgs[3]) { | ||
sCalendarType = aArgs[3]; | ||
} | ||
this._oUDate = createUniversalUTCDate(oJSDate, sCalendarType); | ||
break; | ||
if (aArgs[3]) { | ||
sCalendarType = aArgs[3]; | ||
} | ||
this._oUDate = createUniversalUTCDate(oJSDate, sCalendarType); | ||
break; | ||
default: | ||
throw "Invalid arguments. Accepted arguments are: 1) oCalendarDate, (optional)calendarType" + | ||
"or 2) year, month, date, (optional) calendarType" + aArgs; | ||
default: | ||
throw new Error(`${"Invalid arguments. Accepted arguments are: 1) oCalendarDate, (optional)calendarType" | ||
+ "or 2) year, month, date, (optional) calendarType"}${aArgs}`); | ||
} | ||
@@ -57,3 +59,3 @@ } | ||
setYear(year) { | ||
checkNumericLike(year, "Invalid year: " + year); | ||
checkNumericLike(year, `Invalid year: ${year}`); | ||
this._oUDate.setUTCFullYear(year); | ||
@@ -68,3 +70,3 @@ return this; | ||
setMonth(month) { | ||
checkNumericLike(month, "Invalid month: " + month); | ||
checkNumericLike(month, `Invalid month: ${month}`); | ||
this._oUDate.setUTCMonth(month); | ||
@@ -79,3 +81,3 @@ return this; | ||
setDate(date) { | ||
checkNumericLike(date, "Invalid date: " + date); | ||
checkNumericLike(date, `Invalid date: ${date}`); | ||
this._oUDate.setUTCDate(date); | ||
@@ -121,5 +123,5 @@ return this; | ||
// this._oUDate's getters to avoid non-gregorian Year, Month and Date to be used to construct a Gregorian date | ||
var oLocalDate = new Date(this._oUDate.getTime()); | ||
const oLocalDate = new Date(this._oUDate.getTime()); | ||
//Make this date really local. Now getters are safe. | ||
// Make this date really local. Now getters are safe. | ||
oLocalDate.setFullYear(oLocalDate.getUTCFullYear(), oLocalDate.getUTCMonth(), oLocalDate.getUTCDate()); | ||
@@ -134,3 +136,3 @@ oLocalDate.setHours(0, 0, 0, 0); | ||
// this._oUDate's getters to avoid non-gregorian Year, Month and Date to be used to construct a Gregorian date | ||
var oUTCDate = new Date(this._oUDate.getTime()); | ||
const oUTCDate = new Date(this._oUDate.getTime()); | ||
oUTCDate.setUTCHours(0, 0, 0, 0); | ||
@@ -142,3 +144,3 @@ | ||
toString() { | ||
return this._oUDate.sCalendarType + ": " + this.getYear() + "/" + (this.getMonth() + 1) + "/" + this.getDate(); | ||
return `${this._oUDate.sCalendarType}: ${this.getYear()}/${this.getMonth() + 1}/${this.getDate()}`; | ||
} | ||
@@ -155,6 +157,6 @@ | ||
function isValidDate(date) { | ||
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date); | ||
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date); // eslint-disable-line | ||
} | ||
if (!isValidDate) { | ||
throw new Error("Date parameter must be a JavaScript Date object: [" + oJSDate + "]."); | ||
throw new Error(`Date parameter must be a JavaScript Date object: [${oJSDate}].`); | ||
} | ||
@@ -165,3 +167,3 @@ return new CalendarDate(oJSDate.getFullYear(), oJSDate.getMonth(), oJSDate.getDate(), sCalendarType); | ||
static fromTimestamp(iTimestamp, sCalendarType) { | ||
var oCalDate = new CalendarDate(0, 0, 1); | ||
const oCalDate = new CalendarDate(0, 0, 1); | ||
oCalDate._oUDate = UniversalDate.getInstance(new Date(iTimestamp), sCalendarType); | ||
@@ -175,5 +177,4 @@ return oCalDate; | ||
return UniversalDate.getInstance(createUTCDate(oDate), sCalendarType); | ||
} else { | ||
return new UniversalDate(createUTCDate(oDate).getTime()); | ||
} | ||
return new UniversalDate(createUTCDate(oDate).getTime()); | ||
} | ||
@@ -187,3 +188,3 @@ | ||
function createUTCDate(oDate) { | ||
var oUTCDate = new Date(Date.UTC(0, 0, 1)); | ||
const oUTCDate = new Date(Date.UTC(0, 0, 1)); | ||
@@ -197,3 +198,3 @@ oUTCDate.setUTCFullYear(oDate.getFullYear(), oDate.getMonth(), oDate.getDate()); | ||
if (!(oCalendarDate instanceof CalendarDate)) { | ||
throw "Invalid calendar date: [" + oCalendarDate + "]. Expected: sap.ui.unified.calendar.CalendarDate"; | ||
throw new Error(`Invalid calendar date: [${oCalendarDate}]. Expected: sap.ui.unified.calendar.CalendarDate`); | ||
} | ||
@@ -209,3 +210,3 @@ } | ||
function checkNumericLike(value, message) { | ||
if (value == undefined || value === Infinity || isNaN(value)) {//checks also for null. | ||
if (value === undefined || value === Infinity || isNaN(value)) { // eslint-disable-line | ||
throw message; | ||
@@ -215,2 +216,2 @@ } | ||
export default CalendarDate; | ||
export default CalendarDate; |
@@ -8,12 +8,12 @@ import Gregorian from "@ui5/webcomponents-core/dist/sap/ui/core/date/Gregorian"; | ||
export default { | ||
addCalendarClass: (calendarType, CalendarDateClass) => { | ||
registry.set(calendarType, CalendarDateClass); | ||
}, | ||
getCalendarClass: (calendarType) => { | ||
if (!calendarType) { | ||
// TODO add in configuration | ||
calendarType = CalendarType.Gregorian; | ||
} | ||
return registry.get(calendarType); | ||
} | ||
}; | ||
addCalendarClass: (calendarType, CalendarDateClass) => { | ||
registry.set(calendarType, CalendarDateClass); | ||
}, | ||
getCalendarClass: calendarType => { | ||
if (!calendarType) { | ||
// TODO: add in configuration | ||
calendarType = CalendarType.Gregorian; | ||
} | ||
return registry.get(calendarType); | ||
}, | ||
}; |
@@ -11,3 +11,3 @@ import DataType from "../types/DataType"; | ||
Buddhist: "Buddhist", | ||
Persian: "Persian" | ||
Persian: "Persian", | ||
}; | ||
@@ -14,0 +14,0 @@ |
@@ -0,324 +1,97 @@ | ||
import "../LocaleDataConfigurationProvider"; | ||
import UniversalDate from "@ui5/webcomponents-core/dist/sap/ui/core/date/UniversalDate"; | ||
import CalendarDate from "./CalendarDate"; | ||
import Locale from "@ui5/webcomponents-core/dist/sap/ui/core/Locale"; | ||
import LocaleData from "@ui5/webcomponents-core/dist/sap/ui/core/LocaleData"; | ||
import jQuery from "@ui5/webcomponents-core/dist/sap/ui/thirdparty/jquery"; | ||
class CalendarUtils { | ||
static _createLocalDate(oDate, bTime) { | ||
const calculateWeekNumber = (oDate, iYear, oLocale, oLocaleData) => { | ||
let iWeekNum = 0; | ||
let iWeekDay = 0; | ||
const iFirstDayOfWeek = oLocaleData.getFirstDayOfWeek(); | ||
var oLocaleDate; | ||
// search Locale for containing "en-US", since sometimes | ||
// when any user settings have been defined, subtag "sapufmt" is added to the locale name | ||
// this is described inside sap.ui.core.Configuration file | ||
if (oLocale && (oLocale.getLanguage() === "en" && oLocale.getRegion() === "US")) { | ||
/* | ||
* in US the week starts with Sunday | ||
* The first week of the year starts with January 1st. But Dec. 31 is still in the last year | ||
* So the week beginning in December and ending in January has 2 week numbers | ||
*/ | ||
const oJanFirst = new UniversalDate(oDate.getTime()); | ||
oJanFirst.setUTCFullYear(iYear, 0, 1); | ||
iWeekDay = oJanFirst.getUTCDay(); | ||
if (oDate) { | ||
var oMyDate; | ||
// get the date for the same weekday like jan 1. | ||
const oCheckDate = new UniversalDate(oDate.getTime()); | ||
oCheckDate.setUTCDate(oCheckDate.getUTCDate() - oCheckDate.getUTCDay() + iWeekDay); | ||
if (oDate instanceof UniversalDate) { | ||
oMyDate = oDate.getJSDate(); | ||
} else { | ||
oMyDate = oDate; | ||
} | ||
iWeekNum = Math.round((oCheckDate.getTime() - oJanFirst.getTime()) / 86400000 / 7) + 1; | ||
} else { | ||
// normally the first week of the year is the one where the first Thursday of the year is | ||
// find Thursday of this week | ||
// if the checked day is before the 1. day of the week use a day of the previous week to check | ||
const oThursday = new UniversalDate(oDate.getTime()); | ||
oThursday.setUTCDate(oThursday.getUTCDate() - iFirstDayOfWeek); | ||
iWeekDay = oThursday.getUTCDay(); | ||
oThursday.setUTCDate(oThursday.getUTCDate() - iWeekDay + 4); | ||
oLocaleDate = new Date(oMyDate.getUTCFullYear(), oMyDate.getUTCMonth(), oMyDate.getUTCDate()); | ||
if (oMyDate.getFullYear() < 1000) { | ||
oLocaleDate.setFullYear(oMyDate.getFullYear()); | ||
} | ||
if (bTime) { | ||
oLocaleDate.setHours(oMyDate.getUTCHours()); | ||
oLocaleDate.setMinutes(oMyDate.getUTCMinutes()); | ||
oLocaleDate.setSeconds(oMyDate.getUTCSeconds()); | ||
oLocaleDate.setMilliseconds(oMyDate.getUTCMilliseconds()); | ||
} | ||
const oFirstDayOfYear = new UniversalDate(oThursday.getTime()); | ||
oFirstDayOfYear.setUTCMonth(0, 1); | ||
iWeekDay = oFirstDayOfYear.getUTCDay(); | ||
let iAddDays = 0; | ||
if (iWeekDay > 4) { | ||
iAddDays = 7; // first day of year is after Thursday, so first Thursday is in the next week | ||
} | ||
const oFirstThursday = new UniversalDate(oFirstDayOfYear.getTime()); | ||
oFirstThursday.setUTCDate(1 - iWeekDay + 4 + iAddDays); | ||
return oLocaleDate; | ||
iWeekNum = Math.round((oThursday.getTime() - oFirstThursday.getTime()) / 86400000 / 7) + 1; | ||
} | ||
static _createUTCDate(oDate, bTime) { | ||
return iWeekNum; | ||
}; | ||
var oUTCDate; | ||
const getFirstDateOfWeek = oDate => { | ||
const oUniversalDate = new UniversalDate(oDate.getTime()), | ||
oLocaleData = LocaleData.getInstance(new Locale("en")), | ||
iCLDRFirstWeekDay = oLocaleData.getFirstDayOfWeek(); | ||
if (oDate) { | ||
var oMyDate; | ||
if (oDate instanceof UniversalDate) { | ||
oMyDate = oDate.getJSDate(); | ||
} else { | ||
oMyDate = oDate; | ||
} | ||
const oWeek = UniversalDate.getWeekByDate(oUniversalDate.getCalendarType(), oUniversalDate.getUTCFullYear(), | ||
oUniversalDate.getUTCMonth(), oUniversalDate.getUTCDate()); | ||
oUTCDate = new Date(Date.UTC(oMyDate.getFullYear(), oMyDate.getMonth(), oMyDate.getDate())); | ||
if (oMyDate.getFullYear() < 1000) { | ||
oUTCDate.setUTCFullYear(oMyDate.getFullYear()); | ||
} | ||
const oFirstDateOfWeek = UniversalDate.getFirstDateOfWeek(oUniversalDate.getCalendarType(), oWeek.year, oWeek.week); | ||
const oFirstUniversalDateOfWeek = new UniversalDate(Date.UTC(oFirstDateOfWeek.year, oFirstDateOfWeek.month, oFirstDateOfWeek.day)); | ||
if (bTime) { | ||
oUTCDate.setUTCHours(oMyDate.getHours()); | ||
oUTCDate.setUTCMinutes(oMyDate.getMinutes()); | ||
oUTCDate.setUTCSeconds(oMyDate.getSeconds()); | ||
oUTCDate.setUTCMilliseconds(oMyDate.getMilliseconds()); | ||
} | ||
} | ||
return oUTCDate; | ||
// In case the day of the computed weekFirstDate is not as in CLDR(e.g. en_US locales), make sure we align it | ||
while (oFirstUniversalDateOfWeek.getUTCDay() !== iCLDRFirstWeekDay) { | ||
oFirstUniversalDateOfWeek.setUTCDate(oFirstUniversalDateOfWeek.getUTCDate() - 1); | ||
} | ||
static _createUniversalUTCDate(oDate, sCalendarType, bTime) { | ||
return new UniversalDate(Date.UTC(oFirstUniversalDateOfWeek.getUTCFullYear(), oFirstUniversalDateOfWeek.getUTCMonth(), | ||
oFirstUniversalDateOfWeek.getUTCDate(), oDate.getUTCHours(), oDate.getUTCMinutes(), oDate.getUTCSeconds())).getJSDate(); | ||
}; | ||
var oUTCDate; | ||
const getFirstDateOfMonth = oDate => { | ||
const oNewDate = new UniversalDate(oDate.getTime()); | ||
oNewDate.setUTCDate(1); | ||
if (sCalendarType) { | ||
oUTCDate = UniversalDate.getInstance(this._createUTCDate(oDate, bTime), sCalendarType); | ||
} else { | ||
oUTCDate = new UniversalDate(this._createUTCDate(oDate, bTime).getTime()); // use getTime() because IE and FF can not parse dates < 0100.01.01 | ||
} | ||
return oNewDate; | ||
}; | ||
return oUTCDate; | ||
const monthsDiffer = (oDate1, oDate2) => { | ||
return (oDate1.getMonth() !== oDate2.getMonth() || oDate1.getFullYear() !== oDate2.getFullYear()); | ||
}; | ||
} | ||
const isDateLastInMonth = oDate => { | ||
const oNextDay = new Date(oDate.getTime() + 24 * 60 * 60 * 1000); | ||
return oNextDay.getUTCDate() < oDate.getUTCDate(); | ||
}; | ||
static calculateWeekNumber(oDate, iYear, oLocale, oLocaleData) { | ||
var iWeekNum = 0; | ||
var iWeekDay = 0; | ||
var iFirstDayOfWeek = oLocaleData.getFirstDayOfWeek(); | ||
// search Locale for containing "en-US", since sometimes | ||
// when any user settings have been defined, subtag "sapufmt" is added to the locale name | ||
// this is described inside sap.ui.core.Configuration file | ||
if (oLocale && (oLocale.getLanguage() == 'en' && oLocale.getRegion() == 'US')) { | ||
/* | ||
* in US the week starts with Sunday | ||
* The first week of the year starts with January 1st. But Dec. 31 is still in the last year | ||
* So the week beginning in December and ending in January has 2 week numbers | ||
*/ | ||
var oJanFirst = new UniversalDate(oDate.getTime()); | ||
oJanFirst.setUTCFullYear(iYear, 0, 1); | ||
iWeekDay = oJanFirst.getUTCDay(); | ||
//get the date for the same weekday like jan 1. | ||
var oCheckDate = new UniversalDate(oDate.getTime()); | ||
oCheckDate.setUTCDate(oCheckDate.getUTCDate() - oCheckDate.getUTCDay() + iWeekDay); | ||
iWeekNum = Math.round((oCheckDate.getTime() - oJanFirst.getTime()) / 86400000 / 7) + 1; | ||
} else { | ||
// normally the first week of the year is the one where the first Thursday of the year is | ||
// find Thursday of this week | ||
// if the checked day is before the 1. day of the week use a day of the previous week to check | ||
var oThursday = new UniversalDate(oDate.getTime()); | ||
oThursday.setUTCDate(oThursday.getUTCDate() - iFirstDayOfWeek); | ||
iWeekDay = oThursday.getUTCDay(); | ||
oThursday.setUTCDate(oThursday.getUTCDate() - iWeekDay + 4); | ||
var oFirstDayOfYear = new UniversalDate(oThursday.getTime()); | ||
oFirstDayOfYear.setUTCMonth(0, 1); | ||
iWeekDay = oFirstDayOfYear.getUTCDay(); | ||
var iAddDays = 0; | ||
if (iWeekDay > 4) { | ||
iAddDays = 7; // first day of year is after Thursday, so first Thursday is in the next week | ||
} | ||
var oFirstThursday = new UniversalDate(oFirstDayOfYear.getTime()); | ||
oFirstThursday.setUTCDate(1 - iWeekDay + 4 + iAddDays); | ||
iWeekNum = Math.round((oThursday.getTime() - oFirstThursday.getTime()) / 86400000 / 7) + 1; | ||
} | ||
return iWeekNum; | ||
} | ||
static getFirstDateOfWeek(oDate) { | ||
var oUniversalDate = new UniversalDate(oDate.getTime()), | ||
oFirstDateOfWeek, | ||
oFirstUniversalDateOfWeek, | ||
//MODIFIED | ||
oLocaleData = LocaleData.getInstance(new Locale('en')), | ||
iCLDRFirstWeekDay = oLocaleData.getFirstDayOfWeek(), | ||
oWeek; | ||
oWeek = UniversalDate.getWeekByDate(oUniversalDate.getCalendarType(), oUniversalDate.getUTCFullYear(), | ||
oUniversalDate.getUTCMonth(), oUniversalDate.getUTCDate()); | ||
oFirstDateOfWeek = UniversalDate.getFirstDateOfWeek(oUniversalDate.getCalendarType(), oWeek.year, oWeek.week); | ||
oFirstUniversalDateOfWeek = new UniversalDate(Date.UTC(oFirstDateOfWeek.year, oFirstDateOfWeek.month, oFirstDateOfWeek.day)); | ||
//In case the day of the computed weekFirstDate is not as in CLDR(e.g. en_US locales), make sure we align it | ||
while (oFirstUniversalDateOfWeek.getUTCDay() !== iCLDRFirstWeekDay) { | ||
oFirstUniversalDateOfWeek.setUTCDate(oFirstUniversalDateOfWeek.getUTCDate() - 1); | ||
} | ||
return new UniversalDate(Date.UTC(oFirstUniversalDateOfWeek.getUTCFullYear(), oFirstUniversalDateOfWeek.getUTCMonth(), | ||
oFirstUniversalDateOfWeek.getUTCDate(), oDate.getUTCHours(), oDate.getUTCMinutes(), oDate.getUTCSeconds())).getJSDate(); | ||
} | ||
static getFirstDateOfMonth(oDate) { | ||
var oNewDate = new UniversalDate(oDate.getTime()); | ||
oNewDate.setUTCDate(1); | ||
return oNewDate; | ||
} | ||
static _getNumberOfWeeksForYear(iYear) { | ||
//MODIFIED | ||
// var sLocale = sap.ui.getCore().getConfiguration().getFormatLocale(), | ||
// oLocaleData = LocaleData.getInstance(new Locale(sLocale)), | ||
var oLocaleData = LocaleData.getInstance(new Locale('en')), | ||
o1stJan = new Date(Date.UTC(iYear, 0, 1)), | ||
i1stDay = o1stJan.getUTCDay(), | ||
iNumberOfWeeksInYear = 52; | ||
//This is valid for all the regions where Sunday is the first day of the week | ||
if (oLocaleData.getFirstDayOfWeek() === 0) { | ||
if (i1stDay === 5 || i1stDay === 6) { | ||
iNumberOfWeeksInYear = 53; | ||
} | ||
} else { | ||
if (i1stDay === 3 || i1stDay === 4) { | ||
iNumberOfWeeksInYear = 53; | ||
} | ||
} | ||
return iNumberOfWeeksInYear; | ||
} | ||
static monthsDiffer(oDate1, oDate2) { | ||
return (oDate1.getMonth() !== oDate2.getMonth() || oDate1.getFullYear() !== oDate2.getFullYear()); | ||
} | ||
static isDateLastInMonth(oDate) { | ||
var oNextDay = new Date(oDate.getTime() + 24 * 60 * 60 * 1000); | ||
return oNextDay.getUTCDate() < oDate.getUTCDate(); | ||
} | ||
static _updateUTCDate(oDate, iYear, iMonth, iDate, iHours, iMinutes, iSeconds, iMilliseconds) { | ||
if (jQuery.isNumeric(iYear)) { | ||
oDate.setUTCFullYear(iYear); | ||
} | ||
if (jQuery.isNumeric(iMonth)) { | ||
oDate.setUTCMonth(iMonth); | ||
} | ||
if (jQuery.isNumeric(iDate)) { | ||
oDate.setUTCDate(iDate); | ||
} | ||
if (jQuery.isNumeric(iHours)) { | ||
oDate.setUTCHours(iHours); | ||
} | ||
if (jQuery.isNumeric(iMinutes)) { | ||
oDate.setUTCMinutes(iMinutes); | ||
} | ||
if (jQuery.isNumeric(iSeconds)) { | ||
oDate.setUTCSeconds(iSeconds); | ||
} | ||
if (jQuery.isNumeric(iMilliseconds)) { | ||
oDate.setUTCMilliseconds(iMilliseconds); | ||
} | ||
} | ||
static _checkJSDateObject(oDate) { | ||
// Cross frame check for a date should be performed here otherwise setDateValue would fail in OPA tests | ||
// because Date object in the test is different than the Date object in the application (due to the iframe). | ||
// We can use jQuery.type or this method: | ||
// function isValidDate (date) { | ||
// return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date); | ||
//} | ||
if (jQuery.type(oDate) !== "date") { | ||
throw new Error("Date must be a JavaScript date object."); | ||
} | ||
} | ||
static _checkYearInValidRange(iYear) { | ||
if (!jQuery.isNumeric(iYear) || (iYear < 1 || iYear > 9999)) { | ||
throw new Error("Year must be in valid range (between year 0001 and year 9999)."); | ||
} | ||
} | ||
static _isNextMonth(oDate1, oDate2) { | ||
return (oDate1.getMonth() > oDate2.getMonth() && oDate1.getFullYear() === oDate2.getFullYear()) | ||
|| oDate1.getFullYear() > oDate2.getFullYear(); | ||
} | ||
static _daysInMonth(oCalendarDate) { | ||
this._checkCalendarDate(oCalendarDate); | ||
oCalendarDate = new CalendarDate(oCalendarDate); | ||
oCalendarDate.setDate(1); | ||
oCalendarDate.setMonth(oCalendarDate.getMonth() + 1); | ||
oCalendarDate.setDate(0); | ||
return oCalendarDate.getDate(); | ||
} | ||
static _isLastDateInMonth(oCalendarDate) { | ||
return oCalendarDate.getDate() === CalendarUtils._daysInMonth(oCalendarDate); | ||
} | ||
static _getFirstDateOfMonth(oCalendarDate) { | ||
this._checkCalendarDate(oCalendarDate); | ||
var oJSDate = CalendarUtils.getFirstDateOfMonth(oCalendarDate.toUTCJSDate()).getJSDate(); | ||
oJSDate.setFullYear(oJSDate.getUTCFullYear(), oJSDate.getUTCMonth(), oJSDate.getUTCDate()); | ||
return CalendarDate.fromLocalJSDate(oJSDate, oCalendarDate.getCalendarType()); | ||
} | ||
static _minDate(sCalendarType) { | ||
return new CalendarDate(1, 0, 1, sCalendarType); | ||
} | ||
static _maxDate(sCalendarType) { | ||
var oCalDate = new CalendarDate(9999, 11, 1, sCalendarType); | ||
oCalDate.setDate(this._daysInMonth(oCalDate));// 31st for Gregorian Calendar | ||
return new CalendarDate(oCalDate); | ||
} | ||
static _isBetween(oDate, oStartDate, oEndDate, inclusive) { | ||
this._checkCalendarDate(oDate); | ||
this._checkCalendarDate(oStartDate); | ||
this._checkCalendarDate(oEndDate); | ||
if (inclusive) { | ||
return oDate.isSameOrAfter(oStartDate) && oDate.isSameOrBefore(oEndDate); | ||
} else { | ||
return oDate.isAfter(oStartDate) && oDate.isBefore(oEndDate); | ||
} | ||
} | ||
static _daysBetween(oFirstDate, oSecondDate) { | ||
this._checkCalendarDate(oFirstDate); | ||
this._checkCalendarDate(oSecondDate); | ||
return Math.ceil((oFirstDate.valueOf() - oSecondDate.valueOf()) / (this.HOURS24)); | ||
} | ||
static _isOutside(oCalendarDate, oStartCalendarDate, oEndCalendarDate) { | ||
return !this._isBetween(oCalendarDate, oStartCalendarDate, oEndCalendarDate, true); | ||
} | ||
static _isSameMonthAndYear(oCalendarDate1, oCalendarDate2) { | ||
this._checkCalendarDate(oCalendarDate1); | ||
this._checkCalendarDate(oCalendarDate2); | ||
return oCalendarDate1.getYear() === oCalendarDate2.getYear() && oCalendarDate1.getMonth() === oCalendarDate2.getMonth(); | ||
} | ||
static _checkCalendarDate(oCalendarDate) { | ||
if (!oCalendarDate || !(oCalendarDate instanceof CalendarDate)) { | ||
throw "Invalid calendar date: [" + oCalendarDate + "]. Expected: sap.ui.unified.calendar.CalendarDate"; | ||
} | ||
} | ||
static _getWeek(oCalendarDate) { | ||
this._checkCalendarDate(oCalendarDate); | ||
return UniversalDate.getWeekByDate(oCalendarDate.getCalendarType(), oCalendarDate.getYear(), oCalendarDate.getMonth(), oCalendarDate.getDate()); | ||
} | ||
} | ||
CalendarUtils.MAX_MILLISECONDS = 8640000000000000; | ||
CalendarUtils.HOURS24 = 1000 * 3600 * 24; | ||
export default CalendarUtils; | ||
export { | ||
calculateWeekNumber, | ||
getFirstDateOfWeek, | ||
getFirstDateOfMonth, | ||
monthsDiffer, | ||
isDateLastInMonth, | ||
}; |
const INTERVAL = 300; | ||
class CustomResize { | ||
static initialize() { | ||
@@ -18,3 +17,3 @@ CustomResize.initialized = false; | ||
height: ref ? ref.offsetHeight : 0, | ||
callbacks: existingCallbacks.concat(callback) | ||
callbacks: existingCallbacks.concat(callback), | ||
}); | ||
@@ -59,3 +58,3 @@ | ||
const callbacks = listenerObject ? listenerObject.callbacks : []; | ||
const filteredCallbacks = callbacks.filter((fn) => fn !== callback); | ||
const filteredCallbacks = callbacks.filter(fn => fn !== callback); | ||
@@ -80,2 +79,2 @@ if (!listenerObject || (callbacks.length === filteredCallbacks.length && callbacks.length !== 0)) { | ||
export default CustomResize | ||
export default CustomResize; |
@@ -0,1 +1,10 @@ | ||
import { | ||
isDown, | ||
isUp, | ||
isLeft, | ||
isRight, | ||
isHome, | ||
isEnd, | ||
} from "../events/PseudoEvents"; | ||
import EventProvider from "../EventProvider"; | ||
@@ -6,3 +15,2 @@ import WebComponent from "../WebComponent"; | ||
class ItemNavigation extends EventProvider { | ||
constructor(rootControl, options = {}) { | ||
@@ -44,3 +52,3 @@ super(); | ||
//stops browser scrolling with up/down keys | ||
// stops browser scrolling with up/down keys | ||
event.stopPropagation(); | ||
@@ -51,3 +59,29 @@ event.stopImmediatePropagation(); | ||
onsapup(event) { | ||
onkeydown(event) { | ||
if (isUp(event)) { | ||
return this._handleUp(event); | ||
} | ||
if (isDown(event)) { | ||
return this._handleDown(event); | ||
} | ||
if (isLeft(event)) { | ||
return this._handleLeft(event); | ||
} | ||
if (isRight(event)) { | ||
return this._handleRight(event); | ||
} | ||
if (isHome(event)) { | ||
return this._handleHome(event); | ||
} | ||
if (isEnd(event)) { | ||
return this._handleEnd(event); | ||
} | ||
} | ||
_handleUp(event) { | ||
if (this._canNavigate()) { | ||
@@ -59,3 +93,3 @@ this.currentIndex -= this.rowSize; | ||
onsapdown(event) { | ||
_handleDown(event) { | ||
if (this._canNavigate()) { | ||
@@ -67,3 +101,3 @@ this.currentIndex += this.rowSize; | ||
onsapleft(event) { | ||
_handleLeft(event) { | ||
if (this._canNavigate()) { | ||
@@ -75,3 +109,3 @@ this.currentIndex -= 1; | ||
onsapright(event) { | ||
_handleRight(event) { | ||
if (this._canNavigate()) { | ||
@@ -83,3 +117,3 @@ this.currentIndex += 1; | ||
onsaphome(event) { | ||
_handleHome(event) { | ||
if (this._canNavigate()) { | ||
@@ -92,6 +126,6 @@ const homeEndRange = this.rowSize > 1 ? this.rowSize : this._getItems().length; | ||
onsapend(event) { | ||
_handleEnd(event) { | ||
if (this._canNavigate()) { | ||
const homeEndRange = this.rowSize > 1 ? this.rowSize : this._getItems().length; | ||
this.currentIndex += (homeEndRange - 1 - this.currentIndex % homeEndRange); | ||
this.currentIndex += (homeEndRange - 1 - this.currentIndex % homeEndRange); // eslint-disable-line | ||
this._onKeyPress(event); | ||
@@ -113,3 +147,3 @@ } | ||
let items = origItems.slice(0); | ||
const items = origItems.slice(0); | ||
@@ -126,3 +160,3 @@ for (let i = 0; i < items.length; i++) { | ||
focusCurrent() { | ||
let currentItem = this._getCurrentItem(); | ||
const currentItem = this._getCurrentItem(); | ||
if (currentItem) { | ||
@@ -134,3 +168,3 @@ currentItem.focus(); | ||
_canNavigate() { | ||
let currentItem = this._getCurrentItem(); | ||
const currentItem = this._getCurrentItem(); | ||
@@ -149,3 +183,3 @@ let activeElement = document.activeElement; | ||
//normalize the index | ||
// normalize the index | ||
while (this.currentIndex >= items.length) { | ||
@@ -155,4 +189,8 @@ this.currentIndex -= this.rowSize; | ||
let currentItem = items[this.currentIndex]; | ||
if (this.currentIndex < 0) { | ||
this.currentIndex = 0; | ||
} | ||
const currentItem = items[this.currentIndex]; | ||
if (currentItem instanceof WebComponent) { | ||
@@ -166,3 +204,3 @@ return currentItem.getFocusDomRef(); | ||
return this.rootControl.getDomRef().querySelector("#" + currentItem.id); | ||
return this.rootControl.getDomRef().querySelector(`#${currentItem.id}`); | ||
} | ||
@@ -185,2 +223,2 @@ | ||
export default ItemNavigation; | ||
export default ItemNavigation; |
class NativeResize { | ||
static initialize() { | ||
NativeResize.resizeObserver = new window.ResizeObserver(entries => { | ||
// call attached callbacks | ||
@@ -32,3 +30,3 @@ entries.forEach(entry => { | ||
const callbacks = NativeResize.observedObjects.get(ref) || []; | ||
const filteredCallbacks = callbacks.filter((fn) => fn !== callback); | ||
const filteredCallbacks = callbacks.filter(fn => fn !== callback); | ||
@@ -48,2 +46,2 @@ // TODO: think for a validation mechanism | ||
export default NativeResize; | ||
export default NativeResize; |
@@ -1,7 +0,6 @@ | ||
import WebComponent from '../WebComponent'; | ||
import NativeResize from './NativeResize'; | ||
import CustomResize from './CustomResize'; | ||
import WebComponent from "../WebComponent"; | ||
import NativeResize from "./NativeResize"; | ||
import CustomResize from "./CustomResize"; | ||
class ResizeHandler { | ||
static initialize() { | ||
@@ -42,3 +41,2 @@ ResizeHandler.Implementation = window.ResizeObserver ? NativeResize : CustomResize; | ||
static register(ref, callback) { | ||
if (ref instanceof WebComponent) { | ||
@@ -59,3 +57,2 @@ ref = ref.getDomRef(); | ||
static deregister(ref, callback) { | ||
if (ref instanceof WebComponent) { | ||
@@ -71,2 +68,2 @@ ref = ref.getDomRef(); | ||
export default ResizeHandler; | ||
export default ResizeHandler; |
@@ -1,8 +0,7 @@ | ||
import EventProvider from '../EventProvider'; | ||
import scroll from '../animations/scroll'; | ||
import EventProvider from "../EventProvider"; | ||
import scroll from "../animations/scroll"; | ||
const scrollEventName = 'scroll'; | ||
const scrollEventName = "scroll"; | ||
class ScrollEnablement extends EventProvider { | ||
constructor() { | ||
@@ -28,4 +27,4 @@ super(); | ||
element: this._container, | ||
dx: dx, | ||
dy: dy | ||
dx, | ||
dy, | ||
}); | ||
@@ -43,12 +42,12 @@ } | ||
_isTouchInside(touch) { | ||
let rect = this._container.getBoundingClientRect(); | ||
let x = touch.clientX; | ||
let y = touch.clientY; | ||
const rect = this._container.getBoundingClientRect(); | ||
const x = touch.clientX; | ||
const y = touch.clientY; | ||
return x >= rect.left && x <= rect.right && | ||
y >= rect.top && y <= rect.bottom; | ||
return x >= rect.left && x <= rect.right | ||
&& y >= rect.top && y <= rect.bottom; | ||
} | ||
ontouchstart(event) { | ||
let touch = event.touches[0]; | ||
const touch = event.touches[0]; | ||
this._prevDragX = touch.pageX; | ||
@@ -61,3 +60,2 @@ this._prevDragY = touch.pageY; | ||
ontouchmove(event) { | ||
if (!this._canScroll) { | ||
@@ -67,7 +65,7 @@ return; | ||
let container = this._container; | ||
let touch = event.touches[0]; | ||
const container = this._container; | ||
const touch = event.touches[0]; | ||
let dragX = touch.pageX; | ||
let dragY = touch.pageY; | ||
const dragX = touch.pageX; | ||
const dragY = touch.pageY; | ||
@@ -84,2 +82,2 @@ container.scrollLeft += this._prevDragX - dragX; | ||
export default ScrollEnablement; | ||
export default ScrollEnablement; |
@@ -1,8 +0,8 @@ | ||
import PseudoEvents from '@ui5/webcomponents-core/dist/sap/ui/events/PseudoEvents'; | ||
import ControlEvents from './events/ControlEvents'; | ||
import ControlEvents from "./events/ControlEvents"; | ||
import getOriginalEventTarget from "./events/getOriginalEventTarget"; | ||
import WebComponent from "./WebComponent"; | ||
const handleEvent = function (event) { | ||
const handleEvent = function handleEvent(event) { | ||
// Get the DOM node where the original event occurred | ||
let target = getDomTarget(event); | ||
let target = getOriginalEventTarget(event); | ||
event.ui5target = target; | ||
@@ -20,35 +20,13 @@ | ||
const getDomTarget = function(event) { | ||
// Default - composedPath should be used (also covered by polyfill) | ||
if (typeof event.composedPath === "function") { | ||
const composedPath = event.composedPath(); | ||
if (Array.isArray(composedPath) && composedPath.length) { | ||
return composedPath[0]; | ||
} | ||
const processDOMNode = function processDOMNode(node, event) { | ||
if (node && node instanceof WebComponent) { | ||
return dispatchEvent(node, event); | ||
} | ||
// Fallback | ||
return event.target; | ||
}; | ||
const processDOMNode = function(node, event) { | ||
const id = node.getAttribute("data-sap-ui"); | ||
const tag = node.tagName; | ||
let control; | ||
if (tag.match(/^ui5-/i)) { | ||
control = node; | ||
} | ||
if (control && control._handleEvent) { | ||
return dispatchEvent(control, event); | ||
} | ||
return true; | ||
}; | ||
const dispatchEvent = function(control, event) { | ||
const dispatchEvent = function dispatchEvent(ui5WebComponent, event) { | ||
// Handle the original event (such as "keydown") | ||
control._handleEvent(event); | ||
ui5WebComponent._handleEvent(event); | ||
if (event.isImmediatePropagationStopped()) { | ||
@@ -58,14 +36,7 @@ return false; | ||
// Handle pseudo events that derive from the original event (such as "sapselect") | ||
const pseudoTypes = getPseudoTypesFor(event); | ||
for (let i = 0, len = pseudoTypes.length; i < len; i++) { | ||
control._handleEvent(event, pseudoTypes[i]); | ||
if (event.isImmediatePropagationStopped()) { | ||
return false; | ||
} | ||
} | ||
/* eslint-disable */ | ||
if (event.isPropagationStopped()) { | ||
return false; | ||
} | ||
/* eslint-enable */ | ||
@@ -75,38 +46,5 @@ return true; | ||
// Stores the calculated list of pseudo events per event | ||
const pseudoMap = new WeakMap(); | ||
const getPseudoTypesFor = function(event) { | ||
if (pseudoMap.has(event)) { | ||
return pseudoMap.get(event); | ||
} | ||
const aPseudoTypes = []; | ||
if (PseudoEvents.getBasicTypes().indexOf(event.type) !== -1) { | ||
const iLength = PseudoEvents.order.length; | ||
let oPseudo = null; | ||
for (let i = 0; i < iLength; i++) { | ||
oPseudo = PseudoEvents.events[PseudoEvents.order[i]]; | ||
if (oPseudo.aTypes | ||
&& oPseudo.aTypes.indexOf(event.type) > -1 | ||
&& oPseudo.fnCheck | ||
&& oPseudo.fnCheck(event)) { | ||
aPseudoTypes.push(oPseudo.sName); | ||
} | ||
} | ||
} | ||
pseudoMap.set(event, aPseudoTypes); | ||
return aPseudoTypes; | ||
}; | ||
const getParentDOMNode = function(node) { | ||
const getParentDOMNode = function getParentDOMNode(node) { | ||
const parentNode = node.parentNode; | ||
// Skip the custom element tag (host) only if crossing a shadow DOM boundary | ||
// The reason is that the event was already dispatched to the light control while traversing the shadow DOM | ||
if (parentNode && parentNode.host) { | ||
@@ -134,3 +72,2 @@ return parentNode.host; | ||
export default DOMEventHandler; | ||
export default DOMEventHandler; |
@@ -7,11 +7,12 @@ class EventProvider { | ||
attachEvent(eventName, fnFunction) { | ||
let eventRegistry = this._eventRegistry; | ||
const eventRegistry = this._eventRegistry; | ||
let eventListeners = eventRegistry[eventName]; | ||
if (!Array.isArray(eventListeners)) { | ||
eventListeners = eventRegistry[eventName] = []; | ||
eventRegistry[eventName] = []; | ||
eventListeners = eventRegistry[eventName]; | ||
} | ||
eventListeners.push({ | ||
'function': fnFunction | ||
"function": fnFunction, | ||
}); | ||
@@ -21,4 +22,4 @@ } | ||
detachEvent(eventName, fnFunction) { | ||
let eventRegistry = this._eventRegistry; | ||
let eventListeners = eventRegistry[eventName]; | ||
const eventRegistry = this._eventRegistry; | ||
const eventListeners = eventRegistry[eventName]; | ||
@@ -30,4 +31,4 @@ if (!eventListeners) { | ||
for (let i = 0; i < eventListeners.length; i++) { | ||
let event = eventListeners[i]; | ||
if (event['function'] == fnFunction) { | ||
const event = eventListeners[i]; | ||
if (event["function"] === fnFunction) { // eslint-disable-line | ||
eventListeners.splice(i, 1); | ||
@@ -37,3 +38,3 @@ } | ||
if (eventListeners.length == 0) { | ||
if (eventListeners.length === 0) { | ||
delete eventRegistry[eventName]; | ||
@@ -44,4 +45,4 @@ } | ||
fireEvent(eventName, data) { | ||
let eventRegistry = this._eventRegistry; | ||
let eventListeners = eventRegistry[eventName]; | ||
const eventRegistry = this._eventRegistry; | ||
const eventListeners = eventRegistry[eventName]; | ||
@@ -53,3 +54,3 @@ if (!eventListeners) { | ||
eventListeners.forEach(event => { | ||
event['function'].call(this, data); | ||
event["function"].call(this, data); // eslint-disable-line | ||
}); | ||
@@ -59,4 +60,4 @@ } | ||
isHandlerAttached(eventName, fnFunction) { | ||
let eventRegistry = this._eventRegistry; | ||
let eventListeners = eventRegistry[eventName]; | ||
const eventRegistry = this._eventRegistry; | ||
const eventListeners = eventRegistry[eventName]; | ||
@@ -68,4 +69,4 @@ if (!eventListeners) { | ||
for (let i = 0; i < eventListeners.length; i++) { | ||
let event = eventListeners[i]; | ||
if (event['function'] == fnFunction) { | ||
const event = eventListeners[i]; | ||
if (event["function"] === fnFunction) { // eslint-disable-line | ||
return true; | ||
@@ -83,2 +84,2 @@ } | ||
export default EventProvider; | ||
export default EventProvider; |
import Device from "@ui5/webcomponents-core/dist/sap/ui/Device"; | ||
import * as Gestures from "@polymer/polymer/lib/utils/gestures"; | ||
import Gestures from "./DefaultGestures"; | ||
@@ -8,3 +8,3 @@ /** | ||
*/ | ||
var oControlEvents = {}; | ||
const oControlEvents = {}; | ||
@@ -52,3 +52,3 @@ /** | ||
/* for more details please see : https://developer.mozilla.org/en-US/docs/Web/Reference/Events/input */ | ||
"input" | ||
"input", | ||
]; | ||
@@ -64,3 +64,3 @@ | ||
"up", | ||
"tap" | ||
"tap", | ||
]; | ||
@@ -74,3 +74,3 @@ | ||
*/ | ||
oControlEvents.bindAnyEvent = function (fnCallback) { | ||
oControlEvents.bindAnyEvent = function bindAnyEvent(fnCallback) { | ||
if (fnCallback) { | ||
@@ -105,2 +105,2 @@ oControlEvents.events.forEach(event => { | ||
export default oControlEvents; | ||
export default oControlEvents; |
@@ -6,3 +6,3 @@ | ||
EventEnrichment.run = function () { | ||
EventEnrichment.run = function run() { | ||
if (enriched) { | ||
@@ -18,17 +18,17 @@ return; | ||
Event.prototype.stopPropagation = function () { | ||
Event.prototype.stopPropagation = function stopPropagation() { | ||
stopPropagationSet.add(this); | ||
return originalStopPropagation.apply(this, arguments); | ||
return originalStopPropagation.apply(this, arguments); // eslint-disable-line | ||
}; | ||
Event.prototype.isPropagationStopped = function () { | ||
Event.prototype.isPropagationStopped = function isPropagationStopped() { | ||
return stopPropagationSet.has(this); | ||
}; | ||
Event.prototype.stopImmediatePropagation = function () { | ||
Event.prototype.stopImmediatePropagation = function stopImmediatePropagation() { | ||
stopImmediatePropagationSet.add(this); | ||
return originalStopImmediatePropagation.apply(this, arguments); | ||
return originalStopImmediatePropagation.apply(this, arguments); // eslint-disable-line | ||
}; | ||
Event.prototype.isImmediatePropagationStopped = function () { | ||
Event.prototype.isImmediatePropagationStopped = function isImmediatePropagationStopped() { | ||
return stopImmediatePropagationSet.has(this); | ||
@@ -35,0 +35,0 @@ }; |
import WebComponent from "./WebComponent"; | ||
var rFocusable = /^(?:input|select|textarea|button)$/i, | ||
const rFocusable = /^(?:input|select|textarea|button)$/i, | ||
rClickable = /^(?:a|area)$/i; | ||
class FocusHelper { | ||
static hasTabIndex(domElement) { | ||
if (domElement.disabled) { | ||
@@ -14,23 +12,22 @@ return false; | ||
let tabIndex = domElement.getAttribute("tabindex"); | ||
const tabIndex = domElement.getAttribute("tabindex"); | ||
if (tabIndex !== null && tabIndex !== undefined) { | ||
return parseInt(tabIndex, 10) >= 0; | ||
return parseInt(tabIndex) >= 0; | ||
} | ||
return rFocusable.test(domElement.nodeName) || | ||
rClickable.test(domElement.nodeName) && | ||
domElement.href; | ||
return rFocusable.test(domElement.nodeName) | ||
|| (rClickable.test(domElement.nodeName) | ||
&& domElement.href); | ||
} | ||
static isHidden(domElement) { | ||
if (domElement.nodeName === 'SLOT') { | ||
if (domElement.nodeName === "SLOT") { | ||
return false; | ||
} | ||
let rect = domElement.getBoundingClientRect(); | ||
const rect = domElement.getBoundingClientRect(); | ||
return (domElement.offsetWidth <= 0 && domElement.offsetHeight <= 0) | ||
|| domElement.style.visibility === "hidden" | ||
|| (rect.width === 0 && 0 && rect.height === 0); | ||
|| (rect.width === 0 && 0 && rect.height === 0); | ||
} | ||
@@ -54,3 +51,3 @@ | ||
if (container.assignedNodes && container.assignedNodes()) { | ||
let assignedElements = container.assignedNodes(); | ||
const assignedElements = container.assignedNodes(); | ||
child = forward ? assignedElements[0] : assignedElements[assignedElements.length - 1]; | ||
@@ -72,3 +69,2 @@ } else { | ||
if (child.nodeType === 1 && !FocusHelper.isHidden(child)) { | ||
if (FocusHelper.hasTabIndex(child)) { | ||
@@ -91,3 +87,2 @@ return child; | ||
static findFirstFocusableElement(container) { | ||
if (!container || FocusHelper.isHidden(container)) { | ||
@@ -101,3 +96,2 @@ return null; | ||
static findLastFocusableElement(container) { | ||
if (!container || FocusHelper.isHidden(container)) { | ||
@@ -112,3 +106,3 @@ return null; | ||
let hasTabableContent = false, | ||
content = node.children; | ||
content = node.children; // eslint-disable-line | ||
@@ -122,4 +116,4 @@ if (content) { | ||
if (!hasTabableContent && FocusHelper._isInsideShadowRoot(node)) { | ||
let customElement = FocusHelper._getCustomElement(node); | ||
let content = customElement.children; | ||
const customElement = FocusHelper._getCustomElement(node); | ||
const content = customElement.children; // eslint-disable-line | ||
@@ -135,4 +129,4 @@ if (content) { | ||
static getLastTabbableElement(node) { | ||
let tabbableContent = FocusHelper.getTabbableContent(node); | ||
return tabbableContent.length ? tabbableContent[tabbableContent.length - 1] : null; | ||
const tabbableContent = FocusHelper.getTabbableContent(node); | ||
return tabbableContent.length ? tabbableContent[tabbableContent.length - 1] : null; | ||
} | ||
@@ -142,3 +136,3 @@ | ||
let aTabbableContent = [], | ||
content = node.children; | ||
content = node.children; // eslint-disable-line | ||
@@ -150,4 +144,4 @@ if (content) { | ||
if (FocusHelper._isInsideShadowRoot(node)) { | ||
let customElement = FocusHelper._getCustomElement(node); | ||
let content = customElement.children; | ||
const customElement = FocusHelper._getCustomElement(node); | ||
const content = customElement.children; // eslint-disable-line | ||
@@ -163,3 +157,3 @@ if (content) { | ||
static _getTabbableContent(nodes) { | ||
let aTabbableContent = []; | ||
const aTabbableContent = []; | ||
@@ -172,3 +166,3 @@ Array.from(nodes).forEach(node => { | ||
// as the content is in the <span> template and it is always 2nd child | ||
let children = currentNode.shadowRoot.children; | ||
const children = currentNode.shadowRoot.children; | ||
currentNode = children.length === 1 ? children[0] : children[1]; | ||
@@ -196,3 +190,3 @@ } | ||
// as the content is in the <span> template and it is always 2nd child | ||
let children = currentNode.shadowRoot.children; | ||
const children = currentNode.shadowRoot.children; | ||
currentNode = children.length === 1 ? children[0] : children[1]; | ||
@@ -214,3 +208,3 @@ } | ||
let nodeName = node.nodeName.toLowerCase(); | ||
const nodeName = node.nodeName.toLowerCase(); | ||
@@ -222,3 +216,3 @@ if (node.hasAttribute("data-sap-no-tab-ref")) { | ||
// special tags | ||
if (nodeName === 'a') { | ||
if (nodeName === "a") { | ||
return !!node.href; | ||
@@ -247,2 +241,2 @@ } | ||
export default FocusHelper; | ||
export default FocusHelper; |
@@ -1,39 +0,37 @@ | ||
import iconFontTTF from "@ui5/webcomponents-core/dist/sap/ui/core/themes/base/fonts/SAP-icons.ttf"; | ||
import iconFontWoff from "@ui5/webcomponents-core/dist/sap/ui/core/themes/base/fonts/SAP-icons.woff"; | ||
import iconFontWoff2 from "@ui5/webcomponents-core/dist/sap/ui/core/themes/base/fonts/SAP-icons.woff2"; | ||
/** | ||
* this file extracts the logic of the insertFontFaceStyle from "@ui5/webcomponents-core/dist/sap/ui/core/IconPool" | ||
* but adapted to use the ES6 asset import mechanism to avoid too many magic modifications in the original IconPool | ||
*/ | ||
/** | ||
* CSS font family used for the icons provided by SAP. | ||
*/ | ||
const SAP_ICON_FONT_FAMILY = 'SAP-icons'; | ||
const SAP_ICON_FONT_FAMILY = "SAP-icons"; | ||
class IconFonts { | ||
static load () { | ||
const fontFace = SAP_ICON_FONT_FAMILY; | ||
const woff2Location = iconFontWoff2; | ||
const woffLocation = iconFontWoff; | ||
const ttfLocation = iconFontTTF; | ||
/* CDN Location */ | ||
let iconFontWoff = "https://ui5.sap.com/sdk/resources/sap/ui/core/themes/base/fonts/SAP-icons.woff?ui5-webcomponents"; | ||
let iconFontWoff2 = "https://ui5.sap.com/sdk/resources/sap/ui/core/themes/base/fonts/SAP-icons.woff2?ui5-webcomponents"; | ||
// load the font asynchronously via CSS | ||
const fontFaceCSS = "@font-face {" + | ||
"font-family: '" + fontFace + "';" + | ||
"src: url('" + woff2Location + "') format('woff2')," + /* Chrome 36+, Firefox 39+, Safari 10+, Edge 14+, Chrome 51+ for Android, PhantomJS 2.1.1+ */ | ||
"url('" + woffLocation + "') format('woff')," + /* IE9+, Safari 5.1+, iOS 5.1+, Android Browser 4.4+, IE Mobile 11+ */ | ||
"url('" + ttfLocation + "') format('truetype')," + /* Fallback for any older browser (except IE8 and below which are not supported anyway) */ | ||
"local('" + fontFace + "');" + /* fallback to local installed font in case it can't be loaded (e.g. font download is disabled due to browser security settings) */ | ||
"font-weight: normal;" + | ||
"font-style: normal;" + | ||
const setIconFontsLocations = ({ woff = iconFontWoff, woff2 = iconFontWoff2 } = {}) => { | ||
iconFontWoff = woff; | ||
iconFontWoff2 = woff2; | ||
}; | ||
const insertIconFontFace = (woff2Location = iconFontWoff2, woffLocation = iconFontWoff) => { | ||
const fontFace = SAP_ICON_FONT_FAMILY; | ||
/* eslint-disable */ | ||
// load the font asynchronously via CSS | ||
const fontFaceCSS = "@font-face {" + | ||
"font-family: '" + fontFace + "';" + | ||
"src: url('" + woff2Location + "') format('woff2')," + /* Chrome 36+, Firefox 39+, Safari 10+, Edge 14+, Chrome 51+ for Android, PhantomJS 2.1.1+ */ | ||
"url('" + woffLocation + "') format('woff')," + /* IE9+, Safari 5.1+, iOS 5.1+, Android Browser 4.4+, IE Mobile 11+ */ | ||
"local('" + fontFace + "');" + /* fallback to local installed font in case it can't be loaded (e.g. font download is disabled due to browser security settings) */ | ||
"font-weight: normal;" + | ||
"font-style: normal;" + | ||
"}"; | ||
/* eslint-enable */ | ||
const style = document.createElement("style"); | ||
style.type = "text/css"; | ||
style.textContent = fontFaceCSS; | ||
document.head.appendChild(style); | ||
} | ||
} | ||
const style = document.createElement("style"); | ||
style.type = "text/css"; | ||
style.textContent = fontFaceCSS; | ||
document.head.appendChild(style); | ||
}; | ||
export default IconFonts; | ||
export { insertIconFontFace, setIconFontsLocations }; |
@@ -1,9 +0,6 @@ | ||
import ControlRenderer from "./ControlRenderer"; | ||
const getElementToLabel = id => /* ControlRenderer.byId(id) || */ document.getElementById(id); | ||
const getElementToLabel = (id) => /*ControlRenderer.byId(id) ||*/ document.getElementById(id); | ||
class LabelEnablement { | ||
static labelElement(labelFor) { | ||
let elementToLabel = getElementToLabel(labelFor); | ||
const elementToLabel = getElementToLabel(labelFor); | ||
@@ -16,3 +13,3 @@ if (elementToLabel) { | ||
static getLabelableElementId(labelFor) { | ||
let elementToLabel = getElementToLabel(labelFor); | ||
const elementToLabel = getElementToLabel(labelFor); | ||
@@ -28,2 +25,2 @@ if (elementToLabel) { | ||
export default LabelEnablement; | ||
export default LabelEnablement; |
@@ -6,3 +6,3 @@ import { PropertyPart, AttributePart, directive } from "lit-html"; | ||
*/ | ||
export default directive((value) => (part) => { | ||
export default directive(value => part => { | ||
if (!value && part instanceof AttributePart && !(part instanceof PropertyPart)) { | ||
@@ -13,6 +13,5 @@ if (value !== part.value) { | ||
} | ||
} else { | ||
part.setValue(value); | ||
} | ||
else { | ||
part.setValue(value); | ||
} | ||
}); | ||
}); |
@@ -1,5 +0,4 @@ | ||
import { render } from 'lit-html' | ||
import { render } from "lit-html"; | ||
class LitRenderer { | ||
static render(renderResult, domNode) { | ||
@@ -10,2 +9,5 @@ render(renderResult, domNode); | ||
export default LitRenderer; | ||
export { html, svg } from "lit-html"; | ||
export { repeat } from "lit-html/directives/repeat"; | ||
export default LitRenderer; |
class RenderQueue { | ||
constructor() { | ||
@@ -14,3 +13,3 @@ this.list = []; // Used to store the controls in order | ||
let deferredResolve; | ||
const promise = new Promise(resolve => { | ||
const promise = new Promise(resolve => { | ||
deferredResolve = resolve; | ||
@@ -31,3 +30,3 @@ }); | ||
this.promises.delete(control); | ||
return {control, promise}; | ||
return { control, promise }; | ||
} | ||
@@ -34,0 +33,0 @@ } |
@@ -1,4 +0,2 @@ | ||
/* globals performance */ | ||
import RenderQueue from "./RenderQueue"; | ||
import ControlRenderer from "./ControlRenderer"; | ||
@@ -11,5 +9,7 @@ const MAX_RERENDER_COUNT = 10; | ||
// Queue for invalidated controls | ||
let invalidatedControls = new RenderQueue(); | ||
const invalidatedControls = new RenderQueue(); | ||
let renderTaskPromise, renderTaskPromiseResolve, taskResult; | ||
let renderTaskPromise, | ||
renderTaskPromiseResolve, | ||
taskResult; | ||
@@ -21,3 +21,2 @@ /** | ||
class RenderScheduler { | ||
constructor() { | ||
@@ -55,3 +54,3 @@ throw new Error("Static class"); | ||
// renderTaskId = window.setTimeout(RenderScheduler.renderControls, 3000); // Task | ||
//renderTaskId = Promise.resolve().then(RenderScheduler.renderControls); // Micro task | ||
// renderTaskId = Promise.resolve().then(RenderScheduler.renderControls); // Micro task | ||
renderTaskId = window.requestAnimationFrame(RenderScheduler.renderControls); // AF | ||
@@ -70,7 +69,8 @@ } | ||
// console.log("------------- NEW RENDER TASK ---------------"); | ||
ControlRenderer.storeFocus(); | ||
let controlInfo, control, promise; | ||
let controlInfo, | ||
control, | ||
promise; | ||
const renderStats = new Map(); | ||
while (controlInfo = invalidatedControls.shift()) { | ||
while (controlInfo = invalidatedControls.shift()) { // eslint-disable-line | ||
control = controlInfo.control; | ||
@@ -82,3 +82,3 @@ promise = controlInfo.promise; | ||
// console.warn("WARNING RERENDER", control); | ||
throw new Error("Control re-rendered too many times this task, max allowed is: " + MAX_RERENDER_COUNT); | ||
throw new Error(`Control re-rendered too many times this task, max allowed is: ${MAX_RERENDER_COUNT}`); | ||
} | ||
@@ -91,3 +91,3 @@ control._render(); | ||
// wait for Mutation observer just in case | ||
setTimeout(_ => { | ||
setTimeout(() => { | ||
if (invalidatedControls.getList().length === 0) { | ||
@@ -99,4 +99,2 @@ RenderScheduler._resolveTaskPromise(); | ||
renderTaskId = undefined; | ||
ControlRenderer.restoreFocus(); | ||
} | ||
@@ -114,3 +112,3 @@ | ||
renderTaskPromiseResolve = resolve; | ||
window.requestAnimationFrame(_ => { | ||
window.requestAnimationFrame(() => { | ||
if (invalidatedControls.getList().length === 0) { | ||
@@ -131,5 +129,5 @@ renderTaskPromise = undefined; | ||
// TODO: track promises internally, the dom traversal is a POC only | ||
const ui5Components = Array.from(document.querySelectorAll('*')).filter(_ => _._shadowRootReadyPromise); | ||
const ui5Components = Array.from(document.querySelectorAll("*")).filter(_ => _._shadowRootReadyPromise); | ||
return Promise.all(ui5Components.map(comp => comp._whenShadowRootReady())) | ||
.then(_ => Promise.resolve()); // qunit has a boolean cheack for the promise value and the array from the Promise all is considered truthy | ||
.then(() => Promise.resolve()); // qunit has a boolean cheack for the promise value and the array from the Promise all is considered truthy | ||
} | ||
@@ -136,0 +134,0 @@ |
@@ -1,5 +0,5 @@ | ||
import ResourceBundle from "@ui5/webcomponents-core/dist/sap/base/i18n/ResourceBundle" | ||
import configuration from "./Configuration"; | ||
import ResourceBundle from "@ui5/webcomponents-core/dist/sap/base/i18n/ResourceBundle"; | ||
import { getLanguage } from "./Configuration"; | ||
import { registerModuleContent } from "./ResourceLoaderOverrides"; | ||
import { fetchTextOnce } from "./util/FetchHelper"; | ||
import { fetchJsonOnce } from "./util/FetchHelper"; | ||
@@ -16,3 +16,3 @@ const bundleURLs = new Map(); | ||
*/ | ||
const _getSingletonPromise = (key) => { | ||
const _getSingletonPromise = key => { | ||
const prevPromise = singletonPromises.get(key); | ||
@@ -24,3 +24,3 @@ if (prevPromise) { | ||
let resolveFn; | ||
const newPromise = new Promise ((resolve) => { | ||
const newPromise = new Promise(resolve => { | ||
resolveFn = resolve; | ||
@@ -33,3 +33,3 @@ }); | ||
return newPromise; | ||
} | ||
}; | ||
@@ -45,3 +45,3 @@ /** | ||
*/ | ||
const fetchResourceBundle = async (packageId) => { | ||
const fetchResourceBundle = async packageId => { | ||
// depending on the module resolution order, the fetch might run before the bundle URLs are registered - sync them here | ||
@@ -51,7 +51,7 @@ await _getSingletonPromise(packageId); | ||
const language = configuration.getLanguage(); | ||
const language = getLanguage(); | ||
let localeId = ResourceBundle.__normalize(language); | ||
while (!bundlesForPackage[localeId]) { | ||
localeId = ResourceBundle.__nextFallbackLocale(localeId) | ||
localeId = ResourceBundle.__nextFallbackLocale(localeId); | ||
} | ||
@@ -61,6 +61,12 @@ | ||
const data = await fetchTextOnce(bundleURL); | ||
registerModuleContent(`${packageId}_${localeId}.properties`, data); | ||
} | ||
if (typeof bundleURL === "object") { | ||
// inlined from build | ||
registerModuleContent(`${packageId}_${localeId}.properties`, bundleURL._); | ||
return bundleURL; | ||
} | ||
const data = await fetchJsonOnce(bundleURL); | ||
registerModuleContent(`${packageId}_${localeId}.properties`, data._); | ||
}; | ||
/** | ||
@@ -74,13 +80,11 @@ * Registers a map of locale/url information to be used by the <code>fetchResourceBundle</code> method. | ||
bundleURLs.set(packageId, bundlesMap); | ||
_getSingletonPromise(packageId)._deferredResolve();; | ||
} | ||
_getSingletonPromise(packageId)._deferredResolve(); | ||
}; | ||
const getResourceBundle = (library) => { | ||
const locale = configuration.getLocale(); | ||
const getResourceBundle = library => { | ||
return ResourceBundle.create({ | ||
url: `${library}.properties`, | ||
}); | ||
} | ||
}; | ||
export { fetchResourceBundle, registerMessageBundles, getResourceBundle }; | ||
export { fetchResourceBundle, registerMessageBundles, getResourceBundle }; |
@@ -0,1 +1,3 @@ | ||
/* global sap */ | ||
const resources = new Map(); | ||
@@ -15,3 +17,4 @@ | ||
return customContent; | ||
} else if (getModulecontentOrig) { | ||
} | ||
if (getModulecontentOrig) { | ||
return getModulecontentOrig(moduleName, url); | ||
@@ -27,2 +30,2 @@ } | ||
export { registerModuleContent } | ||
export { registerModuleContent }; // eslint-disable-line |
@@ -1,2 +0,2 @@ | ||
import Function from './types/Function'; | ||
import Function from "./types/Function"; | ||
@@ -18,20 +18,20 @@ class State { | ||
Object.defineProperty(proto, "_id", { | ||
get: function () { | ||
get() { | ||
return this._data._id; | ||
}, | ||
set: function () { | ||
set() { | ||
throw new Error("_id should not be set by the control developer"); | ||
} | ||
}, | ||
}); | ||
for (const [prop, propData] of Object.entries(controlProperties)) { | ||
for (const [prop, propData] of Object.entries(controlProperties)) { // eslint-disable-line | ||
Object.defineProperty(proto, prop, { | ||
get: function () { | ||
if (typeof this._data[prop] !== 'undefined') { | ||
get() { | ||
if (typeof this._data[prop] !== "undefined") { | ||
return this._data[prop]; | ||
} | ||
if (propData.type === 'boolean') { | ||
if (propData.type === "boolean") { | ||
return false; | ||
} else if (propData.multiple) { | ||
} else if (propData.multiple) { // eslint-disable-line | ||
return []; | ||
@@ -42,3 +42,3 @@ } else { | ||
}, | ||
set: function (value) { | ||
set(value) { | ||
let isDifferent = false; | ||
@@ -63,3 +63,3 @@ value = MetadataClass.constructor.validatePropertyValue(value, propData); | ||
} | ||
} | ||
}, | ||
}); | ||
@@ -69,6 +69,6 @@ } | ||
const slots = MetadataClass.getSlots(); | ||
for (const [slot, slotData] of Object.entries(slots)) { | ||
for (const [slot, slotData] of Object.entries(slots)) { // eslint-disable-line | ||
Object.defineProperty(proto, slot, { | ||
get: function () { | ||
if (typeof this._data[slot] !== 'undefined') { | ||
get() { | ||
if (typeof this._data[slot] !== "undefined") { | ||
return this._data[slot]; | ||
@@ -81,3 +81,3 @@ } | ||
}, | ||
set: function (value) { | ||
set(value) { | ||
value = MetadataClass.constructor.validateSlotValue(value, slotData); | ||
@@ -95,3 +95,3 @@ if (this._data[slot] === value) { | ||
if (el && el._attachChildPropertyUpdated) { | ||
this._control._detachChildPropertyUpdated(el) | ||
this._control._detachChildPropertyUpdated(el); | ||
} | ||
@@ -112,3 +112,3 @@ }); | ||
if (el && el._attachChildPropertyUpdated) { | ||
this._control._attachChildPropertyUpdated(el, slotData) | ||
this._control._attachChildPropertyUpdated(el, slotData); | ||
} | ||
@@ -123,3 +123,3 @@ }); | ||
} | ||
} | ||
}, | ||
}); | ||
@@ -129,9 +129,9 @@ } | ||
Object.defineProperty(proto, "_nodeText", { | ||
get: function () { | ||
return this._data["_nodeText"]; | ||
get() { | ||
return this._data._nodeText; | ||
}, | ||
set: function (value) { | ||
this._data["_nodeText"] = value; | ||
set(value) { | ||
this._data._nodeText = value; | ||
this._control._invalidate("_nodeText", value); | ||
} | ||
}, | ||
}); | ||
@@ -141,8 +141,7 @@ } | ||
static generateDefaultState(MetadataClass) { | ||
const defaultState = {}; | ||
let defaultState = {}; | ||
// Initialize properties | ||
let props = MetadataClass.getProperties(); | ||
for (const propName in props) { | ||
const props = MetadataClass.getProperties(); | ||
for (const propName in props) { // eslint-disable-line | ||
if (props[propName].type === "boolean") { | ||
@@ -160,4 +159,4 @@ defaultState[propName] = false; | ||
// Initialize slots | ||
let slots = MetadataClass.getSlots(); | ||
for (const slotName in slots) { | ||
const slots = MetadataClass.getSlots(); | ||
for (const slotName in slots) { // eslint-disable-line | ||
if (slots[slotName].multiple) { | ||
@@ -164,0 +163,0 @@ defaultState[slotName] = []; |
const _convertClasses = (classes, customStyleClasses) => { | ||
for (let i in classes) { | ||
let customStyleClassesToAdd = i === "main" ? customStyleClasses : undefined; | ||
for (const i in classes) { // eslint-disable-line | ||
const customStyleClassesToAdd = i === "main" ? customStyleClasses : undefined; | ||
classes[i] = _convertSingleClass(classes[i], customStyleClassesToAdd); | ||
@@ -13,3 +13,3 @@ } | ||
if (Array.isArray(customStyleClasses)) { | ||
customStyleClasses.forEach(function (sClassName) { | ||
customStyleClasses.forEach(sClassName => { | ||
oClass[sClassName] = true; | ||
@@ -19,3 +19,3 @@ }); | ||
return Object.keys(oClass).filter(function (className) { | ||
return Object.keys(oClass).filter(className => { | ||
return oClass[className]; | ||
@@ -25,4 +25,3 @@ }).join(" "); | ||
const _convertStyles = function (styles) { | ||
const _convertStyles = function _convertStyles(styles) { | ||
if (!styles) { | ||
@@ -32,9 +31,9 @@ return; | ||
for (let i in styles) { | ||
let stylesNs = styles[i]; | ||
for (const i in styles) { // eslint-disable-line | ||
const stylesNs = styles[i]; | ||
let result = []; | ||
Object.keys(stylesNs).forEach(function (key) { | ||
const result = []; | ||
Object.keys(stylesNs).forEach(key => { | ||
if (stylesNs[key]) { | ||
result.push(key + ": " + stylesNs[key]); | ||
result.push(`${key}: ${stylesNs[key]}`); | ||
} | ||
@@ -49,8 +48,7 @@ }); | ||
class TemplateContext { | ||
// calculate control template context | ||
static calculate (control) { | ||
static calculate(control) { | ||
const templateContextMethod = control.constructor.calculateTemplateContext; | ||
const templateContext = templateContextMethod(control._state); | ||
if (!templateContext.hasOwnProperty('ariaHidden')) { | ||
if (!templateContext.hasOwnProperty("ariaHidden")) { // eslint-disable-line | ||
templateContext.ariaHidden = control._state.hidden ? "true" : undefined; | ||
@@ -64,5 +62,4 @@ } | ||
} | ||
} | ||
export default TemplateContext; | ||
export default TemplateContext; |
@@ -5,3 +5,3 @@ import DataType from "./DataType"; | ||
static isValid(value) { | ||
return /^(auto|inherit|[-+]?(0*|([0-9]+|[0-9]*\.[0-9]+)([rR][eE][mM]|[eE][mM]|[eE][xX]|[pP][xX]|[cC][mM]|[mM][mM]|[iI][nN]|[pP][tT]|[pP][cC]|%))|calc\(\s*(\(\s*)*[-+]?(([0-9]+|[0-9]*\.[0-9]+)([rR][eE][mM]|[eE][mM]|[eE][xX]|[pP][xX]|[cC][mM]|[mM][mM]|[iI][nN]|[pP][tT]|[pP][cC]|%)?)(\s*(\)\s*)*(\s[-+]\s|[*\/])\s*(\(\s*)*([-+]?(([0-9]+|[0-9]*\.[0-9]+)([rR][eE][mM]|[eE][mM]|[eE][xX]|[pP][xX]|[cC][mM]|[mM][mM]|[iI][nN]|[pP][tT]|[pP][cC]|%)?)))*\s*(\)\s*)*\))$/.test(value); | ||
return /^(auto|inherit|[-+]?(0*|([0-9]+|[0-9]*\.[0-9]+)([rR][eE][mM]|[eE][mM]|[eE][xX]|[pP][xX]|[cC][mM]|[mM][mM]|[iI][nN]|[pP][tT]|[pP][cC]|%))|calc\(\s*(\(\s*)*[-+]?(([0-9]+|[0-9]*\.[0-9]+)([rR][eE][mM]|[eE][mM]|[eE][xX]|[pP][xX]|[cC][mM]|[mM][mM]|[iI][nN]|[pP][tT]|[pP][cC]|%)?)(\s*(\)\s*)*(\s[-+]\s|[*\/])\s*(\(\s*)*([-+]?(([0-9]+|[0-9]*\.[0-9]+)([rR][eE][mM]|[eE][mM]|[eE][xX]|[pP][xX]|[cC][mM]|[mM][mM]|[iI][nN]|[pP][tT]|[pP][cC]|%)?)))*\s*(\)\s*)*\))$/.test(value); // eslint-disable-line | ||
} | ||
@@ -8,0 +8,0 @@ } |
/** | ||
* Base class for all data types. | ||
* | ||
* | ||
* @class | ||
@@ -11,3 +11,2 @@ * @constructor | ||
class DataType { | ||
static isValid(value) { | ||
@@ -19,5 +18,5 @@ } | ||
Object.defineProperty(this, type, { | ||
get: function () { | ||
get() { | ||
return types[type]; | ||
} | ||
}, | ||
}); | ||
@@ -24,0 +23,0 @@ }); |
@@ -26,7 +26,6 @@ import DataType from "./DataType"; | ||
*/ | ||
CLOSING: "CLOSING" | ||
CLOSING: "CLOSING", | ||
}; | ||
class PopupState extends DataType { | ||
static isValid(value) { | ||
@@ -33,0 +32,0 @@ return !!PopupStates[value]; |
import DataType from "./DataType"; | ||
class URI extends DataType { | ||
static isValid(value) { | ||
// TODO: recheck | ||
return /^((([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)$/.test(value); | ||
return /^((([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)$/.test(value); // eslint-disable-line | ||
} | ||
} | ||
export default URI; | ||
export default URI; |
@@ -10,3 +10,3 @@ import DataType from "./DataType"; | ||
Warning: "Warning", | ||
Error: "Error" | ||
Error: "Error", | ||
}; | ||
@@ -13,0 +13,0 @@ |
@@ -5,28 +5,28 @@ const fetchPromises = new Map(); | ||
const fetchTextOnce = async (url) => { | ||
if (!fetchPromises.get(url)) { | ||
fetchPromises.set(url, fetch(url)); | ||
} | ||
const response = await fetchPromises.get(url); | ||
const fetchTextOnce = async url => { | ||
if (!fetchPromises.get(url)) { | ||
fetchPromises.set(url, fetch(url)); | ||
} | ||
const response = await fetchPromises.get(url); | ||
if (!textPromises.get(url)) { | ||
textPromises.set(url, response.text()); | ||
} | ||
if (!textPromises.get(url)) { | ||
textPromises.set(url, response.text()); | ||
} | ||
return textPromises.get(url); | ||
} | ||
return textPromises.get(url); | ||
}; | ||
const fetchJsonOnce = async (url) => { | ||
if (!fetchPromises.get(url)) { | ||
fetchPromises.set(url, fetch(url)); | ||
} | ||
const response = await fetchPromises.get(url); | ||
const fetchJsonOnce = async url => { | ||
if (!fetchPromises.get(url)) { | ||
fetchPromises.set(url, fetch(url)); | ||
} | ||
const response = await fetchPromises.get(url); | ||
if (!jsonPromises.get(url)) { | ||
jsonPromises.set(url, response.json()); | ||
} | ||
if (!jsonPromises.get(url)) { | ||
jsonPromises.set(url, response.json()); | ||
} | ||
return jsonPromises.get(url); | ||
} | ||
return jsonPromises.get(url); | ||
}; | ||
export { fetchTextOnce, fetchJsonOnce } | ||
export { fetchTextOnce, fetchJsonOnce }; |
import Device from "@ui5/webcomponents-core/dist/sap/ui/Device"; | ||
const setupBrowser = () => { | ||
var html = document.documentElement; | ||
const setupBrowser = node => { | ||
const b = Device.browser; | ||
let id = b.name; | ||
var b = Device.browser; | ||
var id = b.name; | ||
if (id) { | ||
if (id === b.BROWSER.SAFARI && b.mobile) { | ||
id = "m" + id; | ||
id = `m${id}`; | ||
} | ||
id = id + (b.version === -1 ? "" : Math.floor(b.version)); | ||
html.dataset.sapUiBrowser = id; | ||
id += (b.version === -1 ? "" : Math.floor(b.version)); | ||
node.dataset.sapUiBrowser = id; | ||
} | ||
}; | ||
export default setupBrowser; | ||
export default setupBrowser; |
import Device from "@ui5/webcomponents-core/dist/sap/ui/Device"; | ||
const setupOS = () => { | ||
var html = document.documentElement; | ||
const setupOS = node => { | ||
node.dataset.sapUiOs = Device.os.name + Device.os.versionStr; | ||
html.dataset.sapUiOs = Device.os.name + Device.os.versionStr; | ||
var osCSS = null; | ||
let osCSS = null; | ||
switch (Device.os.name) { | ||
case Device.os.OS.IOS: | ||
osCSS = "sap-ios"; | ||
break; | ||
case Device.os.OS.ANDROID: | ||
osCSS = "sap-android"; | ||
break; | ||
case Device.os.OS.BLACKBERRY: | ||
osCSS = "sap-bb"; | ||
break; | ||
case Device.os.OS.WINDOWS_PHONE: | ||
osCSS = "sap-winphone"; | ||
break; | ||
case Device.os.OS.IOS: | ||
osCSS = "sap-ios"; | ||
break; | ||
case Device.os.OS.ANDROID: | ||
osCSS = "sap-android"; | ||
break; | ||
case Device.os.OS.BLACKBERRY: | ||
osCSS = "sap-bb"; | ||
break; | ||
case Device.os.OS.WINDOWS_PHONE: | ||
osCSS = "sap-winphone"; | ||
break; | ||
} | ||
if (osCSS) { | ||
html.classList.add(osCSS); | ||
node.classList.add(osCSS); | ||
} | ||
}; | ||
export default setupOS; | ||
export default setupOS; |
@@ -1,7 +0,7 @@ | ||
const whenDOMReady = _ => { | ||
return new Promise(function (resolve, reject) { | ||
const whenDOMReady = () => { | ||
return new Promise(resolve => { | ||
if (document.body) { | ||
resolve(); | ||
} else { | ||
document.addEventListener("DOMContentLoaded", function () { | ||
document.addEventListener("DOMContentLoaded", () => { | ||
resolve(); | ||
@@ -13,2 +13,2 @@ }); | ||
export default whenDOMReady; | ||
export default whenDOMReady; |
@@ -1,11 +0,11 @@ | ||
import configuration from './Configuration'; | ||
import DOMObserver from './compatibility/DOMObserver'; | ||
import ShadowDOM from './compatibility/ShadowDOM'; | ||
import WebComponentMetadata from './WebComponentMetadata'; | ||
import Integer from './types/Integer'; | ||
import { getWCNoConflict } from "./Configuration"; | ||
import DOMObserver from "./compatibility/DOMObserver"; | ||
import ShadowDOM from "./compatibility/ShadowDOM"; | ||
import WebComponentMetadata from "./WebComponentMetadata"; | ||
import Integer from "./types/Integer"; | ||
import ControlRenderer from "./ControlRenderer"; | ||
import RenderScheduler from "./RenderScheduler"; | ||
import TemplateContext from "./TemplateContext"; | ||
import { attachThemeChange } from "./Theming"; | ||
import State from "./State"; | ||
import Core from "./Core"; | ||
@@ -19,3 +19,3 @@ const metadata = { | ||
type: String, | ||
multiple: true | ||
multiple: true, | ||
}, | ||
@@ -28,8 +28,8 @@ | ||
_customAttributes: { | ||
type: Object | ||
} | ||
type: Object, | ||
}, | ||
}, | ||
events: { | ||
_propertyChange: {} | ||
} | ||
_propertyChange: {}, | ||
}, | ||
}; | ||
@@ -58,3 +58,3 @@ | ||
if (!window.ShadyDOM && !this.constructor.getMetadata().getNoShadowDOM()) { | ||
Core.attachThemeChange(this._onThemeChange.bind(this)); | ||
attachThemeChange(this._onThemeChange.bind(this)); | ||
} | ||
@@ -71,7 +71,2 @@ } | ||
// For duck typing when instanceof WebComponent cannot be used | ||
isUI5WebComponent() { | ||
return true; | ||
} | ||
_whenShadowRootReady() { | ||
@@ -90,4 +85,4 @@ return this._shadowRootReadyPromise; | ||
this.attachShadow({ mode: 'open' }); | ||
return new Promise((resolve, reject) => { | ||
this.attachShadow({ mode: "open" }); | ||
return new Promise(resolve => { | ||
ShadowDOM.prepareShadowDOM(this.constructor).then(shadowDOM => { | ||
@@ -105,8 +100,8 @@ this.shadowRoot.appendChild(shadowDOM); | ||
this._whenShadowRootReady().then(_ => { | ||
this._whenShadowRootReady().then(() => { | ||
this._processChildren(); | ||
RenderScheduler.renderImmediately(this).then(_ => { | ||
RenderScheduler.renderImmediately(this).then(() => { | ||
this._domRefReadyPromise._deferredResolve(); | ||
this._startObservingDOMChildren(); | ||
if (typeof this.onEnterDOM === 'function') { | ||
if (typeof this.onEnterDOM === "function") { | ||
this.onEnterDOM(); | ||
@@ -124,6 +119,7 @@ } | ||
this._stopObservingDOMChildren(); | ||
if (typeof this.onExitDOM === 'function') { | ||
if (typeof this.onExitDOM === "function") { | ||
this.onExitDOM(); | ||
} | ||
} | ||
_startObservingDOMChildren() { | ||
@@ -135,14 +131,17 @@ const shouldObserveChildren = this.constructor.getMetadata().hasSlots(); | ||
} | ||
let mutationObserverOptions = { | ||
const mutationObserverOptions = { | ||
childList: true, | ||
subtree: shouldObserveText, | ||
characterData: shouldObserveText | ||
characterData: shouldObserveText, | ||
}; | ||
DOMObserver.observeDOMNode(this, this._processChildren.bind(this), mutationObserverOptions); | ||
} | ||
_stopObservingDOMChildren() { | ||
DOMObserver.unobserveDOMNode(this); | ||
} | ||
onChildrenChanged(mutations) { | ||
} | ||
_processChildren(mutations) { | ||
@@ -158,5 +157,7 @@ const usesNodeText = this.constructor.getMetadata().usesNodeText(); | ||
} | ||
_updateNodeText() { | ||
this._state._nodeText = this.textContent; | ||
} | ||
_updateSlots() { | ||
@@ -166,3 +167,3 @@ const domChildren = Array.from(this.children); | ||
const slotsMap = this.constructor.getMetadata().getSlots(); | ||
for (let [prop, propData] of Object.entries(slotsMap)) { | ||
for (const [prop, propData] of Object.entries(slotsMap)) { // eslint-disable-line | ||
if (propData.multiple) { | ||
@@ -176,4 +177,6 @@ this._state[prop] = []; | ||
domChildren.forEach(child => { | ||
const slot = child.getAttribute('data-ui5-slot') || this.constructor.getMetadata().getDefaultSlot(); | ||
if (slotsMap[slot] === 'undefined') { | ||
const slot = child.getAttribute("data-ui5-slot") || this.constructor.getMetadata().getDefaultSlot(); | ||
if (slotsMap[slot] === undefined) { | ||
const validValues = Object.keys(slotsMap).join(", "); | ||
console.warn(`Unknown data-ui5-slot value: ${slot}, ignoring`, child, `Valid data-ui5-slot values are: ${validValues}`); // eslint-disable-line | ||
return; | ||
@@ -184,3 +187,3 @@ } | ||
const nextId = (autoIncrementMap.get(slot) || 0) + 1; | ||
slotName = slot + '-' + nextId; | ||
slotName = `${slot}-${nextId}`; | ||
autoIncrementMap.set(slot, nextId); | ||
@@ -196,3 +199,3 @@ } else { | ||
} | ||
child.setAttribute('slot', slotName); | ||
child.setAttribute("slot", slotName); | ||
}); | ||
@@ -203,10 +206,10 @@ } | ||
const observedProps = this.getMetadata().getObservedProps(); | ||
const observedAttributes = observedProps.map(camelToKebabCase); | ||
return observedAttributes; | ||
return observedProps.map(camelToKebabCase); | ||
} | ||
attributeChangedCallback(name, oldValue, newValue) { | ||
const properties = this.constructor.getMetadata().getProperties(); | ||
const realName = name.replace(/^ui5-/, ''); | ||
const realName = name.replace(/^ui5-/, ""); | ||
const nameInCamelCase = kebabToCamelCase(realName); | ||
if (properties.hasOwnProperty(nameInCamelCase)) { | ||
if (properties.hasOwnProperty(nameInCamelCase)) { // eslint-disable-line | ||
const propertyTypeClass = properties[nameInCamelCase].type; | ||
@@ -217,3 +220,3 @@ if (propertyTypeClass === Boolean) { | ||
if (propertyTypeClass === Integer) { | ||
newValue = parseInt(newValue, 10); | ||
newValue = parseInt(newValue); | ||
} | ||
@@ -223,2 +226,3 @@ this[nameInCamelCase] = newValue; | ||
} | ||
_updateAttribute(name, newValue) { | ||
@@ -229,3 +233,3 @@ if (!WebComponentMetadata.isPublicProperty(name)) { | ||
if (typeof newValue === 'object') { | ||
if (typeof newValue === "object") { | ||
return; | ||
@@ -236,16 +240,15 @@ } | ||
const attrValue = this.getAttribute(attrName); | ||
if (typeof newValue === 'boolean') { | ||
if (typeof newValue === "boolean") { | ||
if (newValue === true && attrValue === null) { | ||
this.setAttribute(attrName, ''); | ||
this.setAttribute(attrName, ""); | ||
} else if (newValue === false && attrValue !== null) { | ||
this.removeAttribute(attrName); | ||
} | ||
} else { | ||
if (attrValue !== newValue) { | ||
this.setAttribute(attrName, newValue); | ||
} | ||
} else if (attrValue !== newValue) { | ||
this.setAttribute(attrName, newValue); | ||
} | ||
} | ||
_upgradeProperty(prop) { | ||
if (this.hasOwnProperty(prop)) { | ||
if (this.hasOwnProperty(prop)) { // eslint-disable-line | ||
const value = this[prop]; | ||
@@ -256,2 +259,3 @@ delete this[prop]; | ||
} | ||
_upgradeAllProperties() { | ||
@@ -272,8 +276,2 @@ const observedProps = this.constructor.getMetadata().getObservedProps(); | ||
} | ||
static getMetadata() { | ||
if (!this._metadata) { | ||
this._metadata = new WebComponentMetadata(this.metadata); | ||
} | ||
return this._metadata; | ||
} | ||
@@ -293,3 +291,3 @@ static get metadata() { | ||
static get StateClass() { | ||
if (!this.hasOwnProperty("_StateClass")) { | ||
if (!this.hasOwnProperty("_StateClass")) { // eslint-disable-line | ||
this._StateClass = class extends State {}; | ||
@@ -303,10 +301,9 @@ this._StateClass.generateAccessors(this.getMetadata()); | ||
static getMetadata() { | ||
let klass = this; // eslint-disable-line | ||
let klass = this; | ||
if (klass.hasOwnProperty("_metadata")) { | ||
if (klass.hasOwnProperty("_metadata")) { // eslint-disable-line | ||
return klass._metadata; | ||
} | ||
let metadatas = [Object.assign(klass.metadata, {})]; | ||
const metadatas = [Object.assign(klass.metadata, {})]; | ||
while (klass !== WebComponent) { | ||
@@ -320,3 +317,3 @@ klass = Object.getPrototypeOf(klass); | ||
// merge properties | ||
const mergedProperties = metadatas.reverse().reduce((result, current) => { | ||
result.properties = metadatas.reverse().reduce((result, current) => { // eslint-disable-line | ||
Object.assign(result, current.properties); | ||
@@ -326,6 +323,4 @@ return result; | ||
result.properties = mergedProperties; | ||
// merge slots | ||
const mergedSlots = metadatas.reverse().reduce((result, current) => { | ||
result.slots = metadatas.reverse().reduce((result, current) => { // eslint-disable-line | ||
Object.assign(result, current.slots); | ||
@@ -335,6 +330,4 @@ return result; | ||
result.slots = mergedSlots; | ||
// merge events | ||
const mergedEvents = metadatas.reverse().reduce((result, current) => { | ||
result.events = metadatas.reverse().reduce((result, current) => { // eslint-disable-line | ||
Object.assign(result, current.events); | ||
@@ -344,4 +337,2 @@ return result; | ||
result.events = mergedEvents; | ||
this._metadata = new WebComponentMetadata(result); | ||
@@ -353,3 +344,3 @@ return this._metadata; | ||
return { | ||
ctr: state | ||
ctr: state, | ||
}; | ||
@@ -394,4 +385,9 @@ } | ||
const { observedProps, notObservedProps } = this.parentNode._monitoredChildProps.get(prop.target.getAttribute("data-ui5-slot")); | ||
const propsMetadata = this.parentNode._monitoredChildProps.get(this.getAttribute("data-ui5-slot")); | ||
if (!propsMetadata) { | ||
return; | ||
} | ||
const { observedProps, notObservedProps } = propsMetadata; | ||
if (observedProps.includes(prop.detail.name) && !notObservedProps.includes(prop.detail.name)) { | ||
@@ -418,3 +414,3 @@ this.parentNode._invalidate("_parent_", this); | ||
_render(debugMsg) { | ||
_render() { | ||
// onBeforeRendering | ||
@@ -436,3 +432,2 @@ if (typeof this.onBeforeRendering === "function") { | ||
} | ||
} | ||
@@ -449,3 +444,3 @@ | ||
return this._getPlaceholder().children[0]; | ||
return this._getRoot().children[0]; | ||
} | ||
@@ -457,10 +452,10 @@ | ||
_getPlaceholder() { | ||
return this.shadowRoot.querySelector("[data-sap-ui-wc-placeholder]"); | ||
_getRoot() { | ||
return this.shadowRoot.querySelector("[data-sap-ui-wc-root]"); | ||
} | ||
getFocusDomRef() { | ||
let domRef = this.getDomRef(); | ||
const domRef = this.getDomRef(); | ||
if (domRef) { | ||
let focusRef = domRef.querySelector("[data-sap-focus-ref]"); | ||
const focusRef = domRef.querySelector("[data-sap-focus-ref]"); | ||
return focusRef || domRef; | ||
@@ -470,4 +465,7 @@ } | ||
focus() { | ||
let focusDomRef = this.getFocusDomRef(); | ||
async focus() { | ||
await this._waitForDomRef(); | ||
const focusDomRef = this.getFocusDomRef(); | ||
if (focusDomRef) { | ||
@@ -479,10 +477,9 @@ focusDomRef.focus(); | ||
/** | ||
* Calls the event handler on the control for a native event or a pseudo event | ||
* Calls the event handler on the control for a native event | ||
* | ||
* @param event The event object | ||
* @param pseudoEventType For pseudo events, use this type to construct the name of the handler | ||
* @private | ||
*/ | ||
_handleEvent(event, pseudoEventType) { | ||
const sHandlerName = "on" + (pseudoEventType || event.type); | ||
_handleEvent(event) { | ||
const sHandlerName = `on${event.type}`; | ||
@@ -503,6 +500,6 @@ this._delegates.forEach(delegate => { | ||
let customEvent = new CustomEvent("_propertyChange", { | ||
detail: { name: name, newValue: value }, | ||
const customEvent = new CustomEvent("_propertyChange", { | ||
detail: { name, newValue: value }, | ||
composed: false, | ||
bubbles: true | ||
bubbles: true, | ||
}); | ||
@@ -527,3 +524,3 @@ | ||
bubbles: true, | ||
cancelable: cancelable | ||
cancelable, | ||
}); | ||
@@ -535,7 +532,7 @@ | ||
if (WebComponent.noConflictEvents.includes(name)) { | ||
customEvent = new CustomEvent("ui5-" + name, { | ||
customEvent = new CustomEvent(`ui5-${name}`, { | ||
detail: data, | ||
composed: false, | ||
bubbles: true, | ||
cancelable: cancelable | ||
cancelable, | ||
}); | ||
@@ -557,3 +554,3 @@ | ||
let nodes = el.assignedNodes(); | ||
const nodes = el.assignedNodes(); | ||
@@ -587,4 +584,3 @@ if (nodes.length) { | ||
const properties = this.getMetadata().getProperties(); | ||
for (const [prop, propData] of Object.entries(properties)) { | ||
for (const [prop, propData] of Object.entries(properties)) { // eslint-disable-line | ||
if (nameCollidesWithNative(prop)) { | ||
@@ -599,8 +595,8 @@ throw new Error(`"${prop}" is not a valid property name. Use a name that does not collide with DOM APIs`); | ||
Object.defineProperty(proto, prop, { | ||
get: function () { | ||
get() { | ||
return this._state[prop]; | ||
}, | ||
set: function (value) { | ||
set(value) { | ||
this._state[prop] = value; | ||
} | ||
}, | ||
}); | ||
@@ -611,15 +607,14 @@ } | ||
const slots = this.getMetadata().getSlots(); | ||
for (const [slot, slotData] of Object.entries(slots)) { | ||
for (const [slot] of Object.entries(slots)) { // eslint-disable-line | ||
if (nameCollidesWithNative(slot)) { | ||
throw new Error(`"${prop}" is not a valid property name. Use a name that does not collide with DOM APIs`); | ||
throw new Error(`"${slot}" is not a valid property name. Use a name that does not collide with DOM APIs`); | ||
} | ||
Object.defineProperty(proto, slot, { | ||
get: function () { | ||
get() { | ||
return this._state[slot]; | ||
}, | ||
set: function (value) { | ||
set() { | ||
throw new Error("Cannot set slots directly, use the DOM APIs"); | ||
} | ||
}, | ||
}); | ||
@@ -630,8 +625,8 @@ } | ||
Object.defineProperty(proto, "_nodeText", { | ||
get: function () { | ||
get() { | ||
return this._state._nodeText; | ||
}, | ||
set: function (value) { | ||
set() { | ||
throw new Error("Cannot set node text directly, use the DOM APIs"); | ||
} | ||
}, | ||
}); | ||
@@ -642,3 +637,3 @@ } | ||
if (!this._noConflictEvents) { | ||
const noConflictConfig = configuration.getWCNoConflict(); | ||
const noConflictConfig = getWCNoConflict(); | ||
this._noConflictEvents = []; | ||
@@ -653,11 +648,11 @@ if (typeof noConflictConfig === "object" && typeof noConflictConfig.events === "string") { | ||
} | ||
const kebabToCamelCase = string => toCamelCase(string.split('-')); | ||
const camelToKebabCase = string => string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); | ||
const kebabToCamelCase = string => toCamelCase(string.split("-")); | ||
const camelToKebabCase = string => string.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); | ||
const toCamelCase = parts => { | ||
return parts.map((string, index) => { | ||
return index === 0 ? string.toLowerCase() : string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); | ||
}).join(''); | ||
}).join(""); | ||
}; | ||
const nameCollidesWithNative = name => { | ||
if (name === 'disabled') { | ||
if (name === "disabled") { | ||
return false; | ||
@@ -668,7 +663,7 @@ } | ||
Element, | ||
Node | ||
Node, | ||
]; | ||
return classes.some(klass => klass.prototype.hasOwnProperty(name)); | ||
return classes.some(klass => klass.prototype.hasOwnProperty(name)); // eslint-disable-line | ||
}; | ||
export default WebComponent; |
@@ -1,3 +0,3 @@ | ||
import DataType from './types/DataType'; | ||
import Function from './types/Function'; | ||
import DataType from "./types/DataType"; | ||
import Function from "./types/Function"; | ||
@@ -8,17 +8,23 @@ class WebComponentMetadata { | ||
} | ||
getTag() { | ||
return this.metadata.tag; | ||
} | ||
getNoShadowDOM() { | ||
return this.metadata.noShadowDOM; | ||
} | ||
getStyleUrl() { | ||
return this.metadata.styleUrl || []; | ||
} | ||
usesNodeText() { | ||
return !!this.metadata.usesNodeText; | ||
} | ||
getDefaultSlot() { | ||
return this.metadata.defaultSlot || 'content'; | ||
return this.metadata.defaultSlot || "content"; | ||
} | ||
getObservedProps() { | ||
@@ -30,11 +36,15 @@ const properties = this.getProperties(); | ||
} | ||
getSlots() { | ||
return this.metadata.slots || {}; | ||
} | ||
hasSlots() { | ||
return !!Object.entries(this.getSlots()).length; | ||
} | ||
getProperties() { | ||
return this.metadata.properties || {}; | ||
} | ||
getEvents() { | ||
@@ -45,3 +55,3 @@ return this.metadata.events || {}; | ||
static isPublicProperty(prop) { | ||
return prop.charAt(0) !== '_'; | ||
return prop.charAt(0) !== "_"; | ||
} | ||
@@ -56,2 +66,3 @@ | ||
} | ||
static validateSlotValue(value, slotData) { | ||
@@ -64,3 +75,2 @@ const isMultiple = slotData.multiple; | ||
} | ||
} | ||
@@ -100,3 +110,3 @@ | ||
if (value !== null && !(getSlottedElement(value) instanceof propertyType)) { | ||
throw new Error(`${ value } is not of type ${ propertyType }`); | ||
throw new Error(`${value} is not of type ${propertyType}`); | ||
} | ||
@@ -108,3 +118,3 @@ | ||
const isDescendantOf = (klass, baseKlass, inclusive = false) => { | ||
if (typeof klass !== 'function' || typeof baseKlass !== 'function') { | ||
if (typeof klass !== "function" || typeof baseKlass !== "function") { | ||
return false; | ||
@@ -122,2 +132,2 @@ } | ||
export default WebComponentMetadata; | ||
export default WebComponentMetadata; |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
528218
90
6496
5
2
3
+ Addedlit-html@^1.0.0
+ Addedregenerator-runtime@0.12.1
+ Added@ui5/webcomponents-core@0.8.0(transitive)
+ Addedlit-html@1.4.1(transitive)
+ Addedregenerator-runtime@0.12.1(transitive)
+ Addedurl-search-params-polyfill@5.1.0(transitive)
- Removed@ui5/webcomponents-core@0.7.0(transitive)