Rearrange kotlin-stdlib-js library sources

Move kotlin.* api inside kotlin directory.
Update copyright paths.
This commit is contained in:
Ilya Gorbunov
2018-01-31 06:40:35 +03:00
committed by Stanislav Erokhin
parent 57e47d1830
commit 00b23a0fe9
114 changed files with 31 additions and 25 deletions
+16 -9
View File
@@ -17,9 +17,9 @@ def commonSrcDir = "${buildDir}/common-sources"
def commonTestSrcDir = "${buildDir}/common-test-sources"
def builtinsDir = "${rootDir}/core/builtins"
def experimentalSrcDir = "${rootDir}/libraries/stdlib/experimental"
def jsLibrariesDir = "${rootDir}/js/js.libraries"
def jsSrcDir = "${jsLibrariesDir}/src"
def jsTestSrcDir = "${jsLibrariesDir}/test"
def jsSrcGeneratedDir = "${rootDir}/js/js.libraries/src/core/generated" // to be removed soon
def jsSrcDir = "src"
def jsTestSrcDir = "test"
def jsSrcJsDir = "${jsSrcDir}/js"
def jsOutputFile = "${buildDir}/classes/kotlin.js"
@@ -34,7 +34,7 @@ sourceSets {
builtins {
kotlin {
srcDir builtinsSrcDir2
srcDir "${jsSrcDir}/builtins"
srcDir 'runtime'
}
}
@@ -42,7 +42,7 @@ sourceSets {
kotlin {
srcDir builtinsSrcDir
srcDir jsSrcDir
exclude "builtins"
srcDir jsSrcGeneratedDir
srcDir commonSrcDir
}
}
@@ -143,7 +143,7 @@ compileKotlin2Js {
outputFile = "${buildDir}/classes/main/kotlin.js"
sourceMap = true
sourceMapPrefix = "./"
freeCompilerArgs += [ "-source-map-base-dirs", [builtinsSrcDir, jsSrcDir, commonSrcDir ].join(File.pathSeparator) ]
freeCompilerArgs += [ "-source-map-base-dirs", [builtinsSrcDir, jsSrcDir, commonSrcDir].collect { file(it).absoluteFile }.join(File.pathSeparator) ]
}
}
@@ -212,17 +212,20 @@ task compileJs(type: JavaExec) {
def sourceMapBasePaths = [
"./",
"/js.libraries/src/js/"
"libraries/stdlib/js/src/js/",
"libraries/stdlib/js/src/",
]
sourceMap.sources = sourceMap.sources.collect { sourcePath ->
def prefixToRemove = sourceMapBasePaths.find { basePath -> sourcePath.startsWith(basePath) }
if (prefixToRemove != null) sourcePath.substring(prefixToRemove.length()) else sourcePath
}
def sourceMapSourcesBaseDirs = [ jsSrcDir, builtinsSrcDir2, builtinsSrcDir, commonSrcDir, rootDir ]
def sourceMapSourcesBaseDirs = [jsSrcDir, jsSrcJsDir, jsSrcGeneratedDir, builtinsSrcDir, commonSrcDir, projectDir]
sourceMap.sourcesContent = sourceMap.sources.collect { sourceName ->
sourceMapSourcesBaseDirs.collect { file("$it/$sourceName") }.find { it.exists() && it.name != "kotlin.js" }?.text
def text = sourceMapSourcesBaseDirs.collect { file("$it/$sourceName") }.find { it.exists() }?.text
if (text == null) logger.warn("Sources missing for file $sourceName")
text
}
sourceMapFile.text = groovy.json.JsonOutput.toJson(sourceMap)
@@ -263,8 +266,12 @@ task sourcesJar(type: Jar, dependsOn: classes) {
from (sourceSets.main.allSource) {
into 'kotlin'
exclude '**/*.java'
exclude 'org.w3c/**'
exclude 'js/**'
}
from (sourceSets.main.allSource) {
include 'org.w3c/**'
}
from (sourceSets.experimental.allSource) {
into 'kotlin'
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,229 @@
namespace org.w3c.dom.css;
/* written by CSS3 spec */
partial interface CSSStyleDeclaration {
attribute String alignContent;
attribute String alignItems;
attribute String alignSelf;
attribute String animation;
attribute String animationDelay;
attribute String animationDirection;
attribute String animationDuration;
attribute String animationFillMode;
attribute String animationIterationCount;
attribute String animationName;
attribute String animationPlayState;
attribute String animationTimingFunction;
attribute String backfaceVisibility;
attribute String background;
attribute String backgroundAttachment;
attribute String backgroundClip;
attribute String backgroundColor;
attribute String backgroundImage;
attribute String backgroundOrigin;
attribute String backgroundPosition;
attribute String backgroundRepeat;
attribute String backgroundSize;
attribute String border;
attribute String borderBottom;
attribute String borderBottomColor;
attribute String borderBottomLeftRadius;
attribute String borderBottomRightRadius;
attribute String borderBottomStyle;
attribute String borderBottomWidth;
attribute String borderCollapse;
attribute String borderColor;
attribute String borderImage;
attribute String borderImageOutset;
attribute String borderImageRepeat;
attribute String borderImageSlice;
attribute String borderImageSource;
attribute String borderImageWidth;
attribute String borderLeft;
attribute String borderLeftColor;
attribute String borderLeftStyle;
attribute String borderLeftWidth;
attribute String borderRadius;
attribute String borderRight;
attribute String borderRightColor;
attribute String borderRightStyle;
attribute String borderRightWidth;
attribute String borderSpacing;
attribute String borderStyle;
attribute String borderTop;
attribute String borderTopColor;
attribute String borderTopLeftRadius;
attribute String borderTopRightRadius;
attribute String borderTopStyle;
attribute String borderTopWidth;
attribute String borderWidth;
attribute String bottom;
attribute String boxDecorationBreak;
attribute String boxShadow;
attribute String boxSizing;
attribute String breakAfter;
attribute String breakBefore;
attribute String breakInside;
attribute String captionSide;
attribute String clear;
attribute String clip;
attribute String color;
attribute String columnCount;
attribute String columnFill;
attribute String columnGap;
attribute String columnRule;
attribute String columnRuleColor;
attribute String columnRuleStyle;
attribute String columnRuleWidth;
attribute String columnSpan;
attribute String columnWidth;
attribute String columns;
attribute String content;
attribute String counterIncrement;
attribute String counterReset;
attribute String cursor;
attribute String direction;
attribute String display;
attribute String emptyCells;
attribute String filter;
attribute String flex;
attribute String flexBasis;
attribute String flexDirection;
attribute String flexFlow;
attribute String flexGrow;
attribute String flexShrink;
attribute String flexWrap;
attribute String cssFloat;
attribute String font;
attribute String fontFamily;
attribute String fontFeatureSettings;
attribute String fontKerning;
attribute String fontLanguageOverride;
attribute String fontSize;
attribute String fontSizeAdjust;
attribute String fontStretch;
attribute String fontStyle;
attribute String fontSynthesis;
attribute String fontVariant;
attribute String fontVariantAlternates;
attribute String fontVariantCaps;
attribute String fontVariantEastAsian;
attribute String fontVariantLigatures;
attribute String fontVariantNumeric;
attribute String fontVariantPosition;
attribute String fontWeight;
attribute String hangingPunctuation;
attribute String height;
attribute String hyphens;
attribute String imageOrientation;
attribute String imageRendering;
attribute String imageResolution;
attribute String imeMode;
attribute String justifyContent;
attribute String left;
attribute String letterSpacing;
attribute String lineBreak;
attribute String lineHeight;
attribute String listStyle;
attribute String listStyleImage;
attribute String listStylePosition;
attribute String listStyleType;
attribute String margin;
attribute String marginBottom;
attribute String marginLeft;
attribute String marginRight;
attribute String marginTop;
attribute String mark;
attribute String markAfter;
attribute String markBefore;
attribute String marks;
attribute String marqueeDirection;
attribute String marqueePlayCount;
attribute String marqueeSpeed;
attribute String marqueeStyle;
attribute String mask;
attribute String maskType;
attribute String maxHeight;
attribute String maxWidth;
attribute String minHeight;
attribute String minWidth;
attribute String navDown;
attribute String navIndex;
attribute String navLeft;
attribute String navRight;
attribute String navUp;
attribute String objectFit;
attribute String objectPosition;
attribute String opacity;
attribute String order;
attribute String orphans;
attribute String outline;
attribute String outlineColor;
attribute String outlineOffset;
attribute String outlineStyle;
attribute String outlineWidth;
attribute String overflowWrap;
attribute String overflowX;
attribute String overflowY;
attribute String padding;
attribute String paddingBottom;
attribute String paddingLeft;
attribute String paddingRight;
attribute String paddingTop;
attribute String pageBreakAfter;
attribute String pageBreakBefore;
attribute String pageBreakInside;
attribute String perspective;
attribute String perspectiveOrigin;
attribute String phonemes;
attribute String position;
attribute String quotes;
attribute String resize;
attribute String rest;
attribute String restAfter;
attribute String restBefore;
attribute String right;
attribute String tabSize;
attribute String tableLayout;
attribute String textAlign;
attribute String textAlignLast;
attribute String textCombineUpright;
attribute String textDecoration;
attribute String textDecorationColor;
attribute String textDecorationLine;
attribute String textDecorationStyle;
attribute String textIndent;
attribute String textJustify;
attribute String textOrientation;
attribute String textOverflow;
attribute String textShadow;
attribute String textTransform;
attribute String textUnderlinePosition;
attribute String top;
attribute String transform;
attribute String transformOrigin;
attribute String transformStyle;
attribute String transition;
attribute String transitionDelay;
attribute String transitionDuration;
attribute String transitionProperty;
attribute String transitionTimingFunction;
attribute String unicodeBidi;
attribute String verticalAlign;
attribute String visibility;
attribute String voiceBalance;
attribute String voiceDuration;
attribute String voicePitch;
attribute String voicePitchRange;
attribute String voiceRate;
attribute String voiceStress;
attribute String voiceVolume;
attribute String whiteSpace;
attribute String widows;
attribute String width;
attribute String wordBreak;
attribute String wordSpacing;
attribute String wordWrap;
attribute String writingMode;
attribute String zIndex;
};
+258
View File
@@ -0,0 +1,258 @@
namespace org.w3c.dom.css;
// Downloaded from https://drafts.csswg.org/cssom/
[ArrayClass]
interface MediaList {
[TreatNullAs=EmptyString] stringifier attribute DOMString mediaText;
readonly attribute unsigned long length;
getter DOMString? item(unsigned long index);
void appendMedium(DOMString medium);
void deleteMedium(DOMString medium);
};
interface StyleSheet {
readonly attribute DOMString type;
readonly attribute DOMString? href;
readonly attribute (Element or ProcessingInstruction)? ownerNode;
readonly attribute StyleSheet? parentStyleSheet;
readonly attribute DOMString? title;
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
attribute boolean disabled;
};
interface CSSStyleSheet : StyleSheet {
readonly attribute CSSRule? ownerRule;
[SameObject] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(DOMString rule, unsigned long index);
void deleteRule(unsigned long index);
};
[ArrayClass]
interface StyleSheetList {
getter StyleSheet? item(unsigned long index);
readonly attribute unsigned long length;
};
partial interface Document {
[SameObject] readonly attribute StyleSheetList styleSheets;
};
[NoInterfaceObject]
interface LinkStyle {
readonly attribute StyleSheet? sheet;
};
ProcessingInstruction implements LinkStyle;
[ArrayClass]
interface CSSRuleList {
getter CSSRule? item(unsigned long index);
readonly attribute unsigned long length;
};
interface CSSRule {
const unsigned short STYLE_RULE = 1;
const unsigned short CHARSET_RULE = 2; // historical
const unsigned short IMPORT_RULE = 3;
const unsigned short MEDIA_RULE = 4;
const unsigned short FONT_FACE_RULE = 5;
const unsigned short PAGE_RULE = 6;
const unsigned short MARGIN_RULE = 9;
const unsigned short NAMESPACE_RULE = 10;
readonly attribute unsigned short type;
attribute DOMString cssText;
readonly attribute CSSRule? parentRule;
readonly attribute CSSStyleSheet? parentStyleSheet;
};
interface CSSStyleRule : CSSRule {
attribute DOMString selectorText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
interface CSSImportRule : CSSRule {
readonly attribute DOMString href;
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
[SameObject] readonly attribute CSSStyleSheet styleSheet;
};
interface CSSGroupingRule : CSSRule {
[SameObject] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(DOMString rule, unsigned long index);
void deleteRule(unsigned long index);
};
interface CSSMediaRule : CSSGroupingRule {
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
};
interface CSSPageRule : CSSGroupingRule {
attribute DOMString selectorText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
interface CSSMarginRule : CSSRule {
readonly attribute DOMString name;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
interface CSSNamespaceRule : CSSRule {
readonly attribute DOMString namespaceURI;
readonly attribute DOMString prefix;
};
interface CSSStyleDeclaration {
[CEReactions] attribute DOMString cssText;
readonly attribute unsigned long length;
getter DOMString item(unsigned long index);
DOMString getPropertyValue(DOMString property);
DOMString getPropertyPriority(DOMString property);
[CEReactions] void setProperty(DOMString property, [TreatNullAs=EmptyString] DOMString value, [TreatNullAs=EmptyString] optional DOMString priority = "");
[CEReactions] void setPropertyValue(DOMString property, [TreatNullAs=EmptyString] DOMString value);
[CEReactions] void setPropertyPriority(DOMString property, [TreatNullAs=EmptyString] DOMString priority);
[CEReactions] DOMString removeProperty(DOMString property);
readonly attribute CSSRule? parentRule;
[CEReactions, TreatNullAs=EmptyString] attribute DOMString cssFloat;
};
partial interface CSSStyleDeclaration {
[CEReactions, TreatNullAs=EmptyString] attribute DOMString _dashed_attribute;
};
[NoInterfaceObject]
interface ElementCSSInlineStyle {
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
HTMLElement implements ElementCSSInlineStyle;
SVGElement implements ElementCSSInlineStyle;
partial interface Window {
[NewObject] CSSStyleDeclaration getComputedStyle(Element elt, optional DOMString? pseudoElt);
};
interface CSS {
static DOMString escape(DOMString ident);
};
[ArrayClass]
interface MediaList {
[TreatNullAs=EmptyString] stringifier attribute DOMString mediaText;
readonly attribute unsigned long length;
getter DOMString? item(unsigned long index);
void appendMedium(DOMString medium);
void deleteMedium(DOMString medium);
};
interface StyleSheet {
readonly attribute DOMString type;
readonly attribute DOMString? href;
readonly attribute (Element or ProcessingInstruction)? ownerNode;
readonly attribute StyleSheet? parentStyleSheet;
readonly attribute DOMString? title;
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
attribute boolean disabled;
};
interface CSSStyleSheet : StyleSheet {
readonly attribute CSSRule? ownerRule;
[SameObject] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(DOMString rule, unsigned long index);
void deleteRule(unsigned long index);
};
[ArrayClass]
interface StyleSheetList {
getter StyleSheet? item(unsigned long index);
readonly attribute unsigned long length;
};
partial interface Document {
[SameObject] readonly attribute StyleSheetList styleSheets;
};
[NoInterfaceObject]
interface LinkStyle {
readonly attribute StyleSheet? sheet;
};
ProcessingInstruction implements LinkStyle;
[ArrayClass]
interface CSSRuleList {
getter CSSRule? item(unsigned long index);
readonly attribute unsigned long length;
};
interface CSSRule {
const unsigned short STYLE_RULE = 1;
const unsigned short CHARSET_RULE = 2; // historical
const unsigned short IMPORT_RULE = 3;
const unsigned short MEDIA_RULE = 4;
const unsigned short FONT_FACE_RULE = 5;
const unsigned short PAGE_RULE = 6;
const unsigned short MARGIN_RULE = 9;
const unsigned short NAMESPACE_RULE = 10;
readonly attribute unsigned short type;
attribute DOMString cssText;
readonly attribute CSSRule? parentRule;
readonly attribute CSSStyleSheet? parentStyleSheet;
};
interface CSSStyleRule : CSSRule {
attribute DOMString selectorText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
interface CSSImportRule : CSSRule {
readonly attribute DOMString href;
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
[SameObject] readonly attribute CSSStyleSheet styleSheet;
};
interface CSSGroupingRule : CSSRule {
[SameObject] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(DOMString rule, unsigned long index);
void deleteRule(unsigned long index);
};
interface CSSMediaRule : CSSGroupingRule {
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
};
interface CSSPageRule : CSSGroupingRule {
attribute DOMString selectorText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
interface CSSMarginRule : CSSRule {
readonly attribute DOMString name;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
interface CSSNamespaceRule : CSSRule {
readonly attribute DOMString namespaceURI;
readonly attribute DOMString prefix;
};
interface CSSStyleDeclaration {
[CEReactions] attribute DOMString cssText;
readonly attribute unsigned long length;
getter DOMString item(unsigned long index);
DOMString getPropertyValue(DOMString property);
DOMString getPropertyPriority(DOMString property);
[CEReactions] void setProperty(DOMString property, [TreatNullAs=EmptyString] DOMString value, [TreatNullAs=EmptyString] optional DOMString priority = "");
[CEReactions] void setPropertyValue(DOMString property, [TreatNullAs=EmptyString] DOMString value);
[CEReactions] void setPropertyPriority(DOMString property, [TreatNullAs=EmptyString] DOMString priority);
[CEReactions] DOMString removeProperty(DOMString property);
readonly attribute CSSRule? parentRule;
[CEReactions, TreatNullAs=EmptyString] attribute DOMString cssFloat;
};
partial interface CSSStyleDeclaration {
[CEReactions, TreatNullAs=EmptyString] attribute DOMString _camel_cased_attribute;
};
partial interface CSSStyleDeclaration {
[CEReactions, TreatNullAs=EmptyString] attribute DOMString _webkit_cased_attribute;
};
partial interface CSSStyleDeclaration {
[CEReactions, TreatNullAs=EmptyString] attribute DOMString _dashed_attribute;
};
[NoInterfaceObject]
interface ElementCSSInlineStyle {
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
HTMLElement implements ElementCSSInlineStyle;
SVGElement implements ElementCSSInlineStyle;
partial interface Window {
[NewObject] CSSStyleDeclaration getComputedStyle(Element elt, optional DOMString? pseudoElt);
};
interface CSS {
static DOMString escape(DOMString ident);
};
@@ -0,0 +1,282 @@
namespace org.w3c.dom.events;
// Downloaded from http://www.w3.org/TR/uievents/
[Constructor(DOMString type, optional UIEventInit eventInitDict)]
interface UIEvent : Event {
readonly attribute Window? view;
readonly attribute long detail;
};
dictionary UIEventInit : EventInit {
Window? view = null;
long detail = 0;
};
[Constructor(DOMString type, optional FocusEventInit eventInitDict)]
interface FocusEvent : UIEvent {
readonly attribute EventTarget? relatedTarget;
};
dictionary FocusEventInit : UIEventInit {
EventTarget? relatedTarget = null;
};
[Constructor(DOMString type, optional MouseEventInit eventInitDict)]
interface MouseEvent : UIEvent {
readonly attribute long screenX;
readonly attribute long screenY;
readonly attribute long clientX;
readonly attribute long clientY;
readonly attribute boolean ctrlKey;
readonly attribute boolean shiftKey;
readonly attribute boolean altKey;
readonly attribute boolean metaKey;
readonly attribute short button;
readonly attribute unsigned short buttons;
readonly attribute EventTarget? relatedTarget;
boolean getModifierState(DOMString keyArg);
};
dictionary MouseEventInit : EventModifierInit {
long screenX = 0;
long screenY = 0;
long clientX = 0;
long clientY = 0;
short button = 0;
unsigned short buttons = 0;
EventTarget? relatedTarget = null;
};
dictionary EventModifierInit : UIEventInit {
boolean ctrlKey = false;
boolean shiftKey = false;
boolean altKey = false;
boolean metaKey = false;
boolean modifierAltGraph = false;
boolean modifierCapsLock = false;
boolean modifierFn = false;
boolean modifierFnLock = false;
boolean modifierHyper = false;
boolean modifierNumLock = false;
boolean modifierScrollLock = false;
boolean modifierSuper = false;
boolean modifierSymbol = false;
boolean modifierSymbolLock = false;
};
[Constructor(DOMString type, optional WheelEventInit eventInitDict)]
interface WheelEvent : MouseEvent {
// DeltaModeCode
const unsigned long DOM_DELTA_PIXEL = 0x00;
const unsigned long DOM_DELTA_LINE = 0x01;
const unsigned long DOM_DELTA_PAGE = 0x02;
readonly attribute double deltaX;
readonly attribute double deltaY;
readonly attribute double deltaZ;
readonly attribute unsigned long deltaMode;
};
dictionary WheelEventInit : MouseEventInit {
double deltaX = 0.0;
double deltaY = 0.0;
double deltaZ = 0.0;
unsigned long deltaMode = 0;
};
[Constructor(DOMString type, optional InputEventInit eventInitDict)]
interface InputEvent : UIEvent {
readonly attribute DOMString data;
readonly attribute boolean isComposing;
};
dictionary InputEventInit : UIEventInit {
DOMString data = "";
boolean isComposing = false;
};
[Constructor(DOMString type, optional KeyboardEventInit eventInitDict)]
interface KeyboardEvent : UIEvent {
// KeyLocationCode
const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
const unsigned long DOM_KEY_LOCATION_LEFT = 0x01;
const unsigned long DOM_KEY_LOCATION_RIGHT = 0x02;
const unsigned long DOM_KEY_LOCATION_NUMPAD = 0x03;
readonly attribute DOMString key;
readonly attribute DOMString code;
readonly attribute unsigned long location;
readonly attribute boolean ctrlKey;
readonly attribute boolean shiftKey;
readonly attribute boolean altKey;
readonly attribute boolean metaKey;
readonly attribute boolean repeat;
readonly attribute boolean isComposing;
boolean getModifierState(DOMString keyArg);
};
dictionary KeyboardEventInit : EventModifierInit {
DOMString key = "";
DOMString code = "";
unsigned long location = 0;
boolean repeat = false;
boolean isComposing = false;
};
[Constructor(DOMString type, optional CompositionEventInit eventInitDict)]
interface CompositionEvent : UIEvent {
readonly attribute DOMString data;
};
dictionary CompositionEventInit : UIEventInit {
DOMString data = "";
};
partial interface KeyboardEvent {
// The following support legacy user agents
readonly attribute unsigned long charCode;
readonly attribute unsigned long keyCode;
readonly attribute unsigned long which;
};
[Constructor(DOMString type, optional UIEventInit eventInitDict)]
interface UIEvent : Event {
readonly attribute Window? view;
readonly attribute long detail;
};
dictionary UIEventInit : EventInit {
Window? view = null;
long detail = 0;
};
[Constructor(DOMString type, optional FocusEventInit eventInitDict)]
interface FocusEvent : UIEvent {
readonly attribute EventTarget? relatedTarget;
};
dictionary FocusEventInit : UIEventInit {
EventTarget? relatedTarget = null;
};
[Constructor(DOMString type, optional MouseEventInit eventInitDict)]
interface MouseEvent : UIEvent {
readonly attribute long screenX;
readonly attribute long screenY;
readonly attribute long clientX;
readonly attribute long clientY;
readonly attribute boolean ctrlKey;
readonly attribute boolean shiftKey;
readonly attribute boolean altKey;
readonly attribute boolean metaKey;
readonly attribute short button;
readonly attribute unsigned short buttons;
readonly attribute EventTarget? relatedTarget;
boolean getModifierState(DOMString keyArg);
};
dictionary MouseEventInit : EventModifierInit {
long screenX = 0;
long screenY = 0;
long clientX = 0;
long clientY = 0;
short button = 0;
unsigned short buttons = 0;
EventTarget? relatedTarget = null;
};
dictionary EventModifierInit : UIEventInit {
boolean ctrlKey = false;
boolean shiftKey = false;
boolean altKey = false;
boolean metaKey = false;
boolean modifierAltGraph = false;
boolean modifierCapsLock = false;
boolean modifierFn = false;
boolean modifierFnLock = false;
boolean modifierHyper = false;
boolean modifierNumLock = false;
boolean modifierScrollLock = false;
boolean modifierSuper = false;
boolean modifierSymbol = false;
boolean modifierSymbolLock = false;
};
[Constructor(DOMString type, optional WheelEventInit eventInitDict)]
interface WheelEvent : MouseEvent {
// DeltaModeCode
const unsigned long DOM_DELTA_PIXEL = 0x00;
const unsigned long DOM_DELTA_LINE = 0x01;
const unsigned long DOM_DELTA_PAGE = 0x02;
readonly attribute double deltaX;
readonly attribute double deltaY;
readonly attribute double deltaZ;
readonly attribute unsigned long deltaMode;
};
dictionary WheelEventInit : MouseEventInit {
double deltaX = 0.0;
double deltaY = 0.0;
double deltaZ = 0.0;
unsigned long deltaMode = 0;
};
[Constructor(DOMString type, optional InputEventInit eventInitDict)]
interface InputEvent : UIEvent {
readonly attribute DOMString data;
readonly attribute boolean isComposing;
};
dictionary InputEventInit : UIEventInit {
DOMString data = "";
boolean isComposing = false;
};
[Constructor(DOMString type, optional KeyboardEventInit eventInitDict)]
interface KeyboardEvent : UIEvent {
// KeyLocationCode
const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
const unsigned long DOM_KEY_LOCATION_LEFT = 0x01;
const unsigned long DOM_KEY_LOCATION_RIGHT = 0x02;
const unsigned long DOM_KEY_LOCATION_NUMPAD = 0x03;
readonly attribute DOMString key;
readonly attribute DOMString code;
readonly attribute unsigned long location;
readonly attribute boolean ctrlKey;
readonly attribute boolean shiftKey;
readonly attribute boolean altKey;
readonly attribute boolean metaKey;
readonly attribute boolean repeat;
readonly attribute boolean isComposing;
boolean getModifierState(DOMString keyArg);
};
dictionary KeyboardEventInit : EventModifierInit {
DOMString key = "";
DOMString code = "";
unsigned long location = 0;
boolean repeat = false;
boolean isComposing = false;
};
[Constructor(DOMString type, optional CompositionEventInit eventInitDict)]
interface CompositionEvent : UIEvent {
readonly attribute DOMString data;
};
dictionary CompositionEventInit : UIEventInit {
DOMString data = "";
};
partial interface KeyboardEvent {
// The following support legacy user agents
readonly attribute unsigned long charCode;
readonly attribute unsigned long keyCode;
readonly attribute unsigned long which;
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,21 @@
namespace org.w3c.dom.parsing;
// Downloaded from http://www.w3.org/TR/DOM-Parsing/
[Constructor]
interface DOMParser {
[NewObject] Document parseFromString (DOMString str, SupportedType type);
};
[Constructor]
interface XMLSerializer {
DOMString serializeToString (Node root);
};
partial interface Element {
[CEReactions, TreatNullAs=EmptyString] attribute DOMString innerHTML;
[CEReactions, TreatNullAs=EmptyString] attribute DOMString outerHTML;
[CEReactions] void insertAdjacentHTML (DOMString position, DOMString text);
};
partial interface Range {
[CEReactions, NewObject] DocumentFragment createContextualFragment (DOMString fragment);
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,68 @@
namespace org.w3c.dom.url;
// Downloaded from https://raw.githubusercontent.com/whatwg/url/master/url.html
[Constructor(USVString url, optional USVString base),
Exposed=(Window,Worker)]
interface URL {
static USVString domainToASCII(USVString domain);
static USVString domainToUnicode(USVString domain);
stringifier attribute USVString href;
readonly attribute USVString origin;
attribute USVString protocol;
attribute USVString username;
attribute USVString password;
attribute USVString host;
attribute USVString hostname;
attribute USVString port;
attribute USVString pathname;
attribute USVString search;
readonly attribute URLSearchParams searchParams;
attribute USVString hash;
};
[Constructor(optional (USVString or URLSearchParams) init = ""),
Exposed=(Window,Worker)]
interface URLSearchParams {
void append(USVString name, USVString value);
void delete(USVString name);
USVString? get(USVString name);
sequence<USVString> getAll(USVString name);
boolean has(USVString name);
void set(USVString name, USVString value);
iterable<USVString, USVString>;
stringifier;
};
[Constructor(USVString url, optional USVString base),
Exposed=(Window,Worker)]
interface URL {
static USVString domainToASCII(USVString domain);
static USVString domainToUnicode(USVString domain);
stringifier attribute USVString href;
readonly attribute USVString origin;
attribute USVString protocol;
attribute USVString username;
attribute USVString password;
attribute USVString host;
attribute USVString hostname;
attribute USVString port;
attribute USVString pathname;
attribute USVString search;
readonly attribute URLSearchParams searchParams;
attribute USVString hash;
};
[Constructor(optional (USVString or URLSearchParams) init = ""),
Exposed=(Window,Worker)]
interface URLSearchParams {
void append(USVString name, USVString value);
void delete(USVString name);
USVString? get(USVString name);
sequence<USVString> getAll(USVString name);
boolean has(USVString name);
void set(USVString name, USVString value);
iterable<USVString, USVString>;
stringifier;
};
+104
View File
@@ -0,0 +1,104 @@
namespace org.w3c.fetch;
// Downloaded from https://raw.githubusercontent.com/whatwg/fetch/master/Overview.src.html
typedef (Headers or sequence<sequence<ByteString>> or OpenEndedDictionary<ByteString>) HeadersInit;
[Constructor(optional HeadersInit init),
Exposed=(Window,Worker)]
interface Headers {
void append(ByteString name, ByteString value);
void delete(ByteString name);
ByteString? get(ByteString name);
boolean has(ByteString name);
void set(ByteString name, ByteString value);
iterable<ByteString, ByteString>;
};
typedef (Blob or BufferSource or FormData or URLSearchParams or USVString) BodyInit;
typedef (BodyInit or ReadableStream) ResponseBodyInit;
[NoInterfaceObject,
Exposed=(Window,Worker)]
interface Body {
readonly attribute boolean bodyUsed;
[NewObject] Promise<ArrayBuffer> arrayBuffer();
[NewObject] Promise<Blob> blob();
[NewObject] Promise<FormData> formData();
[NewObject] Promise<any> json();
[NewObject] Promise<USVString> text();
};
typedef (Request or USVString) RequestInfo;
[Constructor(RequestInfo input, optional RequestInit init),
Exposed=(Window,Worker)]
interface Request {
readonly attribute ByteString method;
readonly attribute USVString url;
[SameObject] readonly attribute Headers headers;
readonly attribute RequestType type;
readonly attribute RequestDestination destination;
readonly attribute USVString referrer;
readonly attribute ReferrerPolicy referrerPolicy;
readonly attribute RequestMode mode;
readonly attribute RequestCredentials credentials;
readonly attribute RequestCache cache;
readonly attribute RequestRedirect redirect;
readonly attribute DOMString integrity;
readonly attribute boolean keepalive;
[NewObject] Request clone();
};
Request implements Body;
dictionary RequestInit {
ByteString method;
HeadersInit headers;
BodyInit? body;
USVString referrer;
ReferrerPolicy referrerPolicy;
RequestMode mode;
RequestCredentials credentials;
RequestCache cache;
RequestRedirect redirect;
DOMString integrity;
boolean keepalive;
any window; // can only be set to null
};
enum RequestType { "", "audio", "font", "image", "script", "style", "track", "video" };
enum RequestDestination { "", "document", "embed", "font", "image", "manifest", "media", "object", "report", "script", "serviceworker", "sharedworker", "style", "worker", "xslt" };
enum RequestMode { "navigate", "same-origin", "no-cors", "cors" };
enum RequestCredentials { "omit", "same-origin", "include" };
enum RequestCache { "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached" };
enum RequestRedirect { "follow", "error", "manual" };
[Constructor(optional ResponseBodyInit? body = null, optional ResponseInit init),
Exposed=(Window,Worker)]
interface Response {
[NewObject] static Response error();
[NewObject] static Response redirect(USVString url, optional unsigned short status = 302);
readonly attribute ResponseType type;
readonly attribute USVString url;
readonly attribute boolean redirected;
readonly attribute unsigned short status;
readonly attribute boolean ok;
readonly attribute ByteString statusText;
[SameObject] readonly attribute Headers headers;
readonly attribute ReadableStream? body;
[SameObject] readonly attribute Promise<Headers> trailer;
[NewObject] Response clone();
};
Response implements Body;
dictionary ResponseInit {
unsigned short status = 200;
ByteString statusText = "OK";
HeadersInit headers;
};
enum ResponseType { "basic", "cors", "default", "error", "opaque", "opaqueredirect" };
partial interface WindowOrWorkerGlobalScope {
[NewObject] Promise<Response> fetch(RequestInfo input, optional RequestInit init);
};
+184
View File
@@ -0,0 +1,184 @@
namespace org.w3c.files;
// Downloaded from https://raw.githubusercontent.com/w3c/FileAPI/gh-pages/index.html
[Constructor(optional sequence<BlobPart> blobParts, optional BlobPropertyBag options),
Exposed=(Window,Worker)]
interface Blob {
readonly attribute unsigned long long size;
readonly attribute DOMString type;
readonly attribute boolean isClosed;
//slice Blob into byte-ranged chunks
Blob slice([Clamp] optional long long start,
[Clamp] optional long long end,
optional DOMString contentType);
void close();
};
dictionary BlobPropertyBag {
DOMString type = "";
};
typedef (BufferSource or Blob or USVString) BlobPart;
[Constructor(sequence<BlobPart> fileBits,
[EnsureUTF16] DOMString fileName,
optional FilePropertyBag options),
Exposed=(Window,Worker)]
interface File : Blob {
readonly attribute DOMString name;
readonly attribute long long lastModified;
};
dictionary FilePropertyBag : BlobPropertyBag {
long long lastModified;
};
[Exposed=(Window,Worker)]
interface FileList {
getter File? item(unsigned long index);
readonly attribute unsigned long length;
};
[Constructor, Exposed=(Window,Worker)]
interface FileReader: EventTarget {
// async read methods
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString label);
void readAsDataURL(Blob blob);
void abort();
// states
const unsigned short EMPTY = 0;
const unsigned short LOADING = 1;
const unsigned short DONE = 2;
readonly attribute unsigned short readyState;
// File or Blob data
readonly attribute (DOMString or ArrayBuffer)? result;
readonly attribute DOMError? error;
// event handler content attributes
attribute EventHandler onloadstart;
attribute EventHandler onprogress;
attribute EventHandler onload;
attribute EventHandler onabort;
attribute EventHandler onerror;
attribute EventHandler onloadend;
};
[Constructor, Exposed=Worker]
interface FileReaderSync {
// Synchronously return strings
ArrayBuffer readAsArrayBuffer(Blob blob);
DOMString readAsBinaryString(Blob blob);
DOMString readAsText(Blob blob, optional DOMString label);
DOMString readAsDataURL(Blob blob);
};
[Exposed=(Window,DedicatedWorker,SharedWorker)]
partial interface URL {
static DOMString createObjectURL(Blob blob);
static DOMString createFor(Blob blob);
static void revokeObjectURL(DOMString url);
};
[Constructor(optional sequence<BlobPart> blobParts, optional BlobPropertyBag options),
Exposed=(Window,Worker)]
interface Blob {
readonly attribute unsigned long long size;
readonly attribute DOMString type;
readonly attribute boolean isClosed;
//slice Blob into byte-ranged chunks
Blob slice([Clamp] optional long long start,
[Clamp] optional long long end,
optional DOMString contentType);
void close();
};
dictionary BlobPropertyBag {
DOMString type = "";
};
typedef (BufferSource or Blob or USVString) BlobPart;
[Constructor(sequence<BlobPart> fileBits,
[EnsureUTF16] DOMString fileName,
optional FilePropertyBag options),
Exposed=(Window,Worker)]
interface File : Blob {
readonly attribute DOMString name;
readonly attribute long long lastModified;
};
dictionary FilePropertyBag : BlobPropertyBag {
long long lastModified;
};
[Exposed=(Window,Worker)]
interface FileList {
getter File? item(unsigned long index);
readonly attribute unsigned long length;
};
[Constructor, Exposed=(Window,Worker)]
interface FileReader: EventTarget {
// async read methods
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString label);
void readAsDataURL(Blob blob);
void abort();
// states
const unsigned short EMPTY = 0;
const unsigned short LOADING = 1;
const unsigned short DONE = 2;
readonly attribute unsigned short readyState;
// File or Blob data
readonly attribute (DOMString or ArrayBuffer)? result;
readonly attribute DOMError? error;
// event handler content attributes
attribute EventHandler onloadstart;
attribute EventHandler onprogress;
attribute EventHandler onload;
attribute EventHandler onabort;
attribute EventHandler onerror;
attribute EventHandler onloadend;
};
[Constructor, Exposed=Worker]
interface FileReaderSync {
// Synchronously return strings
ArrayBuffer readAsArrayBuffer(Blob blob);
DOMString readAsBinaryString(Blob blob);
DOMString readAsText(Blob blob, optional DOMString label);
DOMString readAsDataURL(Blob blob);
};
[Exposed=(Window,DedicatedWorker,SharedWorker)]
partial interface URL {
static DOMString createObjectURL(Blob blob);
static DOMString createFor(Blob blob);
static void revokeObjectURL(DOMString url);
};
@@ -0,0 +1,22 @@
namespace org.w3c.fullscreen;
// Downloaded from https://raw.githubusercontent.com/whatwg/fullscreen/master/fullscreen.html
partial interface Element {
Promise<void> requestFullscreen();
};
partial interface Document {
[LenientSetter] readonly attribute boolean fullscreenEnabled;
[LenientSetter] readonly attribute boolean fullscreen; // historical
Promise<void> exitFullscreen();
attribute EventHandler onfullscreenchange;
attribute EventHandler onfullscreenerror;
};
partial interface DocumentOrShadowRoot {
[LenientSetter] readonly attribute Element? fullscreenElement;
};
@@ -0,0 +1,200 @@
namespace org.w3c.notifications;
// Downloaded from https://raw.githubusercontent.com/whatwg/notifications/master/notifications.html
[Constructor(DOMString title, optional NotificationOptions options),
Exposed=(Window,Worker)]
interface Notification : EventTarget {
static readonly attribute NotificationPermission permission;
[Exposed=Window] static Promise<NotificationPermission> requestPermission(optional NotificationPermissionCallback deprecatedCallback);
static readonly attribute unsigned long maxActions;
attribute EventHandler onclick;
attribute EventHandler onerror;
readonly attribute DOMString title;
readonly attribute NotificationDirection dir;
readonly attribute DOMString lang;
readonly attribute DOMString body;
readonly attribute DOMString tag;
readonly attribute USVString image;
readonly attribute USVString icon;
readonly attribute USVString badge;
readonly attribute USVString sound;
[SameObject] readonly attribute FrozenArray<unsigned long> vibrate;
readonly attribute DOMTimeStamp timestamp;
readonly attribute boolean renotify;
readonly attribute boolean silent;
readonly attribute boolean noscreen;
readonly attribute boolean requireInteraction;
readonly attribute boolean sticky;
[SameObject] readonly attribute any data;
[SameObject] readonly attribute FrozenArray<NotificationAction> actions;
void close();
};
dictionary NotificationOptions {
NotificationDirection dir = "auto";
DOMString lang = "";
DOMString body = "";
DOMString tag = "";
USVString image;
USVString icon;
USVString badge;
USVString sound;
VibratePattern vibrate;
DOMTimeStamp timestamp;
boolean renotify = false;
boolean silent = false;
boolean noscreen = false;
boolean requireInteraction = false;
boolean sticky = false;
any data = null;
sequence<NotificationAction> actions = [];
};
enum NotificationPermission {
"default",
"denied",
"granted"
};
enum NotificationDirection {
"auto",
"ltr",
"rtl"
};
dictionary NotificationAction {
required DOMString action;
required DOMString title;
USVString icon;
};
callback NotificationPermissionCallback = void (NotificationPermission permission);
dictionary GetNotificationOptions {
DOMString tag = "";
};
partial interface ServiceWorkerRegistration {
Promise<void> showNotification(DOMString title, optional NotificationOptions options);
Promise<sequence<Notification>> getNotifications(optional GetNotificationOptions filter);
};
[Constructor(DOMString type, NotificationEventInit eventInitDict),
Exposed=ServiceWorker]
interface NotificationEvent : ExtendableEvent {
readonly attribute Notification notification;
readonly attribute DOMString action;
};
dictionary NotificationEventInit : ExtendableEventInit {
required Notification notification;
DOMString action = "";
};
partial interface ServiceWorkerGlobalScope {
attribute EventHandler onnotificationclick;
attribute EventHandler onnotificationclose;
};
[Constructor(DOMString title, optional NotificationOptions options),
Exposed=(Window,Worker)]
interface Notification : EventTarget {
static readonly attribute NotificationPermission permission;
[Exposed=Window] static Promise<NotificationPermission> requestPermission(optional NotificationPermissionCallback deprecatedCallback);
static readonly attribute unsigned long maxActions;
attribute EventHandler onclick;
attribute EventHandler onerror;
readonly attribute DOMString title;
readonly attribute NotificationDirection dir;
readonly attribute DOMString lang;
readonly attribute DOMString body;
readonly attribute DOMString tag;
readonly attribute USVString image;
readonly attribute USVString icon;
readonly attribute USVString badge;
readonly attribute USVString sound;
[SameObject] readonly attribute FrozenArray<unsigned long> vibrate;
readonly attribute DOMTimeStamp timestamp;
readonly attribute boolean renotify;
readonly attribute boolean silent;
readonly attribute boolean noscreen;
readonly attribute boolean requireInteraction;
readonly attribute boolean sticky;
[SameObject] readonly attribute any data;
[SameObject] readonly attribute FrozenArray<NotificationAction> actions;
void close();
};
dictionary NotificationOptions {
NotificationDirection dir = "auto";
DOMString lang = "";
DOMString body = "";
DOMString tag = "";
USVString image;
USVString icon;
USVString badge;
USVString sound;
VibratePattern vibrate;
DOMTimeStamp timestamp;
boolean renotify = false;
boolean silent = false;
boolean noscreen = false;
boolean requireInteraction = false;
boolean sticky = false;
any data = null;
sequence<NotificationAction> actions = [];
};
enum NotificationPermission {
"default",
"denied",
"granted"
};
enum NotificationDirection {
"auto",
"ltr",
"rtl"
};
dictionary NotificationAction {
required DOMString action;
required DOMString title;
USVString icon;
};
callback NotificationPermissionCallback = void (NotificationPermission permission);
dictionary GetNotificationOptions {
DOMString tag = "";
};
partial interface ServiceWorkerRegistration {
Promise<void> showNotification(DOMString title, optional NotificationOptions options);
Promise<sequence<Notification>> getNotifications(optional GetNotificationOptions filter);
};
[Constructor(DOMString type, NotificationEventInit eventInitDict),
Exposed=ServiceWorker]
interface NotificationEvent : ExtendableEvent {
readonly attribute Notification notification;
readonly attribute DOMString action;
};
dictionary NotificationEventInit : ExtendableEventInit {
required Notification notification;
DOMString action = "";
};
partial interface ServiceWorkerGlobalScope {
attribute EventHandler onnotificationclick;
attribute EventHandler onnotificationclose;
};
@@ -0,0 +1,60 @@
namespace org.w3c.performance;
// Downloaded from http://www.w3.org/TR/hr-time/
typedef double DOMHighResTimeStamp;
[Exposed=(Window,Worker)]
interface Performance : EventTarget {
DOMHighResTimeStamp now();
serializer = {attribute};
};
[NoInterfaceObject,
Exposed=(Window,Worker)]
interface GlobalPerformance {
[Replaceable] readonly attribute Performance performance;
};
Window implements GlobalPerformance;
WorkerGlobalScope implements GlobalPerformance;
// Downloaded from http://www.w3.org/TR/2012/REC-navigation-timing-20121217/
interface PerformanceTiming {
readonly attribute unsigned long long navigationStart;
readonly attribute unsigned long long unloadEventStart;
readonly attribute unsigned long long unloadEventEnd;
readonly attribute unsigned long long redirectStart;
readonly attribute unsigned long long redirectEnd;
readonly attribute unsigned long long fetchStart;
readonly attribute unsigned long long domainLookupStart;
readonly attribute unsigned long long domainLookupEnd;
readonly attribute unsigned long long connectStart;
readonly attribute unsigned long long connectEnd;
readonly attribute unsigned long long secureConnectionStart;
readonly attribute unsigned long long requestStart;
readonly attribute unsigned long long responseStart;
readonly attribute unsigned long long responseEnd;
readonly attribute unsigned long long domLoading;
readonly attribute unsigned long long domInteractive;
readonly attribute unsigned long long domContentLoadedEventStart;
readonly attribute unsigned long long domContentLoadedEventEnd;
readonly attribute unsigned long long domComplete;
readonly attribute unsigned long long loadEventStart;
readonly attribute unsigned long long loadEventEnd;
};
interface PerformanceNavigation {
const unsigned short TYPE_NAVIGATE = 0;
const unsigned short TYPE_RELOAD = 1;
const unsigned short TYPE_BACK_FORWARD = 2;
const unsigned short TYPE_RESERVED = 255;
readonly attribute unsigned short type;
readonly attribute unsigned short redirectCount;
};
interface Performance {
readonly attribute PerformanceTiming timing;
readonly attribute PerformanceNavigation navigation;
};
partial interface Window {
[Replaceable] readonly attribute Performance performance;
};
@@ -0,0 +1,8 @@
namespace org.w3c.vibration;
// Downloaded from http://www.w3.org/TR/vibration/
typedef (unsigned long or sequence<unsigned long>) VibratePattern; partial interface Navigator {
boolean vibrate (VibratePattern pattern);
};
@@ -0,0 +1,7 @@
namespace org.w3c.webidl;
/** written by WebIDL spec */
typedef unsigned long long DOMTimeStamp;
callback Function = any (any... arguments);
callback VoidFunction = void ();
+505
View File
@@ -0,0 +1,505 @@
namespace org.w3c.workers;
// Downloaded from https://w3c.github.io/ServiceWorker/
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorker : EventTarget {
readonly attribute USVString scriptURL;
readonly attribute ServiceWorkerState state;
void postMessage(any message, optional sequence<object> transfer);
// event
attribute EventHandler onstatechange;
};
ServiceWorker implements AbstractWorker;
enum ServiceWorkerState {
"installing",
"installed",
"activating",
"activated",
"redundant"
};
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerRegistration : EventTarget {
readonly attribute ServiceWorker? installing;
readonly attribute ServiceWorker? waiting;
readonly attribute ServiceWorker? active;
readonly attribute USVString scope;
[NewObject] Promise<void> update();
[NewObject] Promise<boolean> unregister();
// event
attribute EventHandler onupdatefound;
};
partial interface Navigator {
[SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};
partial interface WorkerNavigator {
[SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerContainer : EventTarget {
readonly attribute ServiceWorker? controller;
[SameObject] readonly attribute Promise<ServiceWorkerRegistration> ready;
[NewObject] Promise<ServiceWorkerRegistration> register(USVString scriptURL, optional RegistrationOptions options);
[NewObject] Promise<any> getRegistration(optional USVString clientURL = "");
[NewObject] Promise<sequence<ServiceWorkerRegistration>> getRegistrations();
void startMessages();
// events
attribute EventHandler oncontrollerchange;
attribute EventHandler onmessage; // event.source of message events is ServiceWorker object
};
dictionary RegistrationOptions {
USVString scope;
WorkerType type = "classic";
};
[Constructor(DOMString type, optional ServiceWorkerMessageEventInit eventInitDict), Exposed=(Window,Worker)]
interface ServiceWorkerMessageEvent : Event {
readonly attribute any data;
readonly attribute DOMString origin;
readonly attribute DOMString lastEventId;
[SameObject] readonly attribute (ServiceWorker or MessagePort)? source;
readonly attribute FrozenArray<MessagePort>? ports;
};
dictionary ServiceWorkerMessageEventInit : EventInit {
any data;
DOMString origin;
DOMString lastEventId;
(ServiceWorker or MessagePort)? source;
sequence<MessagePort>? ports;
};
[Global=(Worker,ServiceWorker), Exposed=ServiceWorker]
interface ServiceWorkerGlobalScope : WorkerGlobalScope {
// A container for a list of Client objects that correspond to
// browsing contexts (or shared workers) that are on the origin of this SW
[SameObject] readonly attribute Clients clients;
[SameObject] readonly attribute ServiceWorkerRegistration registration;
[NewObject] Promise<void> skipWaiting();
attribute EventHandler oninstall;
attribute EventHandler onactivate;
attribute EventHandler onfetch;
attribute EventHandler onforeignfetch;
// event
attribute EventHandler onmessage; // event.source of the message events is Client object
};
[Exposed=ServiceWorker]
interface Client {
readonly attribute USVString url;
readonly attribute FrameType frameType;
readonly attribute DOMString id;
void postMessage(any message, optional sequence<object> transfer);
};
[Exposed=ServiceWorker]
interface WindowClient : Client {
readonly attribute VisibilityState visibilityState;
readonly attribute boolean focused;
[NewObject] Promise<WindowClient> focus();
[NewObject] Promise<WindowClient> navigate(USVString url);
};
enum FrameType {
"auxiliary",
"top-level",
"nested",
"none"
};
[Exposed=ServiceWorker]
interface Clients {
// The objects returned will be new instances every time
[NewObject] Promise<any> get(DOMString id);
[NewObject] Promise<sequence<Client>> matchAll(optional ClientQueryOptions options);
[NewObject] Promise<WindowClient?> openWindow(USVString url);
[NewObject] Promise<void> claim();
};
dictionary ClientQueryOptions {
boolean includeUncontrolled = false;
ClientType type = "window";
};
enum ClientType {
"window",
"worker",
"sharedworker",
"all"
};
[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableEvent : Event {
void waitUntil(Promise<any> f);
};
dictionary ExtendableEventInit : EventInit {
// Defined for the forward compatibility across the derived events
};
[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface InstallEvent : ExtendableEvent {
void registerForeignFetch(ForeignFetchOptions options);
};
dictionary ForeignFetchOptions {
required sequence<USVString> scopes;
required sequence<USVString> origins;
};
[Constructor(DOMString type, FetchEventInit eventInitDict), Exposed=ServiceWorker]
interface FetchEvent : ExtendableEvent {
[SameObject] readonly attribute Request request;
readonly attribute DOMString? clientId;
readonly attribute boolean isReload;
void respondWith(Promise<Response> r);
};
dictionary FetchEventInit : ExtendableEventInit {
required Request request;
DOMString? clientId = null;
boolean isReload = false;
};
[Constructor(DOMString type, ForeignFetchEventInit eventInitDict), Exposed=ServiceWorker]
interface ForeignFetchEvent : ExtendableEvent {
[SameObject] readonly attribute Request request;
readonly attribute USVString origin;
void respondWith(Promise<ForeignFetchResponse> r);
};
dictionary ForeignFetchEventInit : ExtendableEventInit {
required Request request;
USVString origin = "null";
};
dictionary ForeignFetchResponse {
required Response response;
USVString origin;
sequence<ByteString> headers;
};
[Constructor(DOMString type, optional ExtendableMessageEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableMessageEvent : ExtendableEvent {
readonly attribute any data;
readonly attribute DOMString origin;
readonly attribute DOMString lastEventId;
[SameObject] readonly attribute (Client or ServiceWorker or MessagePort)? source;
readonly attribute FrozenArray<MessagePort>? ports;
};
dictionary ExtendableMessageEventInit : ExtendableEventInit {
any data;
DOMString origin;
DOMString lastEventId;
(Client or ServiceWorker or MessagePort)? source;
sequence<MessagePort>? ports;
};
partial interface HTMLLinkElement {
[CEReactions] attribute USVString scope;
[CEReactions] attribute WorkerType workerType;
};
partial interface WindowOrWorkerGlobalScope {
[SecureContext, SameObject] readonly attribute CacheStorage caches;
};
[SecureContext, Exposed=(Window,Worker)]
interface Cache {
[NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<sequence<Response>> matchAll(optional RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<void> add(RequestInfo request);
[NewObject] Promise<void> addAll(sequence<RequestInfo> requests);
[NewObject] Promise<void> put(RequestInfo request, Response response);
[NewObject] Promise<boolean> delete(RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<sequence<Request>> keys(optional RequestInfo request, optional CacheQueryOptions options);
};
dictionary CacheQueryOptions {
boolean ignoreSearch = false;
boolean ignoreMethod = false;
boolean ignoreVary = false;
DOMString cacheName;
};
dictionary CacheBatchOperation {
DOMString type;
Request request;
Response response;
CacheQueryOptions options;
};
[SecureContext, Exposed=(Window,Worker)]
interface CacheStorage {
[NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<boolean> has(DOMString cacheName);
[NewObject] Promise<Cache> open(DOMString cacheName);
[NewObject] Promise<boolean> delete(DOMString cacheName);
[NewObject] Promise<sequence<DOMString>> keys();
};
partial interface ServiceWorkerRegistration {
// e.g. define an API namespace
readonly attribute APISpaceType APISpace;
// e.g. define a method
Promise<T> methodName(/* list of arguments */);
};
// e.g. define FunctionalEvent interface
interface FunctionalEvent : ExtendableEvent {
// add a functional events own attributes and methods
};
partial interface ServiceWorkerGlobalScope {
attribute EventHandler onfunctionalevent;
};
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorker : EventTarget {
readonly attribute USVString scriptURL;
readonly attribute ServiceWorkerState state;
void postMessage(any message, optional sequence<object> transfer);
// event
attribute EventHandler onstatechange;
};
ServiceWorker implements AbstractWorker;
enum ServiceWorkerState {
"installing",
"installed",
"activating",
"activated",
"redundant"
};
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerRegistration : EventTarget {
readonly attribute ServiceWorker? installing;
readonly attribute ServiceWorker? waiting;
readonly attribute ServiceWorker? active;
readonly attribute USVString scope;
[NewObject] Promise<void> update();
[NewObject] Promise<boolean> unregister();
// event
attribute EventHandler onupdatefound;
};
partial interface Navigator {
[SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};
partial interface WorkerNavigator {
[SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerContainer : EventTarget {
readonly attribute ServiceWorker? controller;
[SameObject] readonly attribute Promise<ServiceWorkerRegistration> ready;
[NewObject] Promise<ServiceWorkerRegistration> register(USVString scriptURL, optional RegistrationOptions options);
[NewObject] Promise<any> getRegistration(optional USVString clientURL = "");
[NewObject] Promise<sequence<ServiceWorkerRegistration>> getRegistrations();
void startMessages();
// events
attribute EventHandler oncontrollerchange;
attribute EventHandler onmessage; // event.source of message events is ServiceWorker object
};
dictionary RegistrationOptions {
USVString scope;
WorkerType type = "classic";
};
[Constructor(DOMString type, optional ServiceWorkerMessageEventInit eventInitDict), Exposed=(Window,Worker)]
interface ServiceWorkerMessageEvent : Event {
readonly attribute any data;
readonly attribute DOMString origin;
readonly attribute DOMString lastEventId;
[SameObject] readonly attribute (ServiceWorker or MessagePort)? source;
readonly attribute FrozenArray<MessagePort>? ports;
};
dictionary ServiceWorkerMessageEventInit : EventInit {
any data;
DOMString origin;
DOMString lastEventId;
(ServiceWorker or MessagePort)? source;
sequence<MessagePort>? ports;
};
[Global=(Worker,ServiceWorker), Exposed=ServiceWorker]
interface ServiceWorkerGlobalScope : WorkerGlobalScope {
// A container for a list of Client objects that correspond to
// browsing contexts (or shared workers) that are on the origin of this SW
[SameObject] readonly attribute Clients clients;
[SameObject] readonly attribute ServiceWorkerRegistration registration;
[NewObject] Promise<void> skipWaiting();
attribute EventHandler oninstall;
attribute EventHandler onactivate;
attribute EventHandler onfetch;
attribute EventHandler onforeignfetch;
// event
attribute EventHandler onmessage; // event.source of the message events is Client object
};
[Exposed=ServiceWorker]
interface Client {
readonly attribute USVString url;
readonly attribute FrameType frameType;
readonly attribute DOMString id;
void postMessage(any message, optional sequence<object> transfer);
};
[Exposed=ServiceWorker]
interface WindowClient : Client {
readonly attribute VisibilityState visibilityState;
readonly attribute boolean focused;
[NewObject] Promise<WindowClient> focus();
[NewObject] Promise<WindowClient> navigate(USVString url);
};
enum FrameType {
"auxiliary",
"top-level",
"nested",
"none"
};
[Exposed=ServiceWorker]
interface Clients {
// The objects returned will be new instances every time
[NewObject] Promise<any> get(DOMString id);
[NewObject] Promise<sequence<Client>> matchAll(optional ClientQueryOptions options);
[NewObject] Promise<WindowClient?> openWindow(USVString url);
[NewObject] Promise<void> claim();
};
dictionary ClientQueryOptions {
boolean includeUncontrolled = false;
ClientType type = "window";
};
enum ClientType {
"window",
"worker",
"sharedworker",
"all"
};
[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableEvent : Event {
void waitUntil(Promise<any> f);
};
dictionary ExtendableEventInit : EventInit {
// Defined for the forward compatibility across the derived events
};
[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface InstallEvent : ExtendableEvent {
void registerForeignFetch(ForeignFetchOptions options);
};
dictionary ForeignFetchOptions {
required sequence<USVString> scopes;
required sequence<USVString> origins;
};
[Constructor(DOMString type, FetchEventInit eventInitDict), Exposed=ServiceWorker]
interface FetchEvent : ExtendableEvent {
[SameObject] readonly attribute Request request;
readonly attribute DOMString? clientId;
readonly attribute boolean isReload;
void respondWith(Promise<Response> r);
};
dictionary FetchEventInit : ExtendableEventInit {
required Request request;
DOMString? clientId = null;
boolean isReload = false;
};
[Constructor(DOMString type, ForeignFetchEventInit eventInitDict), Exposed=ServiceWorker]
interface ForeignFetchEvent : ExtendableEvent {
[SameObject] readonly attribute Request request;
readonly attribute USVString origin;
void respondWith(Promise<ForeignFetchResponse> r);
};
dictionary ForeignFetchEventInit : ExtendableEventInit {
required Request request;
USVString origin = "null";
};
dictionary ForeignFetchResponse {
required Response response;
USVString origin;
sequence<ByteString> headers;
};
[Constructor(DOMString type, optional ExtendableMessageEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableMessageEvent : ExtendableEvent {
readonly attribute any data;
readonly attribute DOMString origin;
readonly attribute DOMString lastEventId;
[SameObject] readonly attribute (Client or ServiceWorker or MessagePort)? source;
readonly attribute FrozenArray<MessagePort>? ports;
};
dictionary ExtendableMessageEventInit : ExtendableEventInit {
any data;
DOMString origin;
DOMString lastEventId;
(Client or ServiceWorker or MessagePort)? source;
sequence<MessagePort>? ports;
};
partial interface HTMLLinkElement {
[CEReactions] attribute USVString scope;
[CEReactions] attribute WorkerType workerType;
};
partial interface WindowOrWorkerGlobalScope {
[SecureContext, SameObject] readonly attribute CacheStorage caches;
};
[SecureContext, Exposed=(Window,Worker)]
interface Cache {
[NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<sequence<Response>> matchAll(optional RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<void> add(RequestInfo request);
[NewObject] Promise<void> addAll(sequence<RequestInfo> requests);
[NewObject] Promise<void> put(RequestInfo request, Response response);
[NewObject] Promise<boolean> delete(RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<sequence<Request>> keys(optional RequestInfo request, optional CacheQueryOptions options);
};
dictionary CacheQueryOptions {
boolean ignoreSearch = false;
boolean ignoreMethod = false;
boolean ignoreVary = false;
DOMString cacheName;
};
dictionary CacheBatchOperation {
DOMString type;
Request request;
Response response;
CacheQueryOptions options;
};
[SecureContext, Exposed=(Window,Worker)]
interface CacheStorage {
[NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
[NewObject] Promise<boolean> has(DOMString cacheName);
[NewObject] Promise<Cache> open(DOMString cacheName);
[NewObject] Promise<boolean> delete(DOMString cacheName);
[NewObject] Promise<sequence<DOMString>> keys();
};
+94
View File
@@ -0,0 +1,94 @@
namespace org.w3c.xhr;
// Downloaded from https://raw.githubusercontent.com/whatwg/xhr/master/Overview.src.html
[Exposed=(Window,DedicatedWorker,SharedWorker)]
interface XMLHttpRequestEventTarget : EventTarget {
// event handlers
attribute EventHandler onloadstart;
attribute EventHandler onprogress;
attribute EventHandler onabort;
attribute EventHandler onerror;
attribute EventHandler onload;
attribute EventHandler ontimeout;
attribute EventHandler onloadend;
};
[Exposed=(Window,DedicatedWorker,SharedWorker)]
interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {
};
enum XMLHttpRequestResponseType {
"",
"arraybuffer",
"blob",
"document",
"json",
"text"
};
[Constructor,
Exposed=(Window,DedicatedWorker,SharedWorker)]
interface XMLHttpRequest : XMLHttpRequestEventTarget {
// event handler
attribute EventHandler onreadystatechange;
// states
const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;
readonly attribute unsigned short readyState;
// request
void open(ByteString method, USVString url);
void open(ByteString method, USVString url, boolean async, optional USVString? username = null, optional USVString? password = null);
void setRequestHeader(ByteString name, ByteString value);
attribute unsigned long timeout;
attribute boolean withCredentials;
readonly attribute XMLHttpRequestUpload upload;
void send(optional (Document or BodyInit)? body = null);
void abort();
// response
readonly attribute USVString responseURL;
readonly attribute unsigned short status;
readonly attribute ByteString statusText;
ByteString? getResponseHeader(ByteString name);
ByteString getAllResponseHeaders();
void overrideMimeType(DOMString mime);
attribute XMLHttpRequestResponseType responseType;
readonly attribute any response;
readonly attribute USVString responseText;
[Exposed=Window] readonly attribute Document? responseXML;
};
typedef (File or USVString) FormDataEntryValue;
[Constructor(optional HTMLFormElement form),
Exposed=(Window,Worker)]
interface FormData {
void append(USVString name, USVString value);
void append(USVString name, Blob value, optional USVString filename);
void delete(USVString name);
FormDataEntryValue? get(USVString name);
sequence<FormDataEntryValue> getAll(USVString name);
boolean has(USVString name);
void set(USVString name, USVString value);
void set(USVString name, Blob value, optional USVString filename);
iterable<USVString, FormDataEntryValue>;
};
[Constructor(DOMString type, optional ProgressEventInit eventInitDict),
Exposed=(Window,DedicatedWorker,SharedWorker)]
interface ProgressEvent : Event {
readonly attribute boolean lengthComputable;
readonly attribute unsigned long long loaded;
readonly attribute unsigned long long total;
};
dictionary ProgressEventInit : EventInit {
boolean lengthComputable = false;
unsigned long long loaded = 0;
unsigned long long total = 0;
};
+38
View File
@@ -0,0 +1,38 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
public class Enum<T : Enum<T>> : Comparable<Enum<T>> {
@JsName("name$") private var _name: String = ""
@JsName("ordinal$") private var _ordinal: Int = 0
val name: String
get() = _name
val ordinal: Int
get() = _ordinal
override fun compareTo(other: Enum<T>) = ordinal.compareTo(other.ordinal)
override fun equals(other: Any?) = this === other
override fun hashCode(): Int = js("Kotlin.identityHashCode")(this)
override fun toString() = name
companion object
}
+100
View File
@@ -0,0 +1,100 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// a package is omitted to get declarations directly under the module
@PublishedApi
external internal fun <T> Array(size: Int): Array<T>
@JsName("newArray")
fun <T> newArray(size: Int, initValue: T) = fillArrayVal(Array<T>(size), initValue)
@JsName("newArrayF")
inline fun <T> arrayWithFun(size: Int, init: (Int) -> T) = fillArrayFun(Array<T>(size), init)
@JsName("fillArray")
inline fun <T> fillArrayFun(array: Array<T>, init: (Int) -> T): Array<T> {
for (i in 0..array.size - 1) {
array[i] = init(i)
}
return array
}
@JsName("booleanArray")
fun booleanArray(size: Int, init: dynamic): Array<Boolean> {
val result: dynamic = Array<Boolean>(size)
result.`$type$` = "BooleanArray"
return when (init) {
null, true -> fillArrayVal(result, false)
false -> result
else -> fillArrayFun<Boolean>(result, init)
}
}
@JsName("booleanArrayF")
inline fun booleanArrayWithFun(size: Int, init: (Int) -> Boolean): Array<Boolean> = fillArrayFun(booleanArray(size, false), init)
@JsName("charArray")
@Suppress("UNUSED_PARAMETER")
fun charArray(size: Int, init: dynamic): Array<Char> {
val result = js("new Uint16Array(size)")
result.`$type$` = "CharArray"
return when (init) {
null, true, false -> result // For consistency
else -> fillArrayFun<Char>(result, init)
}
}
@JsName("charArrayF")
inline fun charArrayWithFun(size: Int, init: (Int) -> Char): Array<Char> {
val array = charArray(size, null)
for (i in 0..array.size - 1) {
val value = init(i)
js("array[i] = value;")
}
return array
}
@JsName("untypedCharArrayF")
inline fun untypedCharArrayWithFun(size: Int, init: (Int) -> Char): Array<Char> {
val array = Array<Char>(size)
for (i in 0..array.size - 1) {
val value = init(i)
js("array[i] = value;")
}
return array
}
@JsName("longArray")
fun longArray(size: Int, init: dynamic): Array<Long> {
val result: dynamic = Array<Long>(size)
result.`$type$` = "LongArray"
return when (init) {
null, true -> fillArrayVal(result, 0L)
false -> result
else -> fillArrayFun<Long>(result, init)
}
}
@JsName("longArrayF")
inline fun longArrayWithFun(size: Int, init: (Int) -> Long): Array<Long> = fillArrayFun(longArray(size, false), init)
private fun <T> fillArrayVal(array: Array<T>, initValue: T): Array<T> {
for (i in 0..array.size - 1) {
array[i] = initValue
}
return array
}
@@ -0,0 +1,20 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js.internal
@JsName("Error")
public external open class JsError(message: String?)
+27
View File
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("WRONG_EXTERNAL_DECLARATION")
package kotlin.js
import kotlin.annotation.AnnotationTarget.*
@Retention(AnnotationRetention.BINARY)
@Target(CLASS, FUNCTION, PROPERTY, CONSTRUCTOR, PROPERTY_GETTER, PROPERTY_SETTER)
internal external annotation class JsName(val name: String)
internal external annotation class native
external fun js(code: String): dynamic
@@ -0,0 +1,113 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js.internal
@JsName("DoubleCompanionObject")
private object DoubleCompanionObject {
@JsName("MIN_VALUE")
val MIN_VALUE: Double = js("Number.MIN_VALUE")
@JsName("MAX_VALUE")
val MAX_VALUE: Double = js("Number.MAX_VALUE")
@JsName("POSITIVE_INFINITY")
val POSITIVE_INFINITY: Double = js("Number.POSITIVE_INFINITY")
@JsName("NEGATIVE_INFINITY")
val NEGATIVE_INFINITY: Double = js("Number.NEGATIVE_INFINITY")
@JsName("NaN")
val NaN: Double = js("Number.NaN")
}
@JsName("FloatCompanionObject")
private object FloatCompanionObject {
@JsName("MIN_VALUE")
val MIN_VALUE: Float = js("Number.MIN_VALUE")
@JsName("MAX_VALUE")
val MAX_VALUE: Float = js("Number.MAX_VALUE")
@JsName("POSITIVE_INFINITY")
val POSITIVE_INFINITY: Float = js("Number.POSITIVE_INFINITY")
@JsName("NEGATIVE_INFINITY")
val NEGATIVE_INFINITY: Float = js("Number.NEGATIVE_INFINITY")
@JsName("NaN")
val NaN: Float = js("Number.NaN")
}
@JsName("IntCompanionObject")
private object IntCompanionObject {
@JsName("MIN_VALUE")
val MIN_VALUE: Int = -2147483647 - 1
@JsName("MAX_VALUE")
val MAX_VALUE: Int = 2147483647
}
@JsName("LongCompanionObject")
private object LongCompanionObject {
@JsName("MIN_VALUE")
val MIN_VALUE: Long = js("Kotlin.Long.MIN_VALUE")
@JsName("MAX_VALUE")
val MAX_VALUE: Long = js("Kotlin.Long.MAX_VALUE")
}
@JsName("ShortCompanionObject")
private object ShortCompanionObject {
@JsName("MIN_VALUE")
val MIN_VALUE: Short = -32768
@JsName("MAX_VALUE")
val MAX_VALUE: Short = 32767
}
@JsName("ByteCompanionObject")
private object ByteCompanionObject {
@JsName("MIN_VALUE")
val MIN_VALUE: Byte = -128
@JsName("MAX_VALUE")
val MAX_VALUE: Byte = 127
}
@JsName("CharCompanionObject")
private object CharCompanionObject {
@JsName("MIN_HIGH_SURROGATE")
public const val MIN_HIGH_SURROGATE: Char = '\uD800'
@JsName("MAX_HIGH_SURROGATE")
public const val MAX_HIGH_SURROGATE: Char = '\uDBFF'
@JsName("MIN_LOW_SURROGATE")
public const val MIN_LOW_SURROGATE: Char = '\uDC00'
@JsName("MAX_LOW_SURROGATE")
public const val MAX_LOW_SURROGATE: Char = '\uDFFF'
@JsName("MIN_SURROGATE")
public const val MIN_SURROGATE: Char = MIN_HIGH_SURROGATE
@JsName("MAX_SURROGATE")
public const val MAX_SURROGATE: Char = MAX_LOW_SURROGATE
}
private object StringCompanionObject {}
+77
View File
@@ -0,0 +1,77 @@
@file: Suppress("DEPRECATION")
package jquery
import org.w3c.dom.Element
@Deprecated("JQuery is going to be removed from the standard library")
public external class JQuery() {
public fun addClass(className: String): JQuery
public fun addClass(f: (Int, String) -> String): JQuery
public fun attr(attrName: String): String
public fun attr(attrName: String, value: String): JQuery
public fun html(): String
public fun html(s: String): JQuery
public fun html(f: (Int, String) -> String): JQuery
public fun hasClass(className: String): Boolean
public fun removeClass(className: String): JQuery
public fun height(): Number
public fun width(): Number
public fun click(): JQuery
public fun mousedown(handler: (MouseEvent) -> Unit): JQuery
public fun mouseup(handler: (MouseEvent) -> Unit): JQuery
public fun mousemove(handler: (MouseEvent) -> Unit): JQuery
public fun dblclick(handler: (MouseClickEvent) -> Unit): JQuery
public fun click(handler: (MouseClickEvent) -> Unit): JQuery
public fun load(handler: () -> Unit): JQuery
public fun change(handler: () -> Unit): JQuery
public fun append(str: String): JQuery
public fun ready(handler: () -> Unit): JQuery
public fun text(text: String): JQuery
public fun slideUp(): JQuery
public fun hover(handlerInOut: () -> Unit): JQuery
public fun hover(handlerIn: () -> Unit, handlerOut: () -> Unit): JQuery
public fun next(): JQuery
public fun parent(): JQuery
public fun `val`(): String?
}
@Deprecated("JQuery is going to be removed from the standard library")
open public external class MouseEvent() {
public val pageX: Double
public val pageY: Double
public fun preventDefault()
public fun isDefaultPrevented(): Boolean
}
@Deprecated("JQuery is going to be removed from the standard library")
public external class MouseClickEvent() : MouseEvent {
public val which: Int
}
@Deprecated("JQuery is going to be removed from the standard library")
@JsName("$")
public external fun jq(selector: String): JQuery
@Deprecated("JQuery is going to be removed from the standard library")
@JsName("$")
public external fun jq(selector: String, context: Element): JQuery
@Deprecated("JQuery is going to be removed from the standard library")
@JsName("$")
public external fun jq(callback: () -> Unit): JQuery
@Deprecated("JQuery is going to be removed from the standard library")
@JsName("$")
public external fun jq(obj: JQuery): JQuery
@Deprecated("JQuery is going to be removed from the standard library")
@JsName("$")
public external fun jq(el: Element): JQuery
@Deprecated("JQuery is going to be removed from the standard library")
@JsName("$")
public external fun jq(): JQuery
+37
View File
@@ -0,0 +1,37 @@
@file: Suppress("DEPRECATION")
package jquery.ui
//jquery UI
import jquery.JQuery
import kotlin.js.Json
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.buttonset(): JQuery = asDynamic().buttonset()
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.dialog(): JQuery = asDynamic().dialog()
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.dialog(params: Json): JQuery = asDynamic().dialog(params)
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.dialog(mode: String, param: String): Any? = asDynamic().dialog(mode, param)
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.dialog(mode: String): JQuery = asDynamic().dialog(mode)
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.dialog(mode: String, param: String, value: Any?): JQuery = asDynamic().dialog(mode, param, value)
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.button(): JQuery = asDynamic().button()
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.accordion(): JQuery = asDynamic().accordion()
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.draggable(params: Json): JQuery = asDynamic().draggable(params)
@Deprecated("JQuery is going to be removed from the standard library")
public inline fun JQuery.selectable(): JQuery = asDynamic().selectable()
+134
View File
@@ -0,0 +1,134 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Kotlin.isBooleanArray = function (a) {
return (Array.isArray(a) || a instanceof Int8Array) && a.$type$ === "BooleanArray"
};
Kotlin.isByteArray = function (a) {
return a instanceof Int8Array && a.$type$ !== "BooleanArray"
};
Kotlin.isShortArray = function (a) {
return a instanceof Int16Array
};
Kotlin.isCharArray = function (a) {
return a instanceof Uint16Array && a.$type$ === "CharArray"
};
Kotlin.isIntArray = function (a) {
return a instanceof Int32Array
};
Kotlin.isFloatArray = function (a) {
return a instanceof Float32Array
};
Kotlin.isDoubleArray = function (a) {
return a instanceof Float64Array
};
Kotlin.isLongArray = function (a) {
return Array.isArray(a) && a.$type$ === "LongArray"
};
Kotlin.isArray = function (a) {
return Array.isArray(a) && !a.$type$;
};
Kotlin.isArrayish = function (a) {
return Array.isArray(a) || ArrayBuffer.isView(a)
};
Kotlin.arrayToString = function (a) {
var toString = Kotlin.isCharArray(a) ? String.fromCharCode : Kotlin.toString;
return "[" + Array.prototype.map.call(a, function(e) { return toString(e); }).join(", ") + "]";
};
Kotlin.arrayDeepToString = function (a, visited) {
visited = visited || [a];
var toString = Kotlin.isCharArray(a) ? String.fromCharCode : Kotlin.toString;
return "[" + Array.prototype.map.call(a, function (e) {
if (Kotlin.isArrayish(e) && visited.indexOf(e) < 0) {
visited.push(e);
var result = Kotlin.arrayDeepToString(e, visited);
visited.pop();
return result;
}
else {
return toString(e);
}
}).join(", ") + "]";
};
Kotlin.arrayEquals = function (a, b) {
if (a === b) {
return true;
}
if (!Kotlin.isArrayish(b) || a.length !== b.length) {
return false;
}
for (var i = 0, n = a.length; i < n; i++) {
if (!Kotlin.equals(a[i], b[i])) {
return false;
}
}
return true;
};
Kotlin.arrayDeepEquals = function (a, b) {
if (a === b) {
return true;
}
if (!Kotlin.isArrayish(b) || a.length !== b.length) {
return false;
}
for (var i = 0, n = a.length; i < n; i++) {
if (Kotlin.isArrayish(a[i])) {
if (!Kotlin.arrayDeepEquals(a[i], b[i])) {
return false;
}
}
else if (!Kotlin.equals(a[i], b[i])) {
return false;
}
}
return true;
};
Kotlin.arrayHashCode = function (arr) {
var result = 1;
for (var i = 0, n = arr.length; i < n; i++) {
result = ((31 * result | 0) + Kotlin.hashCode(arr[i])) | 0;
}
return result;
};
Kotlin.arrayDeepHashCode = function (arr) {
var result = 1;
for (var i = 0, n = arr.length; i < n; i++) {
var e = arr[i];
result = ((31 * result | 0) + (Kotlin.isArrayish(e) ? Kotlin.arrayDeepHashCode(e) : Kotlin.hashCode(e))) | 0;
}
return result;
};
Kotlin.primitiveArraySort = function (array) {
array.sort(Kotlin.primitiveCompareTo)
};
@@ -0,0 +1,66 @@
/*
* Copyright 2010-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Kotlin.getCallableRef = function(name, f) {
f.callableName = name;
return f;
};
Kotlin.getPropertyCallableRef = function(name, paramCount, getter, setter) {
getter.get = getter;
getter.set = setter;
getter.callableName = name;
return getPropertyRefClass(getter, setter, propertyRefClassMetadataCache[paramCount]);
};
function getPropertyRefClass(obj, setter, cache) {
obj.$metadata$ = getPropertyRefMetadata(typeof setter === "function" ? cache.mutable : cache.immutable);
obj.constructor = obj;
return obj;
}
var propertyRefClassMetadataCache = [
{
mutable: { value: null, implementedInterface: function () {
return Kotlin.kotlin.reflect.KMutableProperty0 }
},
immutable: { value: null, implementedInterface: function () {
return Kotlin.kotlin.reflect.KProperty0 }
}
},
{
mutable: { value: null, implementedInterface: function () {
return Kotlin.kotlin.reflect.KMutableProperty1 }
},
immutable: { value: null, implementedInterface: function () {
return Kotlin.kotlin.reflect.KProperty1 }
}
}
];
function getPropertyRefMetadata(cache) {
if (cache.value === null) {
cache.value = {
interfaces: [cache.implementedInterface()],
baseClass: null,
functions: {},
properties: {},
types: {},
staticMembers: {}
};
}
return cache.value;
}
+68
View File
@@ -0,0 +1,68 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Kotlin.toShort = function (a) {
return (a & 0xFFFF) << 16 >> 16;
};
Kotlin.toByte = function (a) {
return (a & 0xFF) << 24 >> 24;
};
Kotlin.toChar = function (a) {
return a & 0xFFFF;
};
Kotlin.numberToLong = function (a) {
return a instanceof Kotlin.Long ? a : Kotlin.Long.fromNumber(a);
};
Kotlin.numberToInt = function (a) {
return a instanceof Kotlin.Long ? a.toInt() : Kotlin.doubleToInt(a);
};
Kotlin.numberToShort = function (a) {
return Kotlin.toShort(Kotlin.numberToInt(a));
};
Kotlin.numberToByte = function (a) {
return Kotlin.toByte(Kotlin.numberToInt(a));
};
Kotlin.numberToDouble = function (a) {
return +a;
};
Kotlin.numberToChar = function (a) {
return Kotlin.toChar(Kotlin.numberToInt(a));
};
Kotlin.doubleToInt = function(a) {
if (a > 2147483647) return 2147483647;
if (a < -2147483648) return -2147483648;
return a | 0;
};
Kotlin.toBoxedChar = function (a) {
if (a == null) return a;
if (a instanceof Kotlin.BoxedChar) return a;
return new Kotlin.BoxedChar(a);
};
Kotlin.unboxChar = function(a) {
if (a == null) return a;
return Kotlin.toChar(a);
};
+95
View File
@@ -0,0 +1,95 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Kotlin.equals = function (obj1, obj2) {
if (obj1 == null) {
return obj2 == null;
}
if (obj2 == null) {
return false;
}
if (obj1 !== obj1) {
return obj2 !== obj2;
}
if (typeof obj1 === "object" && typeof obj1.equals === "function") {
return obj1.equals(obj2);
}
return obj1 === obj2;
};
Kotlin.hashCode = function (obj) {
if (obj == null) {
return 0;
}
var objType = typeof obj;
if ("object" === objType) {
return "function" === typeof obj.hashCode ? obj.hashCode() : getObjectHashCode(obj);
}
if ("function" === objType) {
return getObjectHashCode(obj);
}
if ("number" === objType) {
return Kotlin.numberHashCode(obj);
}
if ("boolean" === objType) {
return Number(obj)
}
var str = String(obj);
return getStringHashCode(str);
};
Kotlin.toString = function (o) {
if (o == null) {
return "null";
}
else if (Kotlin.isArrayish(o)) {
return "[...]";
}
else {
return o.toString();
}
};
/** @const */
var POW_2_32 = 4294967296;
// TODO: consider switching to Symbol type once we are on ES6.
/** @const */
var OBJECT_HASH_CODE_PROPERTY_NAME = "kotlinHashCodeValue$";
function getObjectHashCode(obj) {
if (!(OBJECT_HASH_CODE_PROPERTY_NAME in obj)) {
var hash = (Math.random() * POW_2_32) | 0; // Make 32-bit singed integer.
Object.defineProperty(obj, OBJECT_HASH_CODE_PROPERTY_NAME, { value: hash, enumerable: false });
}
return obj[OBJECT_HASH_CODE_PROPERTY_NAME];
}
function getStringHashCode(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
hash = (hash * 31 + code) | 0; // Keep it 32-bit.
}
return hash;
}
Kotlin.identityHashCode = getObjectHashCode;
+846
View File
@@ -0,0 +1,846 @@
/*
* Copyright 2010-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/**
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
* values as *signed* integers. See the from* functions below for more
* convenient ways of constructing Longs.
*
* The internal representation of a long is the two given signed, 32-bit values.
* We use 32-bit pieces because these are the size of integers on which
* Javascript performs bit-operations. For operations like addition and
* multiplication, we split each number into 16-bit pieces, which can easily be
* multiplied within Javascript's floating-point representation without overflow
* or change in sign.
*
* In the algorithms below, we frequently reduce the negative case to the
* positive case by negating the input(s) and then post-processing the result.
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
* a positive number, it overflows back into a negative). Not handling this
* case would often result in infinite recursion.
*
* @param {number} low The low (signed) 32 bits of the long.
* @param {number} high The high (signed) 32 bits of the long.
* @constructor
* @final
*/
Kotlin.Long = function(low, high) {
/**
* @type {number}
* @private
*/
this.low_ = low | 0; // force into 32 signed bits.
/**
* @type {number}
* @private
*/
this.high_ = high | 0; // force into 32 signed bits.
};
Kotlin.Long.$metadata$ = {
kind: "class",
simpleName: "Long",
interfaces:[]
};
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
// from* methods on which they depend.
/**
* A cache of the Long representations of small integer values.
* @type {!Object}
* @private
*/
Kotlin.Long.IntCache_ = {};
/**
* Returns a Long representing the given (32-bit) integer value.
* @param {number} value The 32-bit integer in question.
* @return {!Kotlin.Long} The corresponding Long value.
*/
Kotlin.Long.fromInt = function(value) {
if (-128 <= value && value < 128) {
var cachedObj = Kotlin.Long.IntCache_[value];
if (cachedObj) {
return cachedObj;
}
}
var obj = new Kotlin.Long(value | 0, value < 0 ? -1 : 0);
if (-128 <= value && value < 128) {
Kotlin.Long.IntCache_[value] = obj;
}
return obj;
};
/**
* Returns a Long representing the given value, provided that it is a finite
* number. Otherwise, zero is returned.
* @param {number} value The number in question.
* @return {!Kotlin.Long} The corresponding Long value.
*/
Kotlin.Long.fromNumber = function(value) {
if (isNaN(value) || !isFinite(value)) {
return Kotlin.Long.ZERO;
} else if (value <= -Kotlin.Long.TWO_PWR_63_DBL_) {
return Kotlin.Long.MIN_VALUE;
} else if (value + 1 >= Kotlin.Long.TWO_PWR_63_DBL_) {
return Kotlin.Long.MAX_VALUE;
} else if (value < 0) {
return Kotlin.Long.fromNumber(-value).negate();
} else {
return new Kotlin.Long(
(value % Kotlin.Long.TWO_PWR_32_DBL_) | 0,
(value / Kotlin.Long.TWO_PWR_32_DBL_) | 0);
}
};
/**
* Returns a Long representing the 64-bit integer that comes by concatenating
* the given high and low bits. Each is assumed to use 32 bits.
* @param {number} lowBits The low 32-bits.
* @param {number} highBits The high 32-bits.
* @return {!Kotlin.Long} The corresponding Long value.
*/
Kotlin.Long.fromBits = function(lowBits, highBits) {
return new Kotlin.Long(lowBits, highBits);
};
/**
* Returns a Long representation of the given string, written using the given
* radix.
* @param {string} str The textual representation of the Long.
* @param {number=} opt_radix The radix in which the text is written.
* @return {!Kotlin.Long} The corresponding Long value.
*/
Kotlin.Long.fromString = function(str, opt_radix) {
if (str.length == 0) {
throw Error('number format error: empty string');
}
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (str.charAt(0) == '-') {
return Kotlin.Long.fromString(str.substring(1), radix).negate();
} else if (str.indexOf('-') >= 0) {
throw Error('number format error: interior "-" character: ' + str);
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Kotlin.Long.fromNumber(Math.pow(radix, 8));
var result = Kotlin.Long.ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i);
var value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = Kotlin.Long.fromNumber(Math.pow(radix, size));
result = result.multiply(power).add(Kotlin.Long.fromNumber(value));
} else {
result = result.multiply(radixToPower);
result = result.add(Kotlin.Long.fromNumber(value));
}
}
return result;
};
// NOTE: the compiler should inline these constant values below and then remove
// these variables, so there should be no runtime penalty for these.
/**
* Number used repeated below in calculations. This must appear before the
* first call to any from* function below.
* @type {number}
* @private
*/
Kotlin.Long.TWO_PWR_16_DBL_ = 1 << 16;
/**
* @type {number}
* @private
*/
Kotlin.Long.TWO_PWR_24_DBL_ = 1 << 24;
/**
* @type {number}
* @private
*/
Kotlin.Long.TWO_PWR_32_DBL_ =
Kotlin.Long.TWO_PWR_16_DBL_ * Kotlin.Long.TWO_PWR_16_DBL_;
/**
* @type {number}
* @private
*/
Kotlin.Long.TWO_PWR_31_DBL_ =
Kotlin.Long.TWO_PWR_32_DBL_ / 2;
/**
* @type {number}
* @private
*/
Kotlin.Long.TWO_PWR_48_DBL_ =
Kotlin.Long.TWO_PWR_32_DBL_ * Kotlin.Long.TWO_PWR_16_DBL_;
/**
* @type {number}
* @private
*/
Kotlin.Long.TWO_PWR_64_DBL_ =
Kotlin.Long.TWO_PWR_32_DBL_ * Kotlin.Long.TWO_PWR_32_DBL_;
/**
* @type {number}
* @private
*/
Kotlin.Long.TWO_PWR_63_DBL_ =
Kotlin.Long.TWO_PWR_64_DBL_ / 2;
/** @type {!Kotlin.Long} */
Kotlin.Long.ZERO = Kotlin.Long.fromInt(0);
/** @type {!Kotlin.Long} */
Kotlin.Long.ONE = Kotlin.Long.fromInt(1);
/** @type {!Kotlin.Long} */
Kotlin.Long.NEG_ONE = Kotlin.Long.fromInt(-1);
/** @type {!Kotlin.Long} */
Kotlin.Long.MAX_VALUE =
Kotlin.Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
/** @type {!Kotlin.Long} */
Kotlin.Long.MIN_VALUE = Kotlin.Long.fromBits(0, 0x80000000 | 0);
/**
* @type {!Kotlin.Long}
* @private
*/
Kotlin.Long.TWO_PWR_24_ = Kotlin.Long.fromInt(1 << 24);
/** @return {number} The value, assuming it is a 32-bit integer. */
Kotlin.Long.prototype.toInt = function() {
return this.low_;
};
/** @return {number} The closest floating-point representation to this value. */
Kotlin.Long.prototype.toNumber = function() {
return this.high_ * Kotlin.Long.TWO_PWR_32_DBL_ +
this.getLowBitsUnsigned();
};
/** @return {number} The 32-bit hashCode of this value. */
Kotlin.Long.prototype.hashCode = function() {
return this.high_ ^ this.low_;
};
/**
* @param {number=} opt_radix The radix in which the text should be written.
* @return {string} The textual representation of this value.
* @override
*/
Kotlin.Long.prototype.toString = function(opt_radix) {
var radix = opt_radix || 10;
if (radix < 2 || 36 < radix) {
throw Error('radix out of range: ' + radix);
}
if (this.isZero()) {
return '0';
}
if (this.isNegative()) {
if (this.equalsLong(Kotlin.Long.MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = Kotlin.Long.fromNumber(radix);
var div = this.div(radixLong);
var rem = div.multiply(radixLong).subtract(this);
return div.toString(radix) + rem.toInt().toString(radix);
} else {
return '-' + this.negate().toString(radix);
}
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Kotlin.Long.fromNumber(Math.pow(radix, 6));
var rem = this;
var result = '';
while (true) {
var remDiv = rem.div(radixToPower);
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
var digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) {
return digits + result;
} else {
while (digits.length < 6) {
digits = '0' + digits;
}
result = '' + digits + result;
}
}
};
/** @return {number} The high 32-bits as a signed value. */
Kotlin.Long.prototype.getHighBits = function() {
return this.high_;
};
/** @return {number} The low 32-bits as a signed value. */
Kotlin.Long.prototype.getLowBits = function() {
return this.low_;
};
/** @return {number} The low 32-bits as an unsigned value. */
Kotlin.Long.prototype.getLowBitsUnsigned = function() {
return (this.low_ >= 0) ?
this.low_ : Kotlin.Long.TWO_PWR_32_DBL_ + this.low_;
};
/**
* @return {number} Returns the number of bits needed to represent the absolute
* value of this Long.
*/
Kotlin.Long.prototype.getNumBitsAbs = function() {
if (this.isNegative()) {
if (this.equalsLong(Kotlin.Long.MIN_VALUE)) {
return 64;
} else {
return this.negate().getNumBitsAbs();
}
} else {
var val = this.high_ != 0 ? this.high_ : this.low_;
for (var bit = 31; bit > 0; bit--) {
if ((val & (1 << bit)) != 0) {
break;
}
}
return this.high_ != 0 ? bit + 33 : bit + 1;
}
};
/** @return {boolean} Whether this value is zero. */
Kotlin.Long.prototype.isZero = function() {
return this.high_ == 0 && this.low_ == 0;
};
/** @return {boolean} Whether this value is negative. */
Kotlin.Long.prototype.isNegative = function() {
return this.high_ < 0;
};
/** @return {boolean} Whether this value is odd. */
Kotlin.Long.prototype.isOdd = function() {
return (this.low_ & 1) == 1;
};
/**
* @param {Kotlin.Long} other Long to compare against.
* @return {boolean} Whether this Long equals the other.
*/
Kotlin.Long.prototype.equalsLong = function(other) {
return (this.high_ == other.high_) && (this.low_ == other.low_);
};
/**
* @param {Kotlin.Long} other Long to compare against.
* @return {boolean} Whether this Long does not equal the other.
*/
Kotlin.Long.prototype.notEqualsLong = function(other) {
return (this.high_ != other.high_) || (this.low_ != other.low_);
};
/**
* @param {Kotlin.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than the other.
*/
Kotlin.Long.prototype.lessThan = function(other) {
return this.compare(other) < 0;
};
/**
* @param {Kotlin.Long} other Long to compare against.
* @return {boolean} Whether this Long is less than or equal to the other.
*/
Kotlin.Long.prototype.lessThanOrEqual = function(other) {
return this.compare(other) <= 0;
};
/**
* @param {Kotlin.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than the other.
*/
Kotlin.Long.prototype.greaterThan = function(other) {
return this.compare(other) > 0;
};
/**
* @param {Kotlin.Long} other Long to compare against.
* @return {boolean} Whether this Long is greater than or equal to the other.
*/
Kotlin.Long.prototype.greaterThanOrEqual = function(other) {
return this.compare(other) >= 0;
};
/**
* Compares this Long with the given one.
* @param {Kotlin.Long} other Long to compare against.
* @return {number} 0 if they are the same, 1 if the this is greater, and -1
* if the given one is greater.
*/
Kotlin.Long.prototype.compare = function(other) {
if (this.equalsLong(other)) {
return 0;
}
var thisNeg = this.isNegative();
var otherNeg = other.isNegative();
if (thisNeg && !otherNeg) {
return -1;
}
if (!thisNeg && otherNeg) {
return 1;
}
// at this point, the signs are the same, so subtraction will not overflow
if (this.subtract(other).isNegative()) {
return -1;
} else {
return 1;
}
};
/** @return {!Kotlin.Long} The negation of this value. */
Kotlin.Long.prototype.negate = function() {
if (this.equalsLong(Kotlin.Long.MIN_VALUE)) {
return Kotlin.Long.MIN_VALUE;
} else {
return this.not().add(Kotlin.Long.ONE);
}
};
/**
* Returns the sum of this and the given Long.
* @param {Kotlin.Long} other Long to add to this one.
* @return {!Kotlin.Long} The sum of this and the given Long.
*/
Kotlin.Long.prototype.add = function(other) {
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 + b48;
c48 &= 0xFFFF;
return Kotlin.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns the difference of this and the given Long.
* @param {Kotlin.Long} other Long to subtract from this.
* @return {!Kotlin.Long} The difference of this and the given Long.
*/
Kotlin.Long.prototype.subtract = function(other) {
return this.add(other.negate());
};
/**
* Returns the product of this and the given long.
* @param {Kotlin.Long} other Long to multiply with this.
* @return {!Kotlin.Long} The product of this and the other.
*/
Kotlin.Long.prototype.multiply = function(other) {
if (this.isZero()) {
return Kotlin.Long.ZERO;
} else if (other.isZero()) {
return Kotlin.Long.ZERO;
}
if (this.equalsLong(Kotlin.Long.MIN_VALUE)) {
return other.isOdd() ? Kotlin.Long.MIN_VALUE : Kotlin.Long.ZERO;
} else if (other.equalsLong(Kotlin.Long.MIN_VALUE)) {
return this.isOdd() ? Kotlin.Long.MIN_VALUE : Kotlin.Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().multiply(other.negate());
} else {
return this.negate().multiply(other).negate();
}
} else if (other.isNegative()) {
return this.multiply(other.negate()).negate();
}
// If both longs are small, use float multiplication
if (this.lessThan(Kotlin.Long.TWO_PWR_24_) &&
other.lessThan(Kotlin.Long.TWO_PWR_24_)) {
return Kotlin.Long.fromNumber(this.toNumber() * other.toNumber());
}
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high_ >>> 16;
var a32 = this.high_ & 0xFFFF;
var a16 = this.low_ >>> 16;
var a00 = this.low_ & 0xFFFF;
var b48 = other.high_ >>> 16;
var b32 = other.high_ & 0xFFFF;
var b16 = other.low_ >>> 16;
var b00 = other.low_ & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xFFFF;
return Kotlin.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns this Long divided by the given one.
* @param {Kotlin.Long} other Long by which to divide.
* @return {!Kotlin.Long} This Long divided by the given one.
*/
Kotlin.Long.prototype.div = function(other) {
if (other.isZero()) {
throw Error('division by zero');
} else if (this.isZero()) {
return Kotlin.Long.ZERO;
}
if (this.equalsLong(Kotlin.Long.MIN_VALUE)) {
if (other.equalsLong(Kotlin.Long.ONE) ||
other.equalsLong(Kotlin.Long.NEG_ONE)) {
return Kotlin.Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
} else if (other.equalsLong(Kotlin.Long.MIN_VALUE)) {
return Kotlin.Long.ONE;
} else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shiftRight(1);
var approx = halfThis.div(other).shiftLeft(1);
if (approx.equalsLong(Kotlin.Long.ZERO)) {
return other.isNegative() ? Kotlin.Long.ONE : Kotlin.Long.NEG_ONE;
} else {
var rem = this.subtract(other.multiply(approx));
var result = approx.add(rem.div(other));
return result;
}
}
} else if (other.equalsLong(Kotlin.Long.MIN_VALUE)) {
return Kotlin.Long.ZERO;
}
if (this.isNegative()) {
if (other.isNegative()) {
return this.negate().div(other.negate());
} else {
return this.negate().div(other).negate();
}
} else if (other.isNegative()) {
return this.div(other.negate()).negate();
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
var res = Kotlin.Long.ZERO;
var rem = this;
while (rem.greaterThanOrEqual(other)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
var approxRes = Kotlin.Long.fromNumber(approx);
var approxRem = approxRes.multiply(other);
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
approx -= delta;
approxRes = Kotlin.Long.fromNumber(approx);
approxRem = approxRes.multiply(other);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero()) {
approxRes = Kotlin.Long.ONE;
}
res = res.add(approxRes);
rem = rem.subtract(approxRem);
}
return res;
};
/**
* Returns this Long modulo the given one.
* @param {Kotlin.Long} other Long by which to mod.
* @return {!Kotlin.Long} This Long modulo the given one.
*/
Kotlin.Long.prototype.modulo = function(other) {
return this.subtract(this.div(other).multiply(other));
};
/** @return {!Kotlin.Long} The bitwise-NOT of this value. */
Kotlin.Long.prototype.not = function() {
return Kotlin.Long.fromBits(~this.low_, ~this.high_);
};
/**
* Returns the bitwise-AND of this Long and the given one.
* @param {Kotlin.Long} other The Long with which to AND.
* @return {!Kotlin.Long} The bitwise-AND of this and the other.
*/
Kotlin.Long.prototype.and = function(other) {
return Kotlin.Long.fromBits(this.low_ & other.low_,
this.high_ & other.high_);
};
/**
* Returns the bitwise-OR of this Long and the given one.
* @param {Kotlin.Long} other The Long with which to OR.
* @return {!Kotlin.Long} The bitwise-OR of this and the other.
*/
Kotlin.Long.prototype.or = function(other) {
return Kotlin.Long.fromBits(this.low_ | other.low_,
this.high_ | other.high_);
};
/**
* Returns the bitwise-XOR of this Long and the given one.
* @param {Kotlin.Long} other The Long with which to XOR.
* @return {!Kotlin.Long} The bitwise-XOR of this and the other.
*/
Kotlin.Long.prototype.xor = function(other) {
return Kotlin.Long.fromBits(this.low_ ^ other.low_,
this.high_ ^ other.high_);
};
/**
* Returns this Long with bits shifted to the left by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!Kotlin.Long} This shifted to the left by the given amount.
*/
Kotlin.Long.prototype.shiftLeft = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var low = this.low_;
if (numBits < 32) {
var high = this.high_;
return Kotlin.Long.fromBits(
low << numBits,
(high << numBits) | (low >>> (32 - numBits)));
} else {
return Kotlin.Long.fromBits(0, low << (numBits - 32));
}
}
};
/**
* Returns this Long with bits shifted to the right by the given amount.
* @param {number} numBits The number of bits by which to shift.
* @return {!Kotlin.Long} This shifted to the right by the given amount.
*/
Kotlin.Long.prototype.shiftRight = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return Kotlin.Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >> numBits);
} else {
return Kotlin.Long.fromBits(
high >> (numBits - 32),
high >= 0 ? 0 : -1);
}
}
};
/**
* Returns this Long with bits shifted to the right by the given amount, with
* zeros placed into the new leading bits.
* @param {number} numBits The number of bits by which to shift.
* @return {!Kotlin.Long} This shifted to the right by the given amount, with
* zeros placed into the new leading bits.
*/
Kotlin.Long.prototype.shiftRightUnsigned = function(numBits) {
numBits &= 63;
if (numBits == 0) {
return this;
} else {
var high = this.high_;
if (numBits < 32) {
var low = this.low_;
return Kotlin.Long.fromBits(
(low >>> numBits) | (high << (32 - numBits)),
high >>> numBits);
} else if (numBits == 32) {
return Kotlin.Long.fromBits(high, 0);
} else {
return Kotlin.Long.fromBits(high >>> (numBits - 32), 0);
}
}
};
// Support for Kotlin
Kotlin.Long.prototype.equals = function (other) {
return other instanceof Kotlin.Long && this.equalsLong(other);
};
Kotlin.Long.prototype.compareTo_11rb$ = Kotlin.Long.prototype.compare;
Kotlin.Long.prototype.inc = function() {
return this.add(Kotlin.Long.ONE);
};
Kotlin.Long.prototype.dec = function() {
return this.add(Kotlin.Long.NEG_ONE);
};
Kotlin.Long.prototype.valueOf = function() {
return this.toNumber();
};
Kotlin.Long.prototype.unaryPlus = function() {
return this;
};
Kotlin.Long.prototype.unaryMinus = Kotlin.Long.prototype.negate;
Kotlin.Long.prototype.inv = Kotlin.Long.prototype.not;
Kotlin.Long.prototype.rangeTo = function (other) {
return new Kotlin.kotlin.ranges.LongRange(this, other);
};
@@ -0,0 +1,96 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @param {string} id
* @param {Object} declaration
*/
Kotlin.defineModule = function (id, declaration) {
};
Kotlin.defineInlineFunction = function(tag, fun) {
return fun;
};
Kotlin.wrapFunction = function(fun) {
var f = function() {
f = fun();
return f.apply(this, arguments);
};
return function() {
return f.apply(this, arguments);
};
};
Kotlin.isTypeOf = function(type) {
return function (object) {
return typeof object === type;
}
};
Kotlin.isInstanceOf = function (klass) {
return function (object) {
return Kotlin.isType(object, klass);
}
};
Kotlin.orNull = function (fn) {
return function (object) {
return object == null || fn(object);
}
};
Kotlin.andPredicate = function (a, b) {
return function (object) {
return a(object) && b(object);
}
};
Kotlin.kotlinModuleMetadata = function (abiVersion, moduleName, data) {
};
Kotlin.suspendCall = function(value) {
return value;
};
Kotlin.coroutineResult = function(qualifier) {
throwMarkerError();
};
Kotlin.coroutineController = function(qualifier) {
throwMarkerError();
};
Kotlin.coroutineReceiver = function(qualifier) {
throwMarkerError();
};
Kotlin.setCoroutineResult = function(value, qualifier) {
throwMarkerError();
};
function throwMarkerError() {
throw new Error(
"This marker function should never been called. " +
"Looks like compiler did not eliminate it properly. " +
"Please, report an issue if you caught this exception.");
}
Kotlin.getFunctionById = function(id, defaultValue) {
return function() {
return defaultValue;
}
};
+114
View File
@@ -0,0 +1,114 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Kotlin.compareTo = function (a, b) {
var typeA = typeof a;
var typeB = typeof a;
if (Kotlin.isChar(a) && typeB === "number") {
return Kotlin.primitiveCompareTo(a.charCodeAt(0), b);
}
if (typeA === "number" && Kotlin.isChar(b)) {
return Kotlin.primitiveCompareTo(a, b.charCodeAt(0));
}
if (typeA === "number" || typeA === "string" || typeA === "boolean") {
return Kotlin.primitiveCompareTo(a, b);
}
return a.compareTo_11rb$(b);
};
Kotlin.primitiveCompareTo = function (a, b) {
return a < b ? -1 : a > b ? 1 : 0;
};
Kotlin.charInc = function (value) {
return Kotlin.toChar(value+1);
};
Kotlin.charDec = function (value) {
return Kotlin.toChar(value-1);
};
Kotlin.imul = Math.imul || imul;
Kotlin.imulEmulated = imul;
function imul(a, b) {
return ((a & 0xffff0000) * (b & 0xffff) + (a & 0xffff) * (b | 0)) | 0;
}
(function() {
var buf = new ArrayBuffer(8);
var bufFloat64 = new Float64Array(buf);
var bufFloat32 = new Float32Array(buf);
var bufInt32 = new Int32Array(buf);
var lowIndex = 0;
var highIndex = 1;
bufFloat64[0] = -1; // bff00000_00000000
if (bufInt32[lowIndex] !== 0) {
lowIndex = 1;
highIndex = 0;
}
Kotlin.doubleToBits = function(value) {
return Kotlin.doubleToRawBits(isNaN(value) ? NaN : value);
};
Kotlin.doubleToRawBits = function(value) {
bufFloat64[0] = value;
return Kotlin.Long.fromBits(bufInt32[lowIndex], bufInt32[highIndex]);
};
Kotlin.doubleFromBits = function(value) {
bufInt32[lowIndex] = value.low_;
bufInt32[highIndex] = value.high_;
return bufFloat64[0];
};
Kotlin.floatToBits = function(value) {
return Kotlin.floatToRawBits(isNaN(value) ? NaN : value);
};
Kotlin.floatToRawBits = function(value) {
bufFloat32[0] = value;
return bufInt32[0];
};
Kotlin.floatFromBits = function(value) {
bufInt32[0] = value;
return bufFloat32[0];
};
// returns zero value for number with positive sign bit and non-zero value for number with negative sign bit.
Kotlin.doubleSignBit = function(value) {
bufFloat64[0] = value;
return bufInt32[highIndex] & 0x80000000;
};
Kotlin.numberHashCode = function(obj) {
if ((obj | 0) === obj) {
return obj | 0;
}
else {
bufFloat64[0] = obj;
return (bufInt32[highIndex] * 31 | 0) + bufInt32[lowIndex] | 0;
}
}
})();
Kotlin.ensureNotNull = function(x) {
return x != null ? x : Kotlin.throwNPE();
};
+312
View File
@@ -0,0 +1,312 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (typeof String.prototype.startsWith === "undefined") {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
};
}
if (typeof String.prototype.endsWith === "undefined") {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (position === undefined || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
// ES6 Math polyfills
if (typeof Math.sign === "undefined") {
Math.sign = function(x) {
x = +x; // convert to a number
if (x === 0 || isNaN(x)) {
return Number(x);
}
return x > 0 ? 1 : -1;
};
}
if (typeof Math.trunc === "undefined") {
Math.trunc = function(x) {
if (isNaN(x)) {
return NaN;
}
if (x > 0) {
return Math.floor(x);
}
return Math.ceil(x);
};
}
(function() {
var epsilon = 2.220446049250313E-16;
var taylor_2_bound = Math.sqrt(epsilon);
var taylor_n_bound = Math.sqrt(taylor_2_bound);
var upper_taylor_2_bound = 1/taylor_2_bound;
var upper_taylor_n_bound = 1/taylor_n_bound;
if (typeof Math.sinh === "undefined") {
Math.sinh = function(x) {
if (Math.abs(x) < taylor_n_bound) {
var result = x;
if (Math.abs(x) > taylor_2_bound) {
result += (x * x * x) / 6;
}
return result;
} else {
var y = Math.exp(x);
var y1 = 1 / y;
if (!isFinite(y)) return Math.exp(x - Math.LN2);
if (!isFinite(y1)) return -Math.exp(-x - Math.LN2);
return (y - y1) / 2;
}
};
}
if (typeof Math.cosh === "undefined") {
Math.cosh = function(x) {
var y = Math.exp(x);
var y1 = 1 / y;
if (!isFinite(y) || !isFinite(y1)) return Math.exp(Math.abs(x) - Math.LN2);
return (y + y1) / 2;
};
}
if (typeof Math.tanh === "undefined") {
Math.tanh = function(x){
if (Math.abs(x) < taylor_n_bound) {
var result = x;
if (Math.abs(x) > taylor_2_bound) {
result -= (x * x * x) / 3;
}
return result;
}
else {
var a = Math.exp(+x), b = Math.exp(-x);
return a === Infinity ? 1 : b === Infinity ? -1 : (a - b) / (a + b);
}
};
}
// Inverse hyperbolic function implementations derived from boost special math functions,
// Copyright Eric Ford & Hubert Holin 2001.
if (typeof Math.asinh === "undefined") {
var asinh = function(x) {
if (x >= +taylor_n_bound)
{
if (x > upper_taylor_n_bound)
{
if (x > upper_taylor_2_bound)
{
// approximation by laurent series in 1/x at 0+ order from -1 to 0
return Math.log(x) + Math.LN2;
}
else
{
// approximation by laurent series in 1/x at 0+ order from -1 to 1
return Math.log(x * 2 + (1 / (x * 2)));
}
}
else
{
return Math.log(x + Math.sqrt(x * x + 1));
}
}
else if (x <= -taylor_n_bound)
{
return -asinh(-x);
}
else
{
// approximation by taylor series in x at 0 up to order 2
var result = x;
if (Math.abs(x) >= taylor_2_bound)
{
var x3 = x * x * x;
// approximation by taylor series in x at 0 up to order 4
result -= x3 / 6;
}
return result;
}
};
Math.asinh = asinh;
}
if (typeof Math.acosh === "undefined") {
Math.acosh = function(x) {
if (x < 1)
{
return NaN;
}
else if (x - 1 >= taylor_n_bound)
{
if (x > upper_taylor_2_bound)
{
// approximation by laurent series in 1/x at 0+ order from -1 to 0
return Math.log(x) + Math.LN2;
}
else
{
return Math.log(x + Math.sqrt(x * x - 1));
}
}
else
{
var y = Math.sqrt(x - 1);
// approximation by taylor series in y at 0 up to order 2
var result = y;
if (y >= taylor_2_bound)
{
var y3 = y * y * y;
// approximation by taylor series in y at 0 up to order 4
result -= y3 / 12;
}
return Math.sqrt(2) * result;
}
};
}
if (typeof Math.atanh === "undefined") {
Math.atanh = function(x) {
if (Math.abs(x) < taylor_n_bound) {
var result = x;
if (Math.abs(x) > taylor_2_bound) {
result += (x * x * x) / 3;
}
return result;
}
return Math.log((1 + x) / (1 - x)) / 2;
};
}
if (typeof Math.log1p === "undefined") {
Math.log1p = function(x) {
if (Math.abs(x) < taylor_n_bound) {
var x2 = x * x;
var x3 = x2 * x;
var x4 = x3 * x;
// approximation by taylor series in x at 0 up to order 4
return (-x4 / 4 + x3 / 3 - x2 / 2 + x);
}
return Math.log(x + 1);
};
}
if (typeof Math.expm1 === "undefined") {
Math.expm1 = function(x) {
if (Math.abs(x) < taylor_n_bound) {
var x2 = x * x;
var x3 = x2 * x;
var x4 = x3 * x;
// approximation by taylor series in x at 0 up to order 4
return (x4 / 24 + x3 / 6 + x2 / 2 + x);
}
return Math.exp(x) - 1;
};
}
})();
if (typeof Math.hypot === "undefined") {
Math.hypot = function() {
var y = 0;
var length = arguments.length;
for (var i = 0; i < length; i++) {
if (arguments[i] === Infinity || arguments[i] === -Infinity) {
return Infinity;
}
y += arguments[i] * arguments[i];
}
return Math.sqrt(y);
};
}
if (typeof Math.log10 === "undefined") {
Math.log10 = function(x) {
return Math.log(x) * Math.LOG10E;
};
}
if (typeof Math.log2 === "undefined") {
Math.log2 = function(x) {
return Math.log(x) * Math.LOG2E;
};
}
// For HtmlUnit and PhantomJs
if (typeof ArrayBuffer.isView === "undefined") {
ArrayBuffer.isView = function(a) {
return a != null && a.__proto__ != null && a.__proto__.__proto__ === Int8Array.prototype.__proto__;
};
}
(function() {
function normalizeOffset(offset, length) {
if (offset < 0) return Math.max(0, offset + length);
return Math.min(offset, length);
}
function typedArraySlice(begin, end) {
if (typeof end === "undefined") {
end = this.length;
}
begin = normalizeOffset(begin || 0, this.length);
end = Math.max(begin, normalizeOffset(end, this.length));
return new this.constructor(this.subarray(begin, end));
}
var arrays = [Int8Array, Int16Array, Uint16Array, Int32Array, Float32Array, Float64Array];
for (var i = 0; i < arrays.length; ++i) {
var TypedArray = arrays[i];
if (typeof TypedArray.prototype.slice === "undefined") {
Object.defineProperty(TypedArray.prototype, 'slice', {
value: typedArraySlice
});
}
}
// Patch apply to work with TypedArrays if needed.
try {
(function() {}).apply(null, new Int32Array(0))
} catch (e) {
var apply = Function.prototype.apply;
Object.defineProperty(Function.prototype, 'apply', {
value: function(self, array) {
return apply.call(this, self, [].slice.call(array));
}
});
}
// Patch map to work with TypedArrays if needed.
for (var i = 0; i < arrays.length; ++i) {
var TypedArray = arrays[i];
if (typeof TypedArray.prototype.map === "undefined") {
Object.defineProperty(TypedArray.prototype, 'map', {
value: function(callback, self) {
return [].slice.call(this).map(callback, self);
}
});
}
}
// Patch sort to work with TypedArrays if needed.
for (var i = 0; i < arrays.length; ++i) {
var TypedArray = arrays[i];
if (typeof TypedArray.prototype.sort === "undefined") {
Object.defineProperty(TypedArray.prototype, 'sort', {
value: function(compareFunction) {
return Array.prototype.sort.call(this, compareFunction);
}
});
}
}
})();
+140
View File
@@ -0,0 +1,140 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Kotlin.Kind = {
CLASS: "class",
INTERFACE: "interface",
OBJECT: "object"
};
Kotlin.callGetter = function (thisObject, klass, propertyName) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(klass, propertyName);
if (propertyDescriptor != null && propertyDescriptor.get != null) {
return propertyDescriptor.get.call(thisObject);
}
propertyDescriptor = Object.getOwnPropertyDescriptor(thisObject, propertyName);
if (propertyDescriptor != null && "value" in propertyDescriptor) {
return thisObject[propertyName];
}
return Kotlin.callGetter(thisObject, Object.getPrototypeOf(klass), propertyName);
};
Kotlin.callSetter = function (thisObject, klass, propertyName, value) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(klass, propertyName);
if (propertyDescriptor != null && propertyDescriptor.set != null) {
propertyDescriptor.set.call(thisObject, value);
return;
}
propertyDescriptor = Object.getOwnPropertyDescriptor(thisObject, propertyName);
if (propertyDescriptor != null && "value" in propertyDescriptor) {
thisObject[propertyName] = value;
return
}
Kotlin.callSetter(thisObject, Object.getPrototypeOf(klass), propertyName, value);
};
function isInheritanceFromInterface(ctor, iface) {
if (ctor === iface) return true;
var metadata = ctor.$metadata$;
if (metadata != null) {
var interfaces = metadata.interfaces;
for (var i = 0; i < interfaces.length; i++) {
if (isInheritanceFromInterface(interfaces[i], iface)) {
return true;
}
}
}
var superPrototype = ctor.prototype != null ? Object.getPrototypeOf(ctor.prototype) : null;
var superConstructor = superPrototype != null ? superPrototype.constructor : null;
return superConstructor != null && isInheritanceFromInterface(superConstructor, iface);
}
/**
*
* @param {*} object
* @param {Function|Object} klass
* @returns {Boolean}
*/
Kotlin.isType = function (object, klass) {
if (klass === Object) {
switch (typeof object) {
case "string":
case "number":
case "boolean":
case "function":
return true;
default:
return object instanceof Object;
}
}
if (object == null || klass == null || (typeof object !== 'object' && typeof object !== 'function')) {
return false;
}
if (typeof klass === "function" && object instanceof klass) {
return true;
}
var proto = Object.getPrototypeOf(klass);
var constructor = proto != null ? proto.constructor : null;
if (constructor != null && "$metadata$" in constructor) {
var metadata = constructor.$metadata$;
if (metadata.kind === Kotlin.Kind.OBJECT) {
return object === klass;
}
}
var klassMetadata = klass.$metadata$;
// In WebKit (JavaScriptCore) for some interfaces from DOM typeof returns "object", nevertheless they can be used in RHS of instanceof
if (klassMetadata == null) {
return object instanceof klass;
}
if (klassMetadata.kind === Kotlin.Kind.INTERFACE && object.constructor != null) {
return isInheritanceFromInterface(object.constructor, klass);
}
return false;
};
Kotlin.isNumber = function (a) {
return typeof a == "number" || a instanceof Kotlin.Long;
};
Kotlin.isChar = function (value) {
return value instanceof Kotlin.BoxedChar
};
Kotlin.isComparable = function (value) {
var type = typeof value;
return type === "string" ||
type === "boolean" ||
Kotlin.isNumber(value) ||
Kotlin.isType(value, Kotlin.kotlin.Comparable);
};
Kotlin.isCharSequence = function (value) {
return typeof value === "string" || Kotlin.isType(value, Kotlin.kotlin.CharSequence);
};
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
public interface Comparator<T> {
@JsName("compare") fun compare(a: T, b: T): Int
}
public inline fun <T> Comparator(crossinline comparison: (a: T, b: T) -> Int): Comparator<T> = object : Comparator<T> {
override fun compare(a: T, b: T): Int = comparison(a, b)
}
@@ -0,0 +1,177 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js
import kotlin.annotation.AnnotationTarget.*
@Target(CLASS, FUNCTION, PROPERTY, CONSTRUCTOR, VALUE_PARAMETER, PROPERTY_GETTER, PROPERTY_SETTER)
@Deprecated("Use `external` modifier instead", level = DeprecationLevel.ERROR)
public annotation class native(public val name: String = "")
@Target(FUNCTION)
@Deprecated("Use inline extension function with body using dynamic")
public annotation class nativeGetter
@Target(FUNCTION)
@Deprecated("Use inline extension function with body using dynamic")
public annotation class nativeSetter
@Target(FUNCTION)
@Deprecated("Use inline extension function with body using dynamic")
public annotation class nativeInvoke
@Target(CLASS, FUNCTION, PROPERTY)
internal annotation class library(public val name: String = "")
@Target(CLASS)
internal annotation class marker
/**
* Gives a declaration (a function, a property or a class) specific name in JavaScript.
*
* This may be useful in the following cases:
*
* * There are two functions for which the compiler gives same name in JavaScript, you can
* mark one with `@JsName(...)` to prevent the compiler from reporting error.
* * You are writing a JavaScript library in Kotlin. The compiler produces mangled names
* for functions with parameters, which is unnatural for usual JavaScript developer.
* You can put `@JsName(...)` on functions you want to be available from JavaScript.
* * For some reason you want to rename declaration, e.g. there's common term in JavaScript
* for a concept provided by the declaration, which in uncommon in Kotlin.
*
* Example:
*
* ``` kotlin
* class Person(val name: String) {
* fun hello() {
* println("Hello $name!")
* }
*
* @JsName("helloWithGreeting")
* fun hello(greeting: String) {
* println("$greeting $name!")
* }
* }
* ```
*
* @property name the name which compiler uses both for declaration itself and for all references to the declaration.
* It's required to denote a valid JavaScript identifier.
*
* @since 1.1
*/
@Retention(AnnotationRetention.BINARY)
@Target(CLASS, FUNCTION, PROPERTY, CONSTRUCTOR, PROPERTY_GETTER, PROPERTY_SETTER)
annotation class JsName(val name: String)
/**
* Denotes an `external` declaration that must be imported from native JavaScript library.
*
* The compiler produces the code relevant for the target module system, for example, in case of CommonJS,
* it will import the declaration via the `require(...)` function.
*
* The annotation can be used on top-level external declarations (classes, properties, functions) and files.
* In case of file (which can't be `external`) the following rule applies: all the declarations in
* the file must be `external`. By applying `@JsModule(...)` on a file you tell the compiler to import a JavaScript object
* that contain all the declarations from the file.
*
* Example:
*
* ``` kotlin
* @JsModule("jquery")
* external abstract class JQuery() {
* // some declarations here
* }
*
* @JsModule("jquery")
* external fun JQuery(element: Element): JQuery
* ```
*
* @property import name of a module to import declaration from.
* It is not interpreted by the Kotlin compiler, it's passed as is directly to the target module system.
*
* @see JsNonModule
* @since 1.1
*/
@Retention(AnnotationRetention.BINARY)
@Target(CLASS, PROPERTY, FUNCTION, FILE)
annotation class JsModule(val import: String)
/**
* Denotes an `external` declaration that can be used without module system.
*
* By default, an `external` declaration is available regardless your target module system.
* However, by applying [JsModule] annotation you can make a declaration unavailable to *plain* module system.
* Some JavaScript libraries are distributed both as a standalone downloadable piece of JavaScript and as a module available
* as an npm package.
* To tell the Kotlin compiler to accept both cases, you can augment [JsModule] with the `@JsNonModule` annotation.
*
* For example:
*
* ``` kotlin
* @JsModule("jquery")
* @JsNonModule
* @JsName("$")
* external abstract class JQuery() {
* // some declarations here
* }
*
* @JsModule("jquery")
* @JsNonModule
* @JsName("$")
* external fun JQuery(element: Element): JQuery
* ```
*
* @see JsModule
* @since 1.1
*/
@Retention(AnnotationRetention.BINARY)
@Target(CLASS, PROPERTY, FUNCTION, FILE)
annotation class JsNonModule
/**
* Adds prefix to `external` declarations in a source file.
*
* JavaScript does not have concept of packages (namespaces). They are usually emulated by nested objects.
* The compiler turns references to `external` declarations either to plain unprefixed names (in case of *plain* modules)
* or to plain imports.
* However, if a JavaScript library provides its declarations in packages, you won't be satisfied with this.
* You can tell the compiler to generate additional prefix before references to `external` declarations using the `@JsQuafier(...)`
* annotation.
*
* Note that a file marked with the `@JsQulifier(...)` annotation can't contain non-`external` declarations.
*
* Example:
*
* ```
* @file:JsQualifier("my.jsPackageName")
* package some.kotlinPackage
*
* external fun foo(x: Int)
*
* external fun bar(): String
* ```
*
* @property value the qualifier to add to the declarations in the generated code.
* It must be a sequence of valid JavaScript identifiers separated by the `.` character.
* Examples of valid qualifiers are: `foo`, `bar.Baz`, `_.$0.f`.
*
* @see JsModule
* @since 1.1
*/
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FILE)
annotation class JsQualifier(val value: String)
@@ -0,0 +1,47 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.jvm
// these are used in common generated code in stdlib
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CONSTRUCTOR)
@Retention(AnnotationRetention.SOURCE)
internal annotation class JvmOverloads
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FILE)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
internal annotation class JvmName(public val name: String)
@Target(AnnotationTarget.FILE)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
internal annotation class JvmMultifileClass
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
internal annotation class JvmField
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.SOURCE)
public annotation class Volatile
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@Retention(AnnotationRetention.SOURCE)
public annotation class Synchronized
@@ -0,0 +1,12 @@
package kotlin.browser
import org.w3c.dom.*
public external val window: Window
public external val document: Document
public external val localStorage: Storage
public external val sessionStorage: Storage
+229
View File
@@ -0,0 +1,229 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@JsName("arrayIterator")
internal fun arrayIterator(array: dynamic, type: String?) = when (type) {
null -> {
val arr: Array<dynamic> = array
object : Iterator<dynamic> {
var index = 0
override fun hasNext() = index < arr.size
override fun next() = if (index < arr.size) arr[index++] else throw NoSuchElementException("$index")
}
}
"BooleanArray" -> booleanArrayIterator(array)
"ByteArray" -> byteArrayIterator(array)
"ShortArray" -> shortArrayIterator(array)
"CharArray" -> charArrayIterator(array)
"IntArray" -> intArrayIterator(array)
"LongArray" -> longArrayIterator(array)
"FloatArray" -> floatArrayIterator(array)
"DoubleArray" -> doubleArrayIterator(array)
else -> throw IllegalStateException("Unsupported type argument for arrayIterator: $type")
}
@JsName("booleanArrayIterator")
internal fun booleanArrayIterator(array: BooleanArray) = object : BooleanIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextBoolean() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("byteArrayIterator")
internal fun byteArrayIterator(array: ByteArray) = object : ByteIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextByte() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("shortArrayIterator")
internal fun shortArrayIterator(array: ShortArray) = object : ShortIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextShort() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("charArrayIterator")
internal fun charArrayIterator(array: CharArray) = object : CharIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextChar() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("intArrayIterator")
internal fun intArrayIterator(array: IntArray) = object : IntIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextInt() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("floatArrayIterator")
internal fun floatArrayIterator(array: FloatArray) = object : FloatIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextFloat() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("doubleArrayIterator")
internal fun doubleArrayIterator(array: DoubleArray) = object : DoubleIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextDouble() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("longArrayIterator")
internal fun longArrayIterator(array: LongArray) = object : LongIterator() {
var index = 0
override fun hasNext() = index < array.size
override fun nextLong() = if (index < array.size) array[index++] else throw NoSuchElementException("$index")
}
@JsName("PropertyMetadata")
internal class PropertyMetadata(@JsName("callableName") val name: String)
@JsName("noWhenBranchMatched")
internal fun noWhenBranchMatched(): Nothing = throw NoWhenBranchMatchedException()
@JsName("subSequence")
internal fun subSequence(c: CharSequence, startIndex: Int, endIndex: Int): CharSequence {
if (c is String) {
return c.substring(startIndex, endIndex)
}
else {
return c.asDynamic().`subSequence_vux9f0$`(startIndex, endIndex)
}
}
@JsName("captureStack")
internal fun captureStack(baseClass: JsClass<in Throwable>, instance: Throwable) {
if (js("Error").captureStackTrace) {
js("Error").captureStackTrace(instance, instance::class.js);
}
else {
instance.asDynamic().stack = js("new Error()").stack;
}
}
@JsName("newThrowable")
internal fun newThrowable(message: String?, cause: Throwable?): Throwable {
val throwable = js("new Error()")
throwable.message = if (jsTypeOf(message) == "undefined") {
if (cause != null) cause.toString() else null
}
else {
message
}
throwable.cause = cause
throwable.name = "Throwable"
return throwable
}
@JsName("BoxedChar")
internal class BoxedChar(val c: Int) : Comparable<Int> {
override fun equals(other: Any?): Boolean {
return other is BoxedChar && c == other.c
}
override fun hashCode(): Int {
return c
}
override fun toString(): String {
return js("this.c").unsafeCast<Char>().toString()
}
override fun compareTo(other: Int): Int {
return js("this.c - other").unsafeCast<Int>()
}
@JsName("valueOf")
public fun valueOf(): Int {
return c
}
}
@kotlin.internal.InlineOnly
internal inline fun <T> concat(args: Array<T>): T {
val typed = js("Array")(args.size)
for (i in args.indices) {
val arr = args[i]
if (arr !is Array<*>) {
typed[i] = js("[]").slice.call(arr)
}
else {
typed[i] = arr
}
}
return js("[]").concat.apply(js("[]"), typed);
}
/** Concat regular Array's and TypedArray's into an Array.
*/
@PublishedApi
@JsName("arrayConcat")
@Suppress("UNUSED_PARAMETER")
internal fun <T> arrayConcat(a: T, b: T): T {
return concat(js("arguments"))
}
/** Concat primitive arrays. Main use: prepare vararg arguments.
* For compatibility with 1.1.0 the arguments may be a mixture of Array's and TypedArray's.
*
* If the first argument is TypedArray (Byte-, Short-, Char-, Int-, Float-, and DoubleArray) returns a TypedArray, otherwise an Array.
* If the first argument has the $type$ property (Boolean-, Char-, and LongArray) copy its value to result.$type$.
* If the first argument is a regular Array without the $type$ property default to arrayConcat.
*/
@PublishedApi
@JsName("primitiveArrayConcat")
@Suppress("UNUSED_PARAMETER")
internal fun <T> primitiveArrayConcat(a: T, b: T): T {
val args: Array<T> = js("arguments")
if (a is Array<*> && a.asDynamic().`$type$` === undefined) {
return concat(args)
}
else {
var size = 0
for (i in args.indices) {
size += args[i].asDynamic().length as Int
}
val result = js("new a.constructor(size)")
kotlin.copyArrayType(a, result)
size = 0
for (i in args.indices) {
val arr = args[i].asDynamic()
for (j in 0 until arr.length) {
result[size++] = arr[j]
}
}
return result
}
}
@JsName("booleanArrayOf")
internal fun booleanArrayOf() = withType("BooleanArray", js("[].slice.call(arguments)"))
@JsName("charArrayOf") // The arguments have to be slice'd here because of Rhino (see KT-16974)
internal fun charArrayOf() = withType("CharArray", js("new Uint16Array([].slice.call(arguments))"))
@JsName("longArrayOf")
internal fun longArrayOf() = withType("LongArray", js("[].slice.call(arguments)"))
@JsName("withType")
@kotlin.internal.InlineOnly
internal inline fun withType(type: String, array: dynamic): dynamic {
array.`$type$` = type
return array
}
+36
View File
@@ -0,0 +1,36 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.text
// actually \s is enough to match all whitespace, but \xA0 added because of different regexp behavior of Rhino used in Selenium tests
public fun Char.isWhitespace(): Boolean = toString().matches("[\\s\\xA0]")
@kotlin.internal.InlineOnly
public inline fun Char.toLowerCase(): Char = js("String.fromCharCode")(this).toLowerCase().charCodeAt(0)
@kotlin.internal.InlineOnly
public inline fun Char.toUpperCase(): Char = js("String.fromCharCode")(this).toUpperCase().charCodeAt(0)
/**
* Returns `true` if this character is a Unicode high-surrogate code unit (also known as leading-surrogate code unit).
*/
public fun Char.isHighSurrogate(): Boolean = this in Char.MIN_HIGH_SURROGATE..Char.MAX_HIGH_SURROGATE
/**
* Returns `true` if this character is a Unicode low-surrogate code unit (also known as trailing-surrogate code unit).
*/
public fun Char.isLowSurrogate(): Boolean = this in Char.MIN_LOW_SURROGATE..Char.MAX_LOW_SURROGATE
@@ -0,0 +1,157 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
import kotlin.comparisons.naturalOrder
import kotlin.math.floor
/** Returns the array if it's not `null`, or an empty array otherwise. */
@kotlin.internal.InlineOnly
public inline fun <T> Array<out T>?.orEmpty(): Array<out T> = this ?: emptyArray<T>()
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.toTypedArray(): Array<T> = copyToArray(this)
@JsName("copyToArray")
@PublishedApi
internal fun <T> copyToArray(collection: Collection<T>): Array<T> {
return if (collection.asDynamic().toArray !== undefined)
collection.asDynamic().toArray().unsafeCast<Array<T>>()
else
copyToArrayImpl(collection).unsafeCast<Array<T>>()
}
@JsName("copyToArrayImpl")
internal fun copyToArrayImpl(collection: Collection<*>): Array<Any?> {
val array = emptyArray<Any?>()
val iterator = collection.iterator()
while (iterator.hasNext())
array.asDynamic().push(iterator.next())
return array
}
@JsName("copyToExistingArrayImpl")
internal fun <T> copyToArrayImpl(collection: Collection<*>, array: Array<T>): Array<T> {
if (array.size < collection.size)
return copyToArrayImpl(collection).unsafeCast<Array<T>>()
val iterator = collection.iterator()
var index = 0
while (iterator.hasNext()) {
array[index++] = iterator.next().unsafeCast<T>()
}
if (index < array.size) {
array[index] = null.unsafeCast<T>()
}
return array
}
@library("arrayToString")
@Suppress("UNUSED_PARAMETER")
internal fun arrayToString(array: Array<*>): String = definedExternally
/**
* Returns an immutable list containing only the specified object [element].
*/
public fun <T> listOf(element: T): List<T> = arrayListOf(element)
/**
* Returns an immutable set containing only the specified object [element].
*/
public fun <T> setOf(element: T): Set<T> = hashSetOf(element)
/**
* Returns an immutable map, mapping only the specified key to the
* specified value.
*/
public fun <K, V> mapOf(pair: Pair<K, V>): Map<K, V> = hashMapOf(pair)
/**
* Fills the list with the provided [value].
*
* Each element in the list gets replaced with the [value].
*/
@SinceKotlin("1.2")
public fun <T> MutableList<T>.fill(value: T): Unit {
for (index in 0..lastIndex) {
this[index] = value
}
}
/**
* Randomly shuffles elements in this list.
*
* See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
*/
@SinceKotlin("1.2")
public fun <T> MutableList<T>.shuffle(): Unit {
for (i in lastIndex downTo 1) {
val j = rand(i + 1)
val copy = this[i]
this[i] = this[j]
this[j] = copy
}
}
private fun rand(upperBound: Int) = floor(kotlin.js.Math.random() * upperBound).toInt()
/**
* Returns a new list with the elements of this list randomly shuffled.
*/
@SinceKotlin("1.2")
public fun <T> Iterable<T>.shuffled(): List<T> = toMutableList().apply { shuffle() }
/**
* Sorts elements in the list in-place according to their natural sort order.
*/
public fun <T : Comparable<T>> MutableList<T>.sort(): Unit {
collectionsSort(this, naturalOrder())
}
/**
* Sorts elements in the list in-place according to the order specified with [comparator].
*/
public fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit {
collectionsSort(this, comparator)
}
private fun <T> collectionsSort(list: MutableList<T>, comparator: Comparator<in T>) {
if (list.size <= 1) return
val array = copyToArray(list)
array.asDynamic().sort(comparator.asDynamic().compare.bind(comparator))
for (i in 0 until array.size) {
list[i] = array[i]
}
}
internal fun <T> arrayOfNulls(reference: Array<out T>, size: Int): Array<T> {
return arrayOfNulls<Any>(size).unsafeCast<Array<T>>()
}
// no singleton map implementation in js, return map as is
internal inline fun <K, V> Map<K, V>.toSingletonMapOrSelf(): Map<K, V> = this
internal inline fun <K, V> Map<out K, V>.toSingletonMap(): Map<K, V> = this.toMutableMap()
internal inline fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean): Array<out Any?> =
if (isVarargs)
// no need to copy vararg array in JS
this
else
this.copyOf()
@@ -0,0 +1,60 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
/**
* Provides a skeletal implementation of the [MutableCollection] interface.
*
* @param E the type of elements contained in the collection. The collection is invariant on its element type.
*/
public abstract class AbstractMutableCollection<E> protected constructor() : AbstractCollection<E>(), MutableCollection<E> {
abstract override fun add(element: E): Boolean
override fun remove(element: E): Boolean {
val iterator = iterator()
while (iterator.hasNext()) {
if (iterator.next() == element) {
iterator.remove()
return true
}
}
return false
}
override fun addAll(elements: Collection<E>): Boolean {
var modified = false
for (element in elements) {
if (add(element)) modified = true
}
return modified
}
override fun removeAll(elements: Collection<E>): Boolean = (this as MutableIterable<E>).removeAll { it in elements }
override fun retainAll(elements: Collection<E>): Boolean = (this as MutableIterable<E>).removeAll { it !in elements }
override fun clear(): Unit {
val iterator = this.iterator()
while (iterator.hasNext()) {
iterator.next()
iterator.remove()
}
}
open fun toJSON(): Any = this.toArray()
}
@@ -0,0 +1,215 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT AbstractList
* Copyright 2007 Google Inc.
*/
package kotlin.collections
/**
* Provides a skeletal implementation of the [MutableList] interface.
*
* @param E the type of elements contained in the list. The list is invariant on its element type.
*/
public abstract class AbstractMutableList<E> protected constructor() : AbstractMutableCollection<E>(), MutableList<E> {
protected var modCount: Int = 0
abstract override fun add(index: Int, element: E): Unit
abstract override fun removeAt(index: Int): E
abstract override fun set(index: Int, element: E): E
override fun add(element: E): Boolean {
add(size, element)
return true
}
override fun addAll(index: Int, elements: Collection<E>): Boolean {
var _index = index
var changed = false
for (e in elements) {
add(_index++, e)
changed = true
}
return changed
}
override fun clear() {
removeRange(0, size)
}
override fun removeAll(elements: Collection<E>): Boolean = removeAll { it in elements }
override fun retainAll(elements: Collection<E>): Boolean = removeAll { it !in elements }
override fun iterator(): MutableIterator<E> = IteratorImpl()
override fun contains(element: E): Boolean = indexOf(element) >= 0
override fun indexOf(element: E): Int {
for (index in 0..lastIndex) {
if (get(index) == element) {
return index
}
}
return -1
}
override fun lastIndexOf(element: E): Int {
for (index in lastIndex downTo 0) {
if (get(index) == element) {
return index
}
}
return -1
}
override fun listIterator(): MutableListIterator<E> = listIterator(0)
override fun listIterator(index: Int): MutableListIterator<E> = ListIteratorImpl(index)
override fun subList(fromIndex: Int, toIndex: Int): MutableList<E> = SubList(this, fromIndex, toIndex)
/**
* Removes the range of elements from this list starting from [fromIndex] and ending with but not including [toIndex].
*/
protected open fun removeRange(fromIndex: Int, toIndex: Int) {
val iterator = listIterator(fromIndex)
repeat(toIndex - fromIndex) {
iterator.next()
iterator.remove()
}
}
/**
* Compares this list with another list instance with the ordered structural equality.
*
* @return true, if [other] instance is a [List] of the same size, which contains the same elements in the same order.
*/
override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is List<*>) return false
return AbstractList.orderedEquals(this, other)
}
/**
* Returns the hash code value for this list.
*/
override fun hashCode(): Int = AbstractList.orderedHashCode(this)
private open inner class IteratorImpl : MutableIterator<E> {
/** the index of the item that will be returned on the next call to [next]`()` */
protected var index = 0
/** the index of the item that was returned on the previous call to [next]`()`
* or [ListIterator.previous]`()` (for `ListIterator`),
* -1 if no such item exists
*/
protected var last = -1
override fun hasNext(): Boolean = index < size
override fun next(): E {
if (!hasNext()) throw NoSuchElementException()
last = index++
return get(last)
}
override fun remove() {
check(last != -1) { "Call next() or previous() before removing element from the iterator."}
removeAt(last)
index = last
last = -1
}
}
/**
* Implementation of `MutableListIterator` for abstract lists.
*/
private inner class ListIteratorImpl(index: Int) : IteratorImpl(), MutableListIterator<E> {
init {
AbstractList.checkPositionIndex(index, this@AbstractMutableList.size)
this.index = index
}
override fun hasPrevious(): Boolean = index > 0
override fun nextIndex(): Int = index
override fun previous(): E {
if (!hasPrevious()) throw NoSuchElementException()
last = --index
return get(last)
}
override fun previousIndex(): Int = index - 1
override fun add(element: E) {
add(index, element)
index++
last = -1
}
override fun set(element: E) {
check(last != -1) { "Call next() or previous() before updating element value with the iterator."}
this@AbstractMutableList[last] = element
}
}
private class SubList<E>(private val list: AbstractMutableList<E>, private val fromIndex: Int, toIndex: Int) : AbstractMutableList<E>(), RandomAccess {
private var _size: Int = 0
init {
AbstractList.checkRangeIndexes(fromIndex, toIndex, list.size)
this._size = toIndex - fromIndex
}
override fun add(index: Int, element: E) {
AbstractList.checkPositionIndex(index, _size)
list.add(fromIndex + index, element)
_size++
}
override fun get(index: Int): E {
AbstractList.checkElementIndex(index, _size)
return list[fromIndex + index]
}
override fun removeAt(index: Int): E {
AbstractList.checkElementIndex(index, _size)
val result = list.removeAt(fromIndex + index)
_size--
return result
}
override fun set(index: Int, element: E): E {
AbstractList.checkElementIndex(index, _size)
return list.set(fromIndex + index, element)
}
override val size: Int get() = _size
}
}
@@ -0,0 +1,147 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT AbstractMap
* Copyright 2007 Google Inc.
*/
package kotlin.collections
/**
* Provides a skeletal implementation of the [MutableMap] interface.
*
* The implementor is required to implement the [entries] property, which should return mutable set of map entries, and the [put] function.
*
* @param K the type of map keys. The map is invariant on its key type.
* @param V the type of map values. The map is invariant on its value type.
*/
public abstract class AbstractMutableMap<K, V> protected constructor() : AbstractMap<K, V>(), MutableMap<K, V> {
/**
* A mutable [Map.Entry] shared by several [Map] implementations.
*/
internal open class SimpleEntry<K, V>(override val key: K, value: V) : MutableMap.MutableEntry<K, V> {
constructor(entry: Map.Entry<K, V>) : this(entry.key, entry.value)
private var _value = value
override val value: V get() = _value
override fun setValue(newValue: V): V {
val oldValue = this._value
this._value = newValue
return oldValue
}
override fun hashCode(): Int = entryHashCode(this)
override fun toString(): String = entryToString(this)
override fun equals(other: Any?): Boolean = entryEquals(this, other)
}
override fun clear() {
entries.clear()
}
private var _keys: MutableSet<K>? = null
override val keys: MutableSet<K> get() {
if (_keys == null) {
_keys = object : AbstractMutableSet<K>() {
override fun add(element: K): Boolean = throw UnsupportedOperationException("Add is not supported on keys")
override fun clear() {
this@AbstractMutableMap.clear()
}
override operator fun contains(element: K): Boolean = containsKey(element)
override operator fun iterator(): MutableIterator<K> {
val entryIterator = entries.iterator()
return object : MutableIterator<K> {
override fun hasNext(): Boolean = entryIterator.hasNext()
override fun next(): K = entryIterator.next().key
override fun remove() = entryIterator.remove()
}
}
override fun remove(element: K): Boolean {
if (containsKey(element)) {
this@AbstractMutableMap.remove(element)
return true
}
return false
}
override val size: Int get() = this@AbstractMutableMap.size
}
}
return _keys!!
}
abstract override fun put(key: K, value: V): V?
override fun putAll(from: Map<out K, V>) {
for ((key, value) in from) {
put(key, value)
}
}
private var _values: MutableCollection<V>? = null
override val values: MutableCollection<V> get() {
if (_values == null) {
_values = object : AbstractMutableCollection<V>() {
override fun add(element: V): Boolean = throw UnsupportedOperationException("Add is not supported on values")
override fun clear() = this@AbstractMutableMap.clear()
override operator fun contains(element: V): Boolean = containsValue(element)
override operator fun iterator(): MutableIterator<V> {
val entryIterator = entries.iterator()
return object : MutableIterator<V> {
override fun hasNext(): Boolean = entryIterator.hasNext()
override fun next(): V = entryIterator.next().value
override fun remove() = entryIterator.remove()
}
}
override val size: Int get() = this@AbstractMutableMap.size
// TODO: should we implement them this way? Currently it's unspecified in JVM
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Collection<*>) return false
return AbstractList.orderedEquals(this, other)
}
override fun hashCode(): Int = AbstractList.orderedHashCode(this)
}
}
return _values!!
}
override fun remove(key: K): V? {
val iter = entries.iterator()
while (iter.hasNext()) {
var entry = iter.next()
val k = entry.key
if (key == k) {
val value = entry.value
iter.remove()
return value
}
}
return null
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
/**
* Provides a skeletal implementation of the [MutableSet] interface.
*
* @param E the type of elements contained in the set. The set is invariant on its element type.
*/
public abstract class AbstractMutableSet<E> protected constructor() : AbstractMutableCollection<E>(), MutableSet<E> {
/**
* Compares this set with another set instance with the unordered structural equality.
*
* @return true, if [other] instance is a [Set] of the same size, all elements of which are contained in this set.
*/
override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is Set<*>) return false
return AbstractSet.setEquals(this, other)
}
/**
* Returns the hash code value for this set.
*/
override fun hashCode(): Int = AbstractSet.unorderedHashCode(this)
}
@@ -0,0 +1,130 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
/**
* Provides a [MutableList] implementation, which uses a resizable array as its backing storage.
*
* This implementation doesn't provide a way to manage capacity, as backing JS array is resizeable itself.
* There is no speed advantage to pre-allocating array sizes in JavaScript, so this implementation does not include any of the
* capacity and "growth increment" concepts.
*/
public open class ArrayList<E> internal constructor(private var array: Array<Any?>) : AbstractMutableList<E>(), RandomAccess {
/**
* Creates an empty [ArrayList].
* @param capacity initial capacity (ignored)
*/
public constructor(@Suppress("UNUSED_PARAMETER") capacity: Int = 0) : this(emptyArray()) {}
/**
* Creates an [ArrayList] filled from the [elements] collection.
*/
public constructor(elements: Collection<E>) : this(elements.toTypedArray<Any?>()) {}
/** Does nothing in this ArrayList implementation. */
public fun trimToSize() {}
/** Does nothing in this ArrayList implementation. */
public fun ensureCapacity(@Suppress("UNUSED_PARAMETER") minCapacity: Int) {}
override val size: Int get() = array.size
override fun get(index: Int): E = array[rangeCheck(index)] as E
override fun set(index: Int, element: E): E {
rangeCheck(index)
return array[index].apply { array[index] = element } as E
}
override fun add(element: E): Boolean {
array.asDynamic().push(element)
modCount++
return true
}
override fun add(index: Int, element: E): Unit {
array.asDynamic().splice(insertionRangeCheck(index), 0, element)
modCount++
}
override fun addAll(elements: Collection<E>): Boolean {
if (elements.isEmpty()) return false
array += elements.toTypedArray<Any?>()
modCount++
return true
}
override fun addAll(index: Int, elements: Collection<E>): Boolean {
insertionRangeCheck(index)
if (index == size) return addAll(elements)
if (elements.isEmpty()) return false
when (index) {
size -> return addAll(elements)
0 -> array = elements.toTypedArray<Any?>() + array
else -> array = array.copyOfRange(0, index).asDynamic().concat(elements.toTypedArray<Any?>(), array.copyOfRange(index, size))
}
modCount++
return true
}
override fun removeAt(index: Int): E {
rangeCheck(index)
modCount++
return if (index == lastIndex)
array.asDynamic().pop()
else
array.asDynamic().splice(index, 1)[0]
}
override fun remove(element: E): Boolean {
for (index in array.indices) {
if (array[index] == element) {
array.asDynamic().splice(index, 1)
modCount++
return true
}
}
return false
}
override fun removeRange(fromIndex: Int, toIndex: Int) {
modCount++
array.asDynamic().splice(fromIndex, toIndex - fromIndex)
}
override fun clear() {
array = emptyArray()
modCount++
}
override fun indexOf(element: E): Int = array.indexOf(element)
override fun lastIndexOf(element: E): Int = array.lastIndexOf(element)
override fun toString() = arrayToString(array)
override fun toArray(): Array<Any?> = js("[]").slice.call(array)
private fun rangeCheck(index: Int) = index.apply {
AbstractList.checkElementIndex(index, size)
}
private fun insertionRangeCheck(index: Int) = index.apply {
AbstractList.checkPositionIndex(index, size)
}
}
@@ -0,0 +1,37 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
internal interface EqualityComparator {
/**
* Subclasses must override to return a value indicating
* whether or not two keys or values are equal.
*/
abstract fun equals(value1: Any?, value2: Any?): Boolean
/**
* Subclasses must override to return the hash code of a given key.
*/
abstract fun getHashCode(value: Any?): Int
object HashCode : EqualityComparator {
override fun equals(value1: Any?, value2: Any?): Boolean = value1 == value2
override fun getHashCode(value: Any?): Int = value?.hashCode() ?: 0
}
}
@@ -0,0 +1,129 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT AbstractHashMap
* Copyright 2008 Google Inc.
*/
package kotlin.collections
import kotlin.collections.Map.Entry
import kotlin.collections.MutableMap.MutableEntry
/**
* Hash table based implementation of the [MutableMap] interface.
*
* This implementation makes no guarantees regarding the order of enumeration of [keys], [values] and [entries] collections.
*/
public open class HashMap<K, V> : AbstractMutableMap<K, V> {
private inner class EntrySet : AbstractMutableSet<MutableEntry<K, V>>() {
override fun add(element: MutableEntry<K, V>): Boolean = throw UnsupportedOperationException("Add is not supported on entries")
override fun clear() {
this@HashMap.clear()
}
override operator fun contains(element: MutableEntry<K, V>): Boolean = containsEntry(element)
override operator fun iterator(): MutableIterator<MutableEntry<K, V>> = internalMap.iterator()
override fun remove(element: MutableEntry<K, V>): Boolean {
if (contains(element)) {
this@HashMap.remove(element.key)
return true
}
return false
}
override val size: Int get() = this@HashMap.size
}
/**
* Internal implementation of the map: either string-based or hashcode-based.
*/
private val internalMap: InternalMap<K, V>
private val equality: EqualityComparator
internal constructor(internalMap: InternalMap<K, V>) : super() {
this.internalMap = internalMap
this.equality = internalMap.equality
}
/**
* Constructs an empty [HashMap] instance.
*/
constructor() : this(InternalHashCodeMap(EqualityComparator.HashCode))
/**
* Constructs an empty [HashMap] instance.
*
* @param initialCapacity the initial capacity (ignored)
* @param loadFactor the load factor (ignored)
*
* @throws IllegalArgumentException if the initial capacity or load factor are negative
*/
constructor(initialCapacity: Int, loadFactor: Float = 0f) : this() {
// This implementation of HashMap has no need of load factors or capacities.
require(initialCapacity >= 0) { "Negative initial capacity" }
require(loadFactor >= 0) { "Non-positive load factor" }
}
/**
* Constructs an instance of [HashMap] filled with the contents of the specified [original] map.
*/
constructor(original: Map<out K, V>) : this() {
this.putAll(original)
}
override fun clear() {
internalMap.clear()
// structureChanged(this)
}
override fun containsKey(key: K): Boolean = internalMap.contains(key)
override fun containsValue(value: V): Boolean = internalMap.any { equality.equals(it.value, value) }
private var _entries: MutableSet<MutableMap.MutableEntry<K, V>>? = null
override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() {
if (_entries == null) {
_entries = createEntrySet()
}
return _entries!!
}
protected open fun createEntrySet(): MutableSet<MutableMap.MutableEntry<K, V>> = EntrySet()
override operator fun get(key: K): V? = internalMap.get(key)
override fun put(key: K, value: V): V? = internalMap.put(key, value)
override fun remove(key: K): V? = internalMap.remove(key)
override val size: Int get() = internalMap.size
}
/**
* Constructs the specialized implementation of [HashMap] with [String] keys, which stores the keys as properties of
* JS object without hashing them.
*/
public fun <V> stringMapOf(vararg pairs: Pair<String, V>): HashMap<String, V> {
return HashMap<String, V>(InternalStringMap(EqualityComparator.HashCode)).apply { putAll(pairs) }
}
@@ -0,0 +1,98 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT HashSet
* Copyright 2008 Google Inc.
*/
package kotlin.collections
/**
* The implementation of the [MutableSet] interface, backed by a [HashMap] instance.
*/
public open class HashSet<E> : AbstractMutableSet<E> {
private val map: HashMap<E, Any>
/**
* Constructs a new empty [HashSet].
*/
constructor() {
map = HashMap<E, Any>()
}
/**
* Constructs a new [HashSet] filled with the elements of the specified collection.
*/
constructor(elements: Collection<E>) {
map = HashMap<E, Any>(elements.size)
addAll(elements)
}
/**
* Constructs a new empty [HashSet].
*
* @param initialCapacity the initial capacity (ignored)
* @param loadFactor the load factor (ignored)
*
* @throws IllegalArgumentException if the initial capacity or load factor are negative
*/
constructor(initialCapacity: Int, loadFactor: Float = 0.0f) {
map = HashMap<E, Any>(initialCapacity, loadFactor)
}
/**
* Protected constructor to specify the underlying map. This is used by
* LinkedHashSet.
* @param map underlying map to use.
*/
internal constructor(map: HashMap<E, Any>) {
this.map = map
}
override fun add(element: E): Boolean {
val old = map.put(element, this)
return old == null
}
override fun clear() {
map.clear()
}
// public override fun clone(): Any {
// return HashSet<E>(this)
// }
override operator fun contains(element: E): Boolean = map.containsKey(element)
override fun isEmpty(): Boolean = map.isEmpty()
override fun iterator(): MutableIterator<E> = map.keys.iterator()
override fun remove(element: E): Boolean = map.remove(element) != null
override val size: Int get() = map.size
}
/**
* Creates a new instance of the specialized implementation of [HashSet] with the specified [String] elements,
* which elements the keys as properties of JS object without hashing them.
*/
public fun stringSetOf(vararg elements: String): HashSet<String> {
return HashSet(stringMapOf<Any>()).apply { addAll(elements) }
}
@@ -0,0 +1,210 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT InternalHashCodeMap
* Copyright 2008 Google Inc.
*/
package kotlin.collections
import kotlin.collections.MutableMap.MutableEntry
import kotlin.collections.AbstractMutableMap.SimpleEntry
/**
* A simple wrapper around JavaScriptObject to provide [java.util.Map]-like semantics for any
* key type.
*
*
* Implementation notes:
*
*
* A key's hashCode is the index in backingMap which should contain that key. Since several keys may
* have the same hash, each value in hashCodeMap is actually an array containing all entries whose
* keys share the same hash.
*/
internal class InternalHashCodeMap<K, V>(override val equality: EqualityComparator) : InternalMap<K, V> {
private var backingMap: dynamic = createJsMap()
override var size: Int = 0
private set
override fun put(key: K, value: V): V? {
val hashCode = equality.getHashCode(key)
val chainOrEntry = getChainOrEntryOrNull(hashCode)
if (chainOrEntry == null) {
// This is a new chain, put it to the map.
backingMap[hashCode] = SimpleEntry(key, value)
}
else {
if (chainOrEntry !is Array<*>) {
// It is an entry
val entry: SimpleEntry<K, V> = chainOrEntry
if (equality.equals(entry.key, key)) {
return entry.setValue(value)
}
else {
backingMap[hashCode] = arrayOf(entry, SimpleEntry(key, value))
size++
return null
}
}
else {
// Chain already exists, perhaps key also exists.
val chain: Array<MutableEntry<K, V>> = chainOrEntry
val entry = chain.findEntryInChain(key)
if (entry != null) {
return entry.setValue(value)
}
chain.asDynamic().push(SimpleEntry(key, value))
}
}
size++
// structureChanged(host)
return null
}
override fun remove(key: K): V? {
val hashCode = equality.getHashCode(key)
val chainOrEntry = getChainOrEntryOrNull(hashCode) ?: return null
if (chainOrEntry !is Array<*>) {
val entry: MutableEntry<K, V> = chainOrEntry
if (equality.equals(entry.key, key)) {
deleteProperty(backingMap, hashCode)
size--
return entry.value
}
else {
return null
}
}
else {
val chain: Array<MutableEntry<K, V>> = chainOrEntry
for (index in chain.indices) {
val entry = chain[index]
if (equality.equals(key, entry.key)) {
if (chain.size == 1) {
chain.asDynamic().length = 0
// remove the whole array
deleteProperty(backingMap, hashCode)
} else {
// splice out the entry we're removing
chain.asDynamic().splice(index, 1)
}
size--
// structureChanged(host)
return entry.value
}
}
}
return null
}
override fun clear() {
backingMap = createJsMap()
size = 0
}
override fun contains(key: K): Boolean = getEntry(key) != null
override fun get(key: K): V? = getEntry(key)?.value
private fun getEntry(key: K): MutableEntry<K, V>? {
val chainOrEntry = getChainOrEntryOrNull(equality.getHashCode(key)) ?: return null
if (chainOrEntry !is Array<*>) {
val entry: MutableEntry<K, V> = chainOrEntry
if (equality.equals(entry.key, key)) {
return entry
}
else {
return null
}
}
else {
val chain: Array<MutableEntry<K, V>> = chainOrEntry
return chain.findEntryInChain(key)
}
}
private fun Array<MutableEntry<K, V>>.findEntryInChain(key: K): MutableEntry<K, V>? =
firstOrNull { entry -> equality.equals(entry.key, key) }
override fun iterator(): MutableIterator<MutableEntry<K, V>> {
return object : MutableIterator<MutableEntry<K, V>> {
var state = -1 // -1 not ready, 0 - ready, 1 - done
val keys: Array<Int> = js("Object").keys(backingMap)
var keyIndex = -1
var chainOrEntry: dynamic = null
var isChain = false
var itemIndex = -1
var lastEntry: MutableEntry<K, V>? = null
private fun computeNext(): Int {
if (chainOrEntry != null && isChain) {
val chainSize: Int = chainOrEntry.unsafeCast<Array<MutableEntry<K, V>>>().size
if (++itemIndex < chainSize)
return 0
}
if (++keyIndex < keys.size) {
chainOrEntry = backingMap[keys[keyIndex]]
isChain = chainOrEntry is Array<*>
itemIndex = 0
return 0
}
else {
chainOrEntry = null
return 1
}
}
override fun hasNext(): Boolean {
if (state == -1)
state = computeNext()
return state == 0
}
override fun next(): MutableEntry<K, V> {
if (!hasNext()) throw NoSuchElementException()
val lastEntry = if (isChain) {
chainOrEntry.unsafeCast<Array<MutableEntry<K, V>>>()[itemIndex]
}
else {
chainOrEntry.unsafeCast<MutableEntry<K, V>>()
}
this.lastEntry = lastEntry
state = -1
return lastEntry
}
override fun remove() {
checkNotNull(lastEntry)
this@InternalHashCodeMap.remove(lastEntry!!.key)
lastEntry = null
// the chain being iterated just got modified by InternalHashCodeMap.remove
itemIndex--
}
}
}
private fun getChainOrEntryOrNull(hashCode: Int): dynamic {
val chainOrEntry = backingMap[hashCode]
return if (chainOrEntry === undefined) null else chainOrEntry
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
/**
* The common interface of [InternalStringMap] and [InternalHashCodeMap].
*/
internal interface InternalMap<K, V> : MutableIterable<MutableMap.MutableEntry<K, V>> {
val equality: EqualityComparator
val size: Int
operator fun contains(key: K): Boolean
operator fun get(key: K): V?
fun put(key: K, value: V): V?
fun remove(key: K): V?
fun clear(): Unit
fun createJsMap(): dynamic {
val result = js("Object.create(null)")
// force to switch object representation to dictionary mode
result["foo"] = 1;
deleteProperty(result, "foo")
return result
}
}
@@ -0,0 +1,127 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT InternalStringMap
* Copyright 2008 Google Inc.
*/
package kotlin.collections
import kotlin.collections.MutableMap.MutableEntry
/**
* A simple wrapper around JavaScript Map for key type is string.
*
* Though this map is instantiated only with K=String, the K type is not fixed to String statically,
* because we want to have it erased to Any? in order not to generate type-safe override bridges for
* [get], [contains], [remove] etc, if they ever are generated.
*/
internal class InternalStringMap<K, V>(override val equality: EqualityComparator) : InternalMap<K, V> {
private var backingMap: dynamic = createJsMap()
override var size: Int = 0
private set
// /**
// * A mod count to track 'value' replacements in map to ensure that the 'value' that we have in the
// * iterator entry is guaranteed to be still correct.
// * This is to optimize for the common scenario where the values are not modified during
// * iterations where the entries are never stale.
// */
// private var valueMod: Int = 0
override operator fun contains(key: K): Boolean {
if (key !is String) return false
return backingMap[key] !== undefined
}
override operator fun get(key: K): V? {
if (key !is String) return null
val value = backingMap[key]
return if (value !== undefined) value.unsafeCast<V>() else null
}
override fun put(key: K, value: V): V? {
require(key is String)
val oldValue = backingMap[key]
backingMap[key] = value
if (oldValue === undefined) {
size++
// structureChanged(host)
return null
}
else {
// valueMod++
return oldValue.unsafeCast<V>()
}
}
override fun remove(key: K): V? {
if (key !is String) return null
val value = backingMap[key]
if (value !== undefined) {
deleteProperty(backingMap, key)
size--
// structureChanged(host)
return value.unsafeCast<V>()
}
else {
// valueMod++
return null
}
}
override fun clear() {
backingMap = createJsMap()
size = 0
}
override fun iterator(): MutableIterator<MutableEntry<K, V>> {
return object : MutableIterator<MutableEntry<K, V>> {
private val keys: Array<String> = js("Object").keys(backingMap)
private val iterator = keys.iterator()
private var lastKey: String? = null
override fun hasNext(): Boolean = iterator.hasNext()
override fun next(): MutableEntry<K, V> {
val key = iterator.next()
lastKey = key
@Suppress("UNCHECKED_CAST")
return newMapEntry(key as K)
}
override fun remove() {
@Suppress("UNCHECKED_CAST")
this@InternalStringMap.remove(checkNotNull(lastKey) as K)
}
}
}
private fun newMapEntry(key: K): MutableEntry<K, V> = object : MutableEntry<K, V> {
override val key: K get() = key
override val value: V get() = this@InternalStringMap[key].unsafeCast<V>()
override fun setValue(newValue: V): V = this@InternalStringMap.put(key, newValue).unsafeCast<V>()
override fun hashCode(): Int = AbstractMap.entryHashCode(this)
override fun toString(): String = AbstractMap.entryToString(this)
override fun equals(other: Any?): Boolean = AbstractMap.entryEquals(this, other)
}
}
@@ -0,0 +1,261 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT LinkedHashMap
* Copyright 2008 Google Inc.
*/
package kotlin.collections
import kotlin.collections.MutableMap.MutableEntry
/**
* Hash table based implementation of the [MutableMap] interface, which additionally preserves the insertion order
* of entries during the iteration.
*
* The insertion order is preserved by maintaining a doubly-linked list of all of its entries.
*/
public open class LinkedHashMap<K, V> : HashMap<K, V>, Map<K, V> {
/**
* The entry we use includes next/prev pointers for a doubly-linked circular
* list with a head node. This reduces the special cases we have to deal with
* in the list operations.
* Note that we duplicate the key from the underlying hash map so we can find
* the eldest entry. The alternative would have been to modify HashMap so more
* of the code was directly usable here, but this would have added some
* overhead to HashMap, or to reimplement most of the HashMap code here with
* small modifications. Paying a small storage cost only if you use
* LinkedHashMap and minimizing code size seemed like a better tradeoff
*/
private class ChainEntry<K, V>(key: K, value: V) : AbstractMutableMap.SimpleEntry<K, V>(key, value) {
internal var next: ChainEntry<K, V>? = null
internal var prev: ChainEntry<K, V>? = null
}
private inner class EntrySet : AbstractMutableSet<MutableEntry<K, V>>() {
private inner class EntryIterator : MutableIterator<MutableEntry<K, V>> {
// The last entry that was returned from this iterator.
private var last: ChainEntry<K, V>? = null
// The next entry to return from this iterator.
private var next: ChainEntry<K, V>? = null
init {
next = head
// recordLastKnownStructure(map, this)
}
override fun hasNext(): Boolean {
return next !== null
}
override fun next(): MutableEntry<K, V> {
// checkStructuralChange(map, this)
if (!hasNext()) throw NoSuchElementException()
val current = next!!
last = current
next = current.next.takeIf { it !== head }
return current
}
override fun remove() {
check(last != null)
// checkStructuralChange(map, this)
last!!.remove()
map.remove(last!!.key)
// recordLastKnownStructure(map, this)
last = null
}
}
override fun add(element: MutableEntry<K, V>): Boolean = throw UnsupportedOperationException("Add is not supported on entries")
override fun clear() {
this@LinkedHashMap.clear()
}
override operator fun contains(element: MutableEntry<K, V>): Boolean = containsEntry(element)
override operator fun iterator(): MutableIterator<MutableEntry<K, V>> = EntryIterator()
override fun remove(element: MutableEntry<K, V>): Boolean {
if (contains(element)) {
this@LinkedHashMap.remove(element.key)
return true
}
return false
}
override val size: Int get() = this@LinkedHashMap.size
}
/*
* The head of the insert order chain, which is a doubly-linked circular
* list.
*
* The most recently inserted node is at the end of the chain, ie.
* chain.prev.
*/
private var head: ChainEntry<K, V>? = null
/**
* Add this node to the end of the chain.
*/
private fun ChainEntry<K, V>.addToEnd() {
// This entry is not in the list.
check(next == null && prev == null)
val _head = head
if (_head == null) {
head = this
next = this
prev = this
} else {
// Chain is valid.
val _tail = checkNotNull(_head.prev)
// Update me.
prev = _tail
next = _head
// Update my new siblings: current head and old tail
_head.prev = this
_tail.next = this
}
}
/**
* Remove this node from the chain it is a part of.
*/
private fun ChainEntry<K, V>.remove() {
if (this.next === this) {
// if this is single element, remove head
head = null
}
else {
if (head === this) {
// if this is first element, move head to next
head = next
}
next!!.prev = prev
prev!!.next = next
}
next = null
prev = null
}
/*
* The hashmap that keeps track of our entries and the chain. Note that we
* duplicate the key here to eliminate changes to HashMap and minimize the
* code here, at the expense of additional space.
*/
private val map: HashMap<K, ChainEntry<K, V>>
/**
* Constructs an empty [LinkedHashMap] instance.
*/
constructor() : super() {
map = HashMap<K, ChainEntry<K, V>>()
}
internal constructor(backingMap: HashMap<K, Any>) : super() {
@Suppress("UNCHECKED_CAST") // expected to work due to erasure
map = backingMap as HashMap<K, ChainEntry<K, V>>
}
/**
* Constructs an empty [LinkedHashMap] instance.
*
* @param initialCapacity the initial capacity (ignored)
* @param loadFactor the load factor (ignored)
*
* @throws IllegalArgumentException if the initial capacity or load factor are negative
*/
constructor(initialCapacity: Int, loadFactor: Float = 0f) : super(initialCapacity, loadFactor) {
map = HashMap<K, ChainEntry<K, V>>()
}
/**
* Constructs an instance of [LinkedHashMap] filled with the contents of the specified [original] map.
*/
constructor(original: Map<out K, V>) {
map = HashMap<K, ChainEntry<K, V>>()
this.putAll(original)
}
override fun clear() {
map.clear()
head = null
}
// override fun clone(): Any {
// return LinkedHashMap(this)
// }
override fun containsKey(key: K): Boolean = map.containsKey(key)
override fun containsValue(value: V): Boolean {
var node: ChainEntry<K, V> = head ?: return false
do {
if (node.value == value) {
return true
}
node = node.next!!
} while (node !== head)
return false
}
override fun createEntrySet(): MutableSet<MutableMap.MutableEntry<K, V>> = EntrySet()
override operator fun get(key: K): V? = map.get(key)?.value
override fun put(key: K, value: V): V? {
val old = map.get(key)
if (old == null) {
val newEntry = ChainEntry(key, value)
map.put(key, newEntry)
newEntry.addToEnd()
return null
}
else {
return old.setValue(value)
}
}
override fun remove(key: K): V? {
val entry = map.remove(key)
if (entry != null) {
entry.remove()
return entry.value
}
return null
}
override val size: Int get() = map.size
}
/**
* Constructs the specialized implementation of [LinkedHashMap] with [String] keys, which stores the keys as properties of
* JS object without hashing them.
*/
public fun <V> linkedStringMapOf(vararg pairs: Pair<String, V>): LinkedHashMap<String, V> {
return LinkedHashMap<String, V>(stringMapOf<Any>()).apply { putAll(pairs) }
}
@@ -0,0 +1,65 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Based on GWT LinkedHashSet
* Copyright 2008 Google Inc.
*/
package kotlin.collections
/**
* The implementation of the [MutableSet] interface, backed by a [LinkedHashMap] instance.
*
* This implementation preserves the insertion order of elements during the iteration.
*/
public open class LinkedHashSet<E> : HashSet<E> {
internal constructor(map: LinkedHashMap<E, Any>) : super(map)
/**
* Constructs a new empty [LinkedHashSet].
*/
constructor() : super(LinkedHashMap<E, Any>())
/**
* Constructs a new [LinkedHashSet] filled with the elements of the specified collection.
*/
constructor(elements: Collection<E>) : super(LinkedHashMap<E, Any>()) {
addAll(elements)
}
/**
* Constructs a new empty [LinkedHashSet].
*
* @param initialCapacity the initial capacity (ignored)
* @param loadFactor the load factor (ignored)
*
* @throws IllegalArgumentException if the initial capacity or load factor are negative
*/
constructor(initialCapacity: Int, loadFactor: Float = 0.0f) : super(LinkedHashMap<E, Any>(initialCapacity, loadFactor))
// public override fun clone(): Any {
// return LinkedHashSet(this)
// }
}
/**
* Creates a new instance of the specialized implementation of [LinkedHashSet] with the specified [String] elements,
* which elements the keys as properties of JS object without hashing them.
*/
public fun linkedStringSetOf(vararg elements: String): LinkedHashSet<String> {
return LinkedHashSet(linkedStringMapOf<Any>()).apply { addAll(elements) }
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
/**
* Marker interface indicating that the [List] implementation supports fast indexed access.
*/
public interface RandomAccess
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
@Deprecated("Use Synchronized annotation from kotlin.jvm package", ReplaceWith("kotlin.jvm.Synchronized"), level = DeprecationLevel.WARNING)
public typealias Synchronized = kotlin.jvm.Synchronized
@Deprecated("Use Volatile annotation from kotlin.jvm package", ReplaceWith("kotlin.jvm.Volatile"), level = DeprecationLevel.WARNING)
public typealias Volatile = kotlin.jvm.Volatile
@kotlin.internal.InlineOnly
public inline fun <R> synchronized(@Suppress("UNUSED_PARAMETER") lock: Any, block: () -> R): R = block()
+113
View File
@@ -0,0 +1,113 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.io
private abstract class BaseOutput {
open fun println() {
print("\n")
}
open fun println(message: Any?) {
print(message)
println()
}
abstract fun print(message: Any?)
open fun flush() {}
}
/** JsName used to make the declaration available outside of module to test it */
@JsName("NodeJsOutput")
private class NodeJsOutput(val outputStream: dynamic) : BaseOutput() {
override fun print(message: Any?) = outputStream.write(String(message))
}
/** JsName used to make the declaration available outside of module to test it */
@JsName("OutputToConsoleLog")
private class OutputToConsoleLog : BaseOutput() {
override fun print(message: Any?) {
console.log(message)
}
override fun println(message: Any?) {
console.log(message)
}
override fun println() {
console.log("")
}
}
/** JsName used to make the declaration available outside of module to test it and use at try.kotl.in */
@JsName("BufferedOutput")
private open class BufferedOutput : BaseOutput() {
var buffer = ""
override fun print(message: Any?) {
buffer += String(message)
}
override fun flush() {
buffer = ""
}
}
/** JsName used to make the declaration available outside of module to test it */
@JsName("BufferedOutputToConsoleLog")
private class BufferedOutputToConsoleLog : BufferedOutput() {
override fun print(message: Any?) {
var s = String(message)
val i = s.lastIndexOf('\n')
if (i >= 0) {
buffer += s.substring(0, i)
flush()
s = s.substring(i + 1)
}
buffer += s
}
override fun flush() {
console.log(buffer)
buffer = ""
}
}
/** JsName used to make the declaration available outside of module to test it and use at try.kotl.in */
@JsName("output")
private var output = run {
val isNode: Boolean = js("typeof process !== 'undefined' && process.versions && !!process.versions.node")
if (isNode) NodeJsOutput(js("process.stdout")) else BufferedOutputToConsoleLog()
}
@kotlin.internal.InlineOnly
private inline fun String(value: Any?): String = js("String")(value)
/** Prints a newline to the standard output stream. */
public fun println() {
output.println()
}
/** Prints the given message and newline to the standard output stream. */
public fun println(message: Any?) {
output.println(message)
}
/** Prints the given message to the standard output stream. */
public fun print(message: Any?) {
output.print(message)
}
+83
View File
@@ -0,0 +1,83 @@
package kotlin.js
@Deprecated(message = "Use `definedExternally` instead", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("definedExternally"))
public external val noImpl: Nothing
/**
* The property that can be used as a placeholder for statements and values that are defined in JavaScript.
*
* This property can be used in two cases:
*
* * To represent body of an external function. In most cases Kotlin does not require to provide bodies of external
* functions and properties, but if for some reason you want to (for example, due to limitation of your coding style guides),
* you should use `definedExternally`.
* * To represent value of default argument.
*
* There's two forms of using `definedExternally`:
*
* 1. `= definedExternally` (for functions, properties and parameters).
* 2. `{ definedExternally }` (for functions and property getters/setters).
*
* This property can't be used from normal code.
*
* Examples:
*
* ``` kotlin
* external fun foo(): String = definedExternally
* external fun bar(x: Int) { definedExternally }
* external fun baz(z: Any = definedExternally): Array<Any>
* external val prop: Float = definedExternally
* ```
*/
public external val definedExternally: Nothing
/**
* Exposes the JavaScript [eval function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) to Kotlin.
*/
public external fun eval(expr: String): dynamic
/**
* Exposes the JavaScript [undefined property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) to Kotlin.
*/
public external val undefined: Nothing?
@Deprecated("Use toInt() instead.", ReplaceWith("s.toInt()"), level = DeprecationLevel.ERROR)
public external fun parseInt(s: String): Int
@Deprecated("Use toInt(radix) instead.", ReplaceWith("s.toInt(radix)"), level = DeprecationLevel.ERROR)
public external fun parseInt(s: String, radix: Int = definedExternally): Int
@Deprecated("Use toDouble() instead.", ReplaceWith("s.toDouble()"), level = DeprecationLevel.ERROR)
public external fun parseFloat(s: String, radix: Int = definedExternally): Double
/**
* Puts the given piece of a JavaScript code right into the calling function.
* The compiler replaces call to `js(...)` code with the string constant provided as a parameter.
*
* Example:
*
* ``` kotlin
* fun logToConsole(message: String): Unit {
* js("console.log(message)")
* }
* ```
*
* @param code the piece of JavaScript code to put to the generated code.
* Must be a compile-time constant, otherwise compiler produces error message.
* You can safely refer to local variables of calling function (but not to local variables of outer functions),
* including parameters. You can't refer to functions, properties and classes by their short names.
*/
public external fun js(code: String): dynamic
/**
* Function corresponding to JavaScript's `typeof` operator
*/
@kotlin.internal.InlineOnly
@Suppress("UNUSED_PARAMETER")
public inline fun jsTypeOf(a: Any?): String = js("typeof a")
@kotlin.internal.InlineOnly
@Suppress("UNUSED_PARAMETER")
internal inline fun deleteProperty(obj: Any, property: Any) {
js("delete obj[property]")
}
@@ -0,0 +1,117 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.coroutines.experimental
import kotlin.coroutines.experimental.intrinsics.*
@JsName("CoroutineImpl")
internal abstract class CoroutineImpl(private val resultContinuation: Continuation<Any?>) : Continuation<Any?> {
protected var state = 0
protected var exceptionState = 0
protected var result: Any? = null
protected var exception: Throwable? = null
protected var finallyPath: Array<Int>? = null
public override val context: CoroutineContext = resultContinuation.context
val facade: Continuation<Any?> = context[ContinuationInterceptor]?.interceptContinuation(this) ?: this
override fun resume(value: Any?) {
result = value
doResumeWrapper()
}
override fun resumeWithException(exception: Throwable) {
state = exceptionState
this.exception = exception
doResumeWrapper()
}
protected fun doResumeWrapper() {
processBareContinuationResume(resultContinuation) { doResume() }
}
protected abstract fun doResume(): Any?
}
private val UNDECIDED: Any? = Any()
private val RESUMED: Any? = Any()
private class Fail(val exception: Throwable)
@PublishedApi
internal class SafeContinuation<in T>
internal constructor(
private val delegate: Continuation<T>,
initialResult: Any?
) : Continuation<T> {
@PublishedApi
internal constructor(delegate: Continuation<T>) : this(delegate, UNDECIDED)
public override val context: CoroutineContext
get() = delegate.context
private var result: Any? = initialResult
override fun resume(value: T) {
when {
result === UNDECIDED -> {
result = value
}
result === COROUTINE_SUSPENDED -> {
result = RESUMED
delegate.resume(value)
}
else -> {
throw IllegalStateException("Already resumed")
}
}
}
override fun resumeWithException(exception: Throwable) {
when {
result === UNDECIDED -> {
result = Fail(exception)
}
result === COROUTINE_SUSPENDED -> {
result = RESUMED
delegate.resumeWithException(exception)
}
else -> {
throw IllegalStateException("Already resumed")
}
}
}
@PublishedApi
internal fun getResult(): Any? {
if (result === UNDECIDED) {
result = COROUTINE_SUSPENDED
}
val result = this.result
return when {
result === RESUMED -> {
COROUTINE_SUSPENDED // already called continuation, indicate SUSPENDED upstream
}
result is Fail -> {
throw result.exception
}
else -> {
result // either SUSPENDED or data
}
}
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.coroutines.experimental.intrinsics
import kotlin.coroutines.experimental.Continuation
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
@kotlin.internal.InlineOnly
public inline fun <T> (suspend () -> T).startCoroutineUninterceptedOrReturn(
completion: Continuation<T>
): Any? = this.asDynamic()(completion, false)
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
@kotlin.internal.InlineOnly
public inline fun <R, T> (suspend R.() -> T).startCoroutineUninterceptedOrReturn(
receiver: R,
completion: Continuation<T>
): Any? = this.asDynamic()(receiver, completion, false)
@SinceKotlin("1.1")
public fun <R, T> (suspend R.() -> T).createCoroutineUnchecked(
receiver: R,
completion: Continuation<T>
): Continuation<Unit> = this.asDynamic()(receiver, completion, true).facade
@SinceKotlin("1.1")
public fun <T> (suspend () -> T).createCoroutineUnchecked(
completion: Continuation<T>
): Continuation<Unit> = this.asDynamic()(completion, true).facade
+132
View File
@@ -0,0 +1,132 @@
package kotlin.js
/**
* Exposes the [Date API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) to Kotlin.
*/
public external class Date() {
public constructor(milliseconds: Number)
public constructor(dateString: String)
public constructor(year: Int, month: Int)
public constructor(year: Int, month: Int, day: Int)
public constructor(year: Int, month: Int, day: Int, hour: Int)
public constructor(year: Int, month: Int, day: Int, hour: Int, minute: Int)
public constructor(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int)
public constructor(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, millisecond: Number)
public fun getDate(): Int
public fun getDay(): Int
public fun getFullYear(): Int
public fun getHours(): Int
public fun getMilliseconds(): Int
public fun getMinutes(): Int
public fun getMonth(): Int
public fun getSeconds(): Int
public fun getTime(): Double
public fun getTimezoneOffset(): Int
public fun getUTCDate(): Int
public fun getUTCDay(): Int
public fun getUTCFullYear(): Int
public fun getUTCHours(): Int
public fun getUTCMilliseconds(): Int
public fun getUTCMinutes(): Int
public fun getUTCMonth(): Int
public fun getUTCSeconds(): Int
public fun toDateString(): String
public fun toISOString(): String
public fun toJSON(): Json
public fun toLocaleDateString(locales: Array<String> = definedExternally, options: LocaleOptions = definedExternally): String
public fun toLocaleDateString(locales: String, options: LocaleOptions = definedExternally): String
public fun toLocaleString(locales: Array<String> = definedExternally, options: LocaleOptions = definedExternally): String
public fun toLocaleString(locales: String, options: LocaleOptions = definedExternally): String
public fun toLocaleTimeString(locales: Array<String> = definedExternally, options: LocaleOptions = definedExternally): String
public fun toLocaleTimeString(locales: String, options: LocaleOptions = definedExternally): String
public fun toTimeString(): String
public fun toUTCString(): String
public companion object {
public fun now(): Double
public fun parse(dateString: String): Double
public fun UTC(year: Int, month: Int): Double
public fun UTC(year: Int, month: Int, day: Int): Double
public fun UTC(year: Int, month: Int, day: Int, hour: Int): Double
public fun UTC(year: Int, month: Int, day: Int, hour: Int, minute: Int): Double
public fun UTC(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Double
public fun UTC(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, millisecond: Number): Double
}
public interface LocaleOptions {
public var localeMatcher: String?
public var timeZone: String?
public var hour12: Boolean?
public var formatMatcher: String?
public var weekday: String?
public var era: String?
public var year: String?
public var month: String?
public var day: String?
public var hour: String?
public var minute: String?
public var second: String?
public var timeZoneName: String?
}
}
public inline fun dateLocaleOptions(init: Date.LocaleOptions.() -> Unit): Date.LocaleOptions {
val result = js("new Object()").unsafeCast<Date.LocaleOptions>()
init(result)
return result
}
+17
View File
@@ -0,0 +1,17 @@
package kotlin.js
/**
* Exposes the [console API](https://developer.mozilla.org/en/DOM/console) to Kotlin.
*/
external public interface Console {
public fun dir(o: Any): Unit
public fun error(vararg o: Any?): Unit
public fun info(vararg o: Any?): Unit
public fun log(vararg o: Any?): Unit
public fun warn(vararg o: Any?): Unit
}
/**
* Exposes the [console API](https://developer.mozilla.org/en/DOM/console) to Kotlin.
*/
public external val console: Console
@@ -0,0 +1,35 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.dom
import org.w3c.dom.*
/**
* Creates a new element with the specified [name].
*
* The element is initialized with the speicifed [init] function.
*/
public fun Document.createElement(name: String, init: Element.() -> Unit): Element = createElement(name).apply(init)
/**
* Appends a newly created element with the specified [name] to this element.
*
* The element is initialized with the speicifed [init] function.
*/
public fun Element.appendElement(name: String, init: Element.() -> Unit): Element =
ownerDocument!!.createElement(name, init).also { appendChild(it) }
@@ -0,0 +1,59 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.dom
import org.w3c.dom.*
/** Returns true if the element has the given CSS class style in its 'class' attribute */
fun Element.hasClass(cssClass: String): Boolean = className.matches("""(^|.*\s+)$cssClass($|\s+.*)""".toRegex())
/**
* Adds CSS class to element. Has no effect if all specified classes are already in class attribute of the element
*
* @return true if at least one class has been added
*/
fun Element.addClass(vararg cssClasses: String): Boolean {
val missingClasses = cssClasses.filterNot { hasClass(it) }
if (missingClasses.isNotEmpty()) {
val presentClasses = className.trim()
className = buildString {
append(presentClasses)
if (!presentClasses.isEmpty()) {
append(" ")
}
missingClasses.joinTo(this, " ")
}
return true
}
return false
}
/**
* Removes all [cssClasses] from element. Has no effect if all specified classes are missing in class attribute of the element
*
* @return true if at least one class has been removed
*/
fun Element.removeClass(vararg cssClasses: String): Boolean {
if (cssClasses.any { hasClass(it) }) {
val toBeRemoved = cssClasses.toSet()
className = className.trim().split("\\s+".toRegex()).filter { it !in toBeRemoved }.joinToString(" ")
return true
}
return false
}
+33
View File
@@ -0,0 +1,33 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.dom
import org.w3c.dom.*
import kotlin.collections.*
/**
* Gets a value indicating whether this node is a TEXT_NODE or a CDATA_SECTION_NODE.
*/
public val Node.isText: Boolean
get() = nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE
/**
* Gets a value indicating whether this node is an [Element].
*/
public val Node.isElement: Boolean
get() = nodeType == Node.ELEMENT_NODE
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.w3c.dom.events
public fun EventListener(handler: (Event) -> Unit): EventListener = EventListenerHandler(handler)
private class EventListenerHandler(private val handler: (Event) -> Unit) : EventListener {
public override fun handleEvent(e: Event) {
handler(e)
}
public override fun toString(): String = "EventListenerHandler($handler)"
}
@@ -0,0 +1,34 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.w3c.dom
public external interface ItemArrayLike<out T> {
val length: Int
fun item(index: Int): T?
}
/**
* Returns the view of this `ItemArrayLike<T>` collection as `List<T>`
*/
public fun <T> ItemArrayLike<T>.asList(): List<T> = object : AbstractList<T>() {
override val size: Int get() = this@asList.length
override fun get(index: Int): T = when (index) {
in 0..lastIndex -> this@asList.item(index).unsafeCast<T>()
else -> throw IndexOutOfBoundsException("index $index is not in range [0..$lastIndex]")
}
}
@@ -0,0 +1,20 @@
package kotlin.dom
import org.w3c.dom.*
/** Removes all the children from this node. */
public fun Node.clear() {
while (hasChildNodes()) {
removeChild(firstChild!!)
}
}
/**
* Creates text node and append it to the element.
*
* @returns this element
*/
fun Element.appendText(text: String): Element {
appendChild(ownerDocument!!.createTextNode(text))
return this
}
+58
View File
@@ -0,0 +1,58 @@
/*
* Copyright 2010-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js
/**
* Reinterprets this value as a value of the [dynamic type](/docs/reference/dynamic-type.html).
*/
@kotlin.internal.InlineOnly
public inline fun Any?.asDynamic(): dynamic = this
/**
* Reinterprets this value as a value of the specified type [T] without any actual type checking.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Any?.unsafeCast(): @kotlin.internal.NoInfer T = this.asDynamic()
/**
* Reinterprets this `dynamic` value as a value of the specified type [T] without any actual type checking.
*/
@kotlin.internal.DynamicExtension
@JsName("unsafeCastDynamic")
@kotlin.internal.InlineOnly
public inline fun <T> dynamic.unsafeCast(): @kotlin.internal.NoInfer T = this
/**
* Allows to iterate this `dynamic` object in the following cases:
* - when it has an `iterator` function,
* - when it is an array
* - when it is an instance of [kotlin.collections.Iterable]
*/
@kotlin.internal.DynamicExtension
public operator fun dynamic.iterator(): Iterator<dynamic> {
val r: Any? = this
return when {
this["iterator"] != null ->
this["iterator"]()
js("Kotlin").isArrayish(r) ->
r.unsafeCast<Array<*>>().iterator()
else ->
(r as Iterable<*>).iterator()
}
}
@@ -0,0 +1,37 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// a package is omitted to get declarations directly under the module
@JsName("throwNPE")
private fun throwNPE(message: String) {
throw NullPointerException(message)
}
@JsName("throwCCE")
private fun throwCCE() {
throw ClassCastException("Illegal cast")
}
@JsName("throwISE")
private fun throwISE(message: String) {
throw IllegalStateException(message)
}
@JsName("throwUPAE")
private fun throwUPAE(propertyName: String) {
throw UninitializedPropertyAccessException("lateinit property ${propertyName} has not been initialized")
}
@@ -0,0 +1,132 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
// NOTE: Do not author your exceptions as they are written in this file, instead use this template:
/*
public open class MyException : Exception {
constructor() : super()
constructor(message: String?) : super(message)
constructor(message: String?, cause: Throwable?) : super(message, cause)
constructor(cause: Throwable?) : super(cause)
}
*/
// TODO: remove workarounds for KT-22053 from direct Throwable inheritors
// TODO: remove primary constructors, make all secondary KT-22055
@Suppress("USELESS_ELVIS_RIGHT_IS_NULL")
public open class Error(message: String?, cause: Throwable?) : Throwable(message, cause ?: null) {
constructor() : this(null, null) {
Error::class.js.asDynamic().call(this, null, null)
}
constructor(message: String?) : this(message, null) {
Error::class.js.asDynamic().call(this, message, null)
}
constructor(cause: Throwable?) : this(undefined, cause) {
Error::class.js.asDynamic().call(this, undefined, cause)
}
}
@Suppress("USELESS_ELVIS_RIGHT_IS_NULL")
public open class Exception(message: String?, cause: Throwable?) : Throwable(message, cause ?: null) {
constructor() : this(null, null) {
Exception::class.js.asDynamic().call(this, null, null)
}
constructor(message: String?) : this(message, null) {
Exception::class.js.asDynamic().call(this, message, null)
}
constructor(cause: Throwable?) : this(undefined, cause) {
Exception::class.js.asDynamic().call(this, undefined, cause)
}
}
public open class RuntimeException(message: String?, cause: Throwable?) : Exception(message, cause) {
constructor() : this(null, null)
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(undefined, cause)
}
public open class IllegalArgumentException(message: String?, cause: Throwable?) : RuntimeException(message, cause) {
constructor() : this(null, null)
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(undefined, cause)
}
public open class IllegalStateException(message: String?, cause: Throwable?) : RuntimeException(message, cause) {
constructor() : this(null, null)
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(undefined, cause)
}
public open class IndexOutOfBoundsException(message: String?) : RuntimeException(message) {
constructor() : this(null)
}
public open class ConcurrentModificationException(message: String?, cause: Throwable?) : RuntimeException(message, cause) {
constructor() : this(null, null)
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(undefined, cause)
}
public open class UnsupportedOperationException(message: String?, cause: Throwable?) : RuntimeException(message, cause) {
constructor() : this(null, null)
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(undefined, cause)
}
public open class NumberFormatException(message: String?) : IllegalArgumentException(message) {
constructor() : this(null)
}
public open class NullPointerException(message: String?) : RuntimeException(message) {
constructor() : this(null)
}
public open class ClassCastException(message: String?) : RuntimeException(message) {
constructor() : this(null)
}
public open class AssertionError private constructor(message: String?, cause: Throwable?) : Error(message, cause) {
constructor() : this(null)
constructor(message: String?) : this(message, null)
constructor(message: Any?) : this(message.toString(), message as? Throwable)
}
public open class NoSuchElementException(message: String?) : RuntimeException(message) {
constructor() : this(null)
}
public open class NoWhenBranchMatchedException(message: String?, cause: Throwable?) : RuntimeException(message, cause) {
constructor() : this(null, null)
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(undefined, cause)
}
public open class UninitializedPropertyAccessException(message: String?, cause: Throwable?) : RuntimeException(message, cause) {
constructor() : this(null, null)
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(undefined, cause)
}
@@ -0,0 +1,36 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
/**
* Groups elements from the [Grouping] source by key and counts elements in each group.
*
* @return a [Map] associating the key of each group with the count of element in the group.
*/
@SinceKotlin("1.1")
public fun <T, K> Grouping<T, K>.eachCount(): Map<K, Int> =
fold(0) { acc, _ -> acc + 1 }
/**
/**
* Groups elements from the [Grouping] source by key and sums values provided by the [valueSelector] function for elements in each group.
*
* @return a [Map] associating the key of each group with the count of element in the group.
*/
@SinceKotlin("1.1")
public inline fun <T, K> Grouping<T, K>.eachSumOf(valueSelector: (T) -> Int): Map<K, Int> =
fold(0) { acc, e -> acc + valueSelector(e) }
*/
+20
View File
@@ -0,0 +1,20 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.io
// temporary for shared code, until we have an annotation like JvmSerializable
internal interface Serializable
+98
View File
@@ -0,0 +1,98 @@
package kotlin.js
/**
* Exposes the JavaScript [Math object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) to Kotlin.
*/
@Deprecated("Use top-level functions from kotlin.math package instead.")
public external object Math {
@Deprecated("Use kotlin.math.PI instead.", ReplaceWith("PI", "kotlin.math.PI"))
public val PI: Double
public fun random(): Double
@Deprecated("Use kotlin.math.abs instead.", ReplaceWith("abs(value)", "kotlin.math.abs"))
public fun abs(value: Double): Double
@Deprecated("Use kotlin.math.acos instead.", ReplaceWith("acos(value)", "kotlin.math.acos"))
public fun acos(value: Double): Double
@Deprecated("Use kotlin.math.asin instead.", ReplaceWith("asin(value)", "kotlin.math.asin"))
public fun asin(value: Double): Double
@Deprecated("Use kotlin.math.atan instead.", ReplaceWith("atan(value)", "kotlin.math.atan"))
public fun atan(value: Double): Double
@Deprecated("Use kotlin.math.atan2 instead.", ReplaceWith("atan2(y, x)", "kotlin.math.atan2"))
public fun atan2(y: Double, x: Double): Double
@Deprecated("Use kotlin.math.cos instead.", ReplaceWith("cos(value)", "kotlin.math.cos"))
public fun cos(value: Double): Double
@Deprecated("Use kotlin.math.sin instead.", ReplaceWith("sin(value)", "kotlin.math.sin"))
public fun sin(value: Double): Double
@Deprecated("Use kotlin.math.exp instead.", ReplaceWith("exp(value)", "kotlin.math.exp"))
public fun exp(value: Double): Double
@Deprecated("Use maxOf or kotlin.math.max instead")
public fun max(vararg values: Int): Int
@Deprecated("Use maxOf or kotlin.math.max instead")
public fun max(vararg values: Float): Float
@Deprecated("Use maxOf or kotlin.math.max instead")
public fun max(vararg values: Double): Double
@Deprecated("Use minOf or kotlin.math.min instead")
public fun min(vararg values: Int): Int
@Deprecated("Use minOf or kotlin.math.min instead")
public fun min(vararg values: Float): Float
@Deprecated("Use minOf or kotlin.math.min instead")
public fun min(vararg values: Double): Double
@Deprecated("Use kotlin.math.sqrt instead.", ReplaceWith("sqrt(value)", "kotlin.math.sqrt"))
public fun sqrt(value: Double): Double
@Deprecated("Use kotlin.math.tan instead.", ReplaceWith("tan(value)", "kotlin.math.tan"))
public fun tan(value: Double): Double
@Deprecated("Use kotlin.math.log instead.", ReplaceWith("log(value)", "kotlin.math.log"))
public fun log(value: Double): Double
@Deprecated("Use kotlin.math.pow instead.", ReplaceWith("pow(base, exp)", "kotlin.math.pow"))
public fun pow(base: Double, exp: Double): Double
@Deprecated("Use kotlin.math.round instead.", ReplaceWith("round(value)", "kotlin.math.round"))
public fun round(value: Number): Int
@Deprecated("Use kotlin.math.floor instead.", ReplaceWith("floor(value)", "kotlin.math.floor"))
public fun floor(value: Number): Int
@Deprecated("Use kotlin.math.ceil instead.", ReplaceWith("ceil(value)", "kotlin.math.ceil"))
public fun ceil(value: Number): Int
@PublishedApi
internal fun trunc(value: Number): Double
@PublishedApi
internal fun sign(value: Number): Double
@PublishedApi
internal fun sinh(value: Double): Double
@PublishedApi
internal fun cosh(value: Double): Double
@PublishedApi
internal fun tanh(value: Double): Double
@PublishedApi
internal fun asinh(value: Double): Double
@PublishedApi
internal fun acosh(value: Double): Double
@PublishedApi
internal fun atanh(value: Double): Double
@PublishedApi
internal fun hypot(x: Double, y: Double): Double
@PublishedApi
internal fun expm1(value: Double): Double
@PublishedApi
internal fun log10(value: Double): Double
@PublishedApi
internal fun log2(value: Double): Double
@PublishedApi
internal fun log1p(value: Double): Double
}
/**
* Returns the smaller of two values.
*/
@Suppress("DEPRECATION")
@Deprecated("Use minOf or kotlin.math.min instead", ReplaceWith("minOf(a, b)"))
public fun Math.min(a: Long, b: Long): Long = if (a <= b) a else b
/**
* Returns the greater of two values.
*/
@Suppress("DEPRECATION")
@Deprecated("Use maxOf or kotlin.math.max instead", ReplaceWith("maxOf(a, b)"))
public fun Math.max(a: Long, b: Long): Long = if (a >= b) a else b
+86
View File
@@ -0,0 +1,86 @@
package kotlin.js
/**
* An interface for indexing access to a collection of key-value pairs, where type of key is [String] and type of value is [Any?][Any].
*/
public external interface Json {
/**
* Calls to the function will be translated to indexing operation (square brackets) on the receiver with [propertyName] as the argument.
*
* E.g. for next code:
* ```kotlin
* fun test(j: Json, p: String) = j["prop"] + j.get(p)
* ```
*
* will be generated:
* ```js
* function test(j, p) {
* return j["prop"] + j[p];
* }
* ```
*/
operator fun get(propertyName: String): Any?
/**
* Calls of the function will be translated to an assignment of [value] to the receiver indexed (with square brackets/index operation) with [propertyName].
*
* E.g. for the following code:
* ```kotlin
* fun test(j: Json, p: String, newValue: Any) {
* j["prop"] = 1
* j.set(p, newValue)
* }
* ```
*
* will be generated:
* ```js
* function test(j, p, newValue) {
* j["prop"] = 1;
* j[p] = newValue;
* }
* }
* ```
*/
operator fun set(propertyName: String, value: Any?): Unit
}
/**
* Returns a simple JavaScript object (as [Json]) using provided key-value pairs as names and values of its properties.
*/
public fun json(vararg pairs: Pair<String, Any?>): Json {
val res: dynamic = js("({})")
for ((name, value) in pairs) {
res[name] = value
}
return res
}
/**
* Adds key-value pairs from [other] to [this].
* Returns the original receiver.
*/
public fun Json.add(other: Json): Json {
val keys: Array<String> = js("Object").keys(other)
for (key in keys) {
if (other.asDynamic().hasOwnProperty(key)) {
this[key] = other[key];
}
}
return this
}
/**
* Exposes the JavaScript [JSON object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) to Kotlin.
*/
public external object JSON {
public fun stringify(o: Any?): String
public fun stringify(o: Any?, replacer: ((key: String, value: Any?) -> Any?)): String
public fun stringify(o: Any?, replacer: ((key: String, value: Any?) -> Any?)? = definedExternally, space: Int): String
public fun stringify(o: Any?, replacer: ((key: String, value: Any?) -> Any?)? = definedExternally, space: String): String
public fun stringify(o: Any?, replacer: Array<String>): String
public fun stringify(o: Any?, replacer: Array<String>, space: Int): String
public fun stringify(o: Any?, replacer: Array<String>, space: String): String
public fun <T> parse(text: String): T
public fun <T> parse(text: String, reviver: ((key: String, value: Any?) -> Any?)): T
}
+111
View File
@@ -0,0 +1,111 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UNUSED_PARAMETER", "NOTHING_TO_INLINE")
package kotlin
/**
* Returns an empty array of the specified type [T].
*/
public inline fun <T> emptyArray(): Array<T> = js("[]")
@library
public fun <T> arrayOf(vararg elements: T): Array<T> = definedExternally
@library
public fun doubleArrayOf(vararg elements: Double): DoubleArray = definedExternally
@library
public fun floatArrayOf(vararg elements: Float): FloatArray = definedExternally
@library
public fun longArrayOf(vararg elements: Long): LongArray = definedExternally
@library
public fun intArrayOf(vararg elements: Int): IntArray = definedExternally
@library
public fun charArrayOf(vararg elements: Char): CharArray = definedExternally
@library
public fun shortArrayOf(vararg elements: Short): ShortArray = definedExternally
@library
public fun byteArrayOf(vararg elements: Byte): ByteArray = definedExternally
@library
public fun booleanArrayOf(vararg elements: Boolean): BooleanArray = definedExternally
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer].
*/
public fun <T> lazy(initializer: () -> T): Lazy<T> = UnsafeLazyImpl(initializer)
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer].
*
* The [mode] parameter is ignored. */
public fun <T> lazy(mode: LazyThreadSafetyMode, initializer: () -> T): Lazy<T> = UnsafeLazyImpl(initializer)
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer].
*
* The [lock] parameter is ignored.
*/
public fun <T> lazy(lock: Any?, initializer: () -> T): Lazy<T> = UnsafeLazyImpl(initializer)
internal fun fillFrom(src: dynamic, dst: dynamic): dynamic {
val srcLen: Int = src.length
val dstLen: Int = dst.length
var index: Int = 0
while (index < srcLen && index < dstLen) dst[index] = src[index++]
return dst
}
internal fun arrayCopyResize(source: dynamic, newSize: Int, defaultValue: Any?): dynamic {
val result = source.slice(0, newSize)
copyArrayType(source, result)
var index: Int = source.length
if (newSize > index) {
result.length = newSize
while (index < newSize) result[index++] = defaultValue
}
return result
}
internal fun <T> arrayPlusCollection(array: dynamic, collection: Collection<T>): dynamic {
val result = array.slice()
result.length += collection.size
copyArrayType(array, result)
var index: Int = array.length
for (element in collection) result[index++] = element
return result
}
internal fun <T> fillFromCollection(dst: dynamic, startIndex: Int, collection: Collection<T>): dynamic {
var index = startIndex
for (element in collection) dst[index++] = element
return dst
}
internal inline fun copyArrayType(from: dynamic, to: dynamic) {
if (from.`$type$` !== undefined) {
to.`$type$` = from.`$type$`
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,134 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.text
/**
* Returns `true` if the contents of this string is equal to the word "true", ignoring case, and `false` otherwise.
*/
public fun String.toBoolean(): Boolean = toLowerCase() == "true"
/**
* Parses the string as a signed [Byte] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
public fun String.toByte(): Byte = toByteOrNull() ?: numberFormatError(this)
/**
* Parses the string as a signed [Byte] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
public fun String.toByte(radix: Int): Byte = toByteOrNull(radix) ?: numberFormatError(this)
/**
* Parses the string as a [Short] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
public fun String.toShort(): Short = toShortOrNull() ?: numberFormatError(this)
/**
* Parses the string as a [Short] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
public fun String.toShort(radix: Int): Short = toShortOrNull(radix) ?: numberFormatError(this)
/**
* Parses the string as an [Int] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
public fun String.toInt(): Int = toIntOrNull() ?: numberFormatError(this)
/**
* Parses the string as an [Int] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
public fun String.toInt(radix: Int): Int = toIntOrNull(radix) ?: numberFormatError(this)
/**
* Parses the string as a [Long] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
public fun String.toLong(): Long = toLongOrNull() ?: numberFormatError(this)
/**
* Parses the string as a [Long] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
public fun String.toLong(radix: Int): Long = toLongOrNull(radix) ?: numberFormatError(this)
/**
* Parses the string as a [Double] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
public fun String.toDouble(): Double = (+(this.asDynamic())).unsafeCast<Double>().also {
if (it.isNaN() && !this.isNaN() || it == 0.0 && this.isBlank())
numberFormatError(this)
}
/**
* Parses the string as a [Float] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.internal.InlineOnly
public inline fun String.toFloat(): Float = toDouble().unsafeCast<Float>()
/**
* Parses the string as a [Double] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
public fun String.toDoubleOrNull(): Double? = (+(this.asDynamic())).unsafeCast<Double>().takeIf {
!(it.isNaN() && !this.isNaN() || it == 0.0 && this.isBlank())
}
/**
* Parses the string as a [Float] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@kotlin.internal.InlineOnly
public inline fun String.toFloatOrNull(): Float? = toDoubleOrNull().unsafeCast<Float?>()
private fun String.isNaN(): Boolean = when(this.toLowerCase()) {
"nan", "+nan", "-nan" -> true
else -> false
}
/**
* Checks whether the given [radix] is valid radix for string to number and number to string conversion.
*/
@PublishedApi
internal fun checkRadix(radix: Int): Int {
if(radix !in 2..36) {
throw IllegalArgumentException("radix $radix was not in valid range 2..36")
}
return radix
}
internal fun digitOf(char: Char, radix: Int): Int = when {
char >= '0' && char <= '9' -> char - '0'
char >= 'A' && char <= 'Z' -> char - 'A' + 10
char >= 'a' && char <= 'z' -> char - 'a' + 10
else -> -1
}.let { if (it >= radix) -1 else it }
private fun numberFormatError(input: String): Nothing = throw NumberFormatException("Invalid number format: '$input'")
+87
View File
@@ -0,0 +1,87 @@
package kotlin
/**
* Returns `true` if the specified number is a
* Not-a-Number (NaN) value, `false` otherwise.
*/
public fun Double.isNaN(): Boolean = this != this
/**
* Returns `true` if the specified number is a
* Not-a-Number (NaN) value, `false` otherwise.
*/
public fun Float.isNaN(): Boolean = this != this
/**
* Returns `true` if this value is infinitely large in magnitude.
*/
public fun Double.isInfinite(): Boolean = this == Double.POSITIVE_INFINITY || this == Double.NEGATIVE_INFINITY
/**
* Returns `true` if this value is infinitely large in magnitude.
*/
public fun Float.isInfinite(): Boolean = this == Float.POSITIVE_INFINITY || this == Float.NEGATIVE_INFINITY
/**
* Returns `true` if the argument is a finite floating-point value; returns `false` otherwise (for `NaN` and infinity arguments).
*/
public fun Double.isFinite(): Boolean = !isInfinite() && !isNaN()
/**
* Returns `true` if the argument is a finite floating-point value; returns `false` otherwise (for `NaN` and infinity arguments).
*/
public fun Float.isFinite(): Boolean = !isInfinite() && !isNaN()
/**
* Returns a bit representation of the specified floating-point value as [Long]
* according to the IEEE 754 floating-point "double format" bit layout.
*/
@SinceKotlin("1.2")
@library("doubleToBits")
public fun Double.toBits(): Long = definedExternally
/**
* Returns a bit representation of the specified floating-point value as [Long]
* according to the IEEE 754 floating-point "double format" bit layout,
* preserving `NaN` values exact layout.
*/
@SinceKotlin("1.2")
@library("doubleToRawBits")
public fun Double.toRawBits(): Long = definedExternally
/**
* Returns the [Double] value corresponding to a given bit representation.
*/
@SinceKotlin("1.2")
@kotlin.internal.InlineOnly
public inline fun Double.Companion.fromBits(bits: Long): Double = js("Kotlin").doubleFromBits(bits).unsafeCast<Double>()
/**
* Returns a bit representation of the specified floating-point value as [Int]
* according to the IEEE 754 floating-point "single format" bit layout.
*
* Note that in Kotlin/JS [Float] range is wider than "single format" bit layout can represent,
* so some [Float] values may overflow, underflow or loose their accuracy after conversion to bits and back.
*/
@SinceKotlin("1.2")
@library("floatToBits")
public fun Float.toBits(): Int = definedExternally
/**
* Returns a bit representation of the specified floating-point value as [Int]
* according to the IEEE 754 floating-point "single format" bit layout,
* preserving `NaN` values exact layout.
*
* Note that in Kotlin/JS [Float] range is wider than "single format" bit layout can represent,
* so some [Float] values may overflow, underflow or loose their accuracy after conversion to bits and back.
*/
@SinceKotlin("1.2")
@library("floatToRawBits")
public fun Float.toRawBits(): Int = definedExternally
/**
* Returns the [Float] value corresponding to a given bit representation.
*/
@SinceKotlin("1.2")
@kotlin.internal.InlineOnly
public inline fun Float.Companion.fromBits(bits: Int): Float = js("Kotlin").floatFromBits(bits).unsafeCast<Float>()
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js
import kotlin.internal.LowPriorityInOverloadResolution
/**
* Exposes the JavaScript [Promise object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) to Kotlin.
*/
public open external class Promise<out T>(executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit) {
@LowPriorityInOverloadResolution
public open fun <S> then(onFulfilled: ((T) -> S)?): Promise<S>
@LowPriorityInOverloadResolution
public open fun <S> then(onFulfilled: ((T) -> S)?, onRejected: ((Throwable) -> S)?): Promise<S>
public open fun <S> catch(onRejected: (Throwable) -> S): Promise<S>
companion object {
public fun <S> all(promise: Array<out Promise<S>>): Promise<Array<out S>>
public fun <S> race(promise: Array<out Promise<S>>): Promise<S>
public fun reject(e: Throwable): Promise<Nothing>
public fun <S> resolve(e: S): Promise<S>
public fun <S> resolve(e: Promise<S>): Promise<S>
}
}
// It's workaround for KT-19672 since we can fix it properly until KT-11265 isn't fixed.
inline fun <T, S> Promise<Promise<T>>.then(
noinline onFulfilled: ((T) -> S)?
): Promise<S> {
return this.unsafeCast<Promise<T>>().then(onFulfilled)
}
inline fun <T, S> Promise<Promise<T>>.then(
noinline onFulfilled: ((T) -> S)?,
noinline onRejected: ((Throwable) -> S)?
): Promise<S> {
return this.unsafeCast<Promise<T>>().then(onFulfilled, onRejected)
}
+22
View File
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.ranges
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline operator fun Float.rangeTo(that: Float): ClosedFloatingPointRange<Float> =
this.toDouble().rangeTo(that.toDouble()).unsafeCast<ClosedFloatingPointRange<Float>>()
@@ -0,0 +1,55 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js
import getKClass
import kotlin.reflect.KClass
import kotlin.reflect.js.internal.KClassImpl
/**
* Represents the constructor of a class. Instances of `JsClass` can be passed to JavaScript APIs that expect a constructor reference.
*/
external interface JsClass<T : Any> {
/**
* Returns the unqualified name of the class represented by this instance.
*/
val name: String
}
@Deprecated("Use class literal and extension property `js` instead.", replaceWith = ReplaceWith("T::class.js"), level = DeprecationLevel.WARNING)
external fun <T : Any> jsClass(): JsClass<T>
@Deprecated("Use class literal and extension property `js` instead.", replaceWith = ReplaceWith("this::class.js"), level = DeprecationLevel.WARNING)
val <T : Any> T.jsClass: JsClass<T>
get() = when (jsTypeOf(this)) {
"string" -> js("String")
"number" -> js("Number")
"boolean" -> js("Boolean")
else -> js("Object").getPrototypeOf(this).constructor
}
/**
* Obtains a constructor reference for the given `KClass`.
*/
val <T : Any> KClass<T>.js: JsClass<T>
get() = (this as KClassImpl<T>).jClass
/**
* Obtains a `KClass` instance for the given constructor reference.
*/
val <T : Any> JsClass<T>.kotlin: KClass<T>
get() = getKClass(this)
@@ -0,0 +1,106 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.reflect.js.internal
import kotlin.reflect.*
internal abstract class KClassImpl<T : Any>(
internal open val jClass: JsClass<T>
) : KClass<T> {
override val annotations: List<Annotation>
get() = TODO()
override val constructors: Collection<KFunction<T>>
get() = TODO()
override val isAbstract: Boolean
get() = TODO()
override val isCompanion: Boolean
get() = TODO()
override val isData: Boolean
get() = TODO()
override val isFinal: Boolean
get() = TODO()
override val isInner: Boolean
get() = TODO()
override val isOpen: Boolean
get() = TODO()
override val isSealed: Boolean
get() = TODO()
override val members: Collection<KCallable<*>>
get() = TODO()
override val nestedClasses: Collection<KClass<*>>
get() = TODO()
override val objectInstance: T?
get() = TODO()
override val qualifiedName: String?
get() = TODO()
override val supertypes: List<KType>
get() = TODO()
override val typeParameters: List<KTypeParameter>
get() = TODO()
override val visibility: KVisibility?
get() = TODO()
override fun equals(other: Any?): Boolean {
return other is KClassImpl<*> && jClass == other.jClass
}
// TODO: use FQN
override fun hashCode(): Int = simpleName?.hashCode() ?: 0
override fun toString(): String {
// TODO: use FQN
return "class $simpleName"
}
}
internal class SimpleKClassImpl<T : Any>(jClass: JsClass<T>) : KClassImpl<T>(jClass) {
override val simpleName: String? = jClass.asDynamic().`$metadata$`?.simpleName.unsafeCast<String?>()
override fun isInstance(value: Any?): Boolean {
return js("Kotlin").isType(value, jClass)
}
}
internal class PrimitiveKClassImpl<T : Any>(
jClass: JsClass<T>,
private val givenSimpleName: String,
private val isInstanceFunction: (Any?) -> Boolean
) : KClassImpl<T>(jClass) {
override fun equals(other: Any?): Boolean {
if (other !is PrimitiveKClassImpl<*>) return false
return super.equals(other) && givenSimpleName == other.givenSimpleName
}
override val simpleName: String? get() = givenSimpleName
override fun isInstance(value: Any?): Boolean {
return isInstanceFunction(value)
}
}
internal object NothingKClassImpl : KClassImpl<Nothing>(js("Object")) {
override val simpleName: String = "Nothing"
override fun isInstance(value: Any?): Boolean = false
override val jClass: JsClass<Nothing>
get() = throw UnsupportedOperationException("There's no native JS class for Nothing type")
override fun equals(other: Any?): Boolean = other === this
override fun hashCode(): Int = 0
}
@@ -0,0 +1,94 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.reflect.js.internal
import kotlin.js.JsClass
@JsName("PrimitiveClasses")
internal object PrimitiveClasses {
@JsName("anyClass")
val anyClass = PrimitiveKClassImpl(js("Object").unsafeCast<JsClass<Any>>(), "Any", { it is Any })
@JsName("numberClass")
val numberClass = PrimitiveKClassImpl(js("Number").unsafeCast<JsClass<Number>>(), "Number", { it is Number })
@JsName("nothingClass")
val nothingClass = NothingKClassImpl
@JsName("booleanClass")
val booleanClass = PrimitiveKClassImpl(js("Boolean").unsafeCast<JsClass<Boolean>>(), "Boolean", { it is Boolean })
@JsName("byteClass")
val byteClass = PrimitiveKClassImpl(js("Number").unsafeCast<JsClass<Byte>>(), "Byte", { it is Byte })
@JsName("shortClass")
val shortClass = PrimitiveKClassImpl(js("Number").unsafeCast<JsClass<Short>>(), "Short", { it is Short })
@JsName("intClass")
val intClass = PrimitiveKClassImpl(js("Number").unsafeCast<JsClass<Int>>(), "Int", { it is Int })
@JsName("floatClass")
val floatClass = PrimitiveKClassImpl(js("Number").unsafeCast<JsClass<Float>>(), "Float", { it is Float })
@JsName("doubleClass")
val doubleClass = PrimitiveKClassImpl(js("Number").unsafeCast<JsClass<Double>>(), "Double", { it is Double })
@JsName("arrayClass")
val arrayClass = PrimitiveKClassImpl(js("Array").unsafeCast<JsClass<Array<*>>>(), "Array", { it is Array<*> })
@JsName("stringClass")
val stringClass = PrimitiveKClassImpl(js("String").unsafeCast<JsClass<String>>(), "String", { it is String })
@JsName("throwableClass")
val throwableClass = PrimitiveKClassImpl(js("Error").unsafeCast<JsClass<Throwable>>(), "Throwable", { it is Throwable })
@JsName("booleanArrayClass")
val booleanArrayClass = PrimitiveKClassImpl(js("Array").unsafeCast<JsClass<BooleanArray>>(), "BooleanArray", { it is BooleanArray })
@JsName("charArrayClass")
val charArrayClass = PrimitiveKClassImpl(js("Uint16Array").unsafeCast<JsClass<CharArray>>(), "CharArray", { it is CharArray })
@JsName("byteArrayClass")
val byteArrayClass = PrimitiveKClassImpl(js("Int8Array").unsafeCast<JsClass<ByteArray>>(), "ByteArray", { it is ByteArray })
@JsName("shortArrayClass")
val shortArrayClass = PrimitiveKClassImpl(js("Int16Array").unsafeCast<JsClass<ShortArray>>(), "ShortArray", { it is ShortArray })
@JsName("intArrayClass")
val intArrayClass = PrimitiveKClassImpl(js("Int32Array").unsafeCast<JsClass<IntArray>>(), "IntArray", { it is IntArray })
@JsName("longArrayClass")
val longArrayClass = PrimitiveKClassImpl(js("Array").unsafeCast<JsClass<LongArray>>(), "LongArray", { it is LongArray })
@JsName("floatArrayClass")
val floatArrayClass = PrimitiveKClassImpl(js("Float32Array").unsafeCast<JsClass<FloatArray>>(), "FloatArray", { it is FloatArray })
@JsName("doubleArrayClass")
val doubleArrayClass = PrimitiveKClassImpl(js("Float64Array").unsafeCast<JsClass<DoubleArray>>(), "DoubleArray", { it is DoubleArray })
@JsName("functionClass")
fun functionClass(arity: Int): KClassImpl<Any> {
return functionClasses.get(arity) ?: run {
val result = PrimitiveKClassImpl(js("Function").unsafeCast<JsClass<Any>>(), "Function$arity",
{ jsTypeOf(it) === "function" && it.asDynamic().length == arity })
functionClasses.asDynamic()[arity] = result
result
}
}
}
private val functionClasses = arrayOfNulls<KClassImpl<Any>>(0)
@@ -0,0 +1,77 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// a package is omitted to get declarations directly under the module
import kotlin.reflect.KClass
import kotlin.reflect.js.internal.*
@JsName("getKClass")
internal fun <T : Any> getKClass(jClass: JsClass<T>): KClass<T> = getOrCreateKClass(jClass)
@JsName("getKClassFromExpression")
internal fun <T : Any> getKClassFromExpression(e: T): KClass<T> =
when (jsTypeOf(e)) {
"string" -> PrimitiveClasses.stringClass
"number" -> if (js("e | 0") === e) PrimitiveClasses.intClass else PrimitiveClasses.doubleClass
"boolean" -> PrimitiveClasses.booleanClass
"function" -> PrimitiveClasses.functionClass(e.asDynamic().length)
else -> {
when {
e is BooleanArray -> PrimitiveClasses.booleanArrayClass
e is CharArray -> PrimitiveClasses.charArrayClass
e is ByteArray -> PrimitiveClasses.byteArrayClass
e is ShortArray -> PrimitiveClasses.shortArrayClass
e is IntArray -> PrimitiveClasses.intArrayClass
e is LongArray -> PrimitiveClasses.longArrayClass
e is FloatArray -> PrimitiveClasses.floatArrayClass
e is DoubleArray -> PrimitiveClasses.doubleArrayClass
e is KClass<*> -> KClass::class
e is Array<*> -> PrimitiveClasses.arrayClass
else -> {
val constructor = js("Object").getPrototypeOf(e).constructor
when {
constructor === js("Object") -> PrimitiveClasses.anyClass
constructor === js("Error") -> PrimitiveClasses.throwableClass
else -> {
val jsClass: JsClass<T> = constructor
getOrCreateKClass(jsClass)
}
}
}
}
}
}.unsafeCast<KClass<T>>()
private fun <T : Any> getOrCreateKClass(jClass: JsClass<T>): KClass<T> {
if (jClass === js("String")) return PrimitiveClasses.stringClass.unsafeCast<KClass<T>>()
val metadata = jClass.asDynamic().`$metadata$`
return if (metadata != null) {
if (metadata.`$kClass$` == null) {
val kClass = SimpleKClassImpl(jClass)
metadata.`$kClass$` = kClass
kClass
}
else {
metadata.`$kClass$`
}
}
else {
SimpleKClassImpl(jClass)
}
}
+225
View File
@@ -0,0 +1,225 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.text
import kotlin.js.RegExp
/**
* Provides enumeration values to use to set regular expression options.
*/
public enum class RegexOption(val value: String) {
/** Enables case-insensitive matching. */
IGNORE_CASE("i"),
/** Enables multiline mode.
*
* In multiline mode the expressions `^` and `$` match just after or just before,
* respectively, a line terminator or the end of the input sequence. */
MULTILINE("m")
}
/**
* Represents the results from a single capturing group within a [MatchResult] of [Regex].
*
* @param value The value of captured group.
*/
public data class MatchGroup(val value: String)
/** A compiled representation of a regular expression.
*
* For pattern syntax reference see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp] and [http://www.w3schools.com/jsref/jsref_obj_regexp.asp]
*/
public class Regex(pattern: String, options: Set<RegexOption>) {
/** Creates a regular expression from the specified [pattern] string and the specified single [option]. */
public constructor(pattern: String, option: RegexOption) : this(pattern, setOf(option))
/** Creates a regular expression from the specified [pattern] string and the default options. */
public constructor(pattern: String) : this(pattern, emptySet())
/** The pattern string of this regular expression. */
public val pattern: String = pattern
/** The set of options that were used to create this regular expression. */
public val options: Set<RegexOption> = options.toSet()
private val nativePattern: RegExp = RegExp(pattern, options.map { it.value }.joinToString(separator = "") + "g")
/** Indicates whether the regular expression matches the entire [input]. */
public infix fun matches(input: CharSequence): Boolean {
nativePattern.reset()
val match = nativePattern.exec(input.toString())
return match != null && match.index == 0 && nativePattern.lastIndex == input.length
}
/** Indicates whether the regular expression can find at least one match in the specified [input]. */
public fun containsMatchIn(input: CharSequence): Boolean {
nativePattern.reset()
return nativePattern.test(input.toString())
}
/** Returns the first match of a regular expression in the [input], beginning at the specified [startIndex].
*
* @param startIndex An index to start search with, by default 0. Must be not less than zero and not greater than `input.length()`
* @return An instance of [MatchResult] if match was found or `null` otherwise.
*/
public fun find(input: CharSequence, startIndex: Int = 0): MatchResult? = nativePattern.findNext(input.toString(), startIndex)
/** Returns a sequence of all occurrences of a regular expression within the [input] string, beginning at the specified [startIndex].
*/
public fun findAll(input: CharSequence, startIndex: Int = 0): Sequence<MatchResult> = generateSequence({ find(input, startIndex) }, { match -> match.next() })
/**
* Attempts to match the entire [input] CharSequence against the pattern.
*
* @return An instance of [MatchResult] if the entire input matches or `null` otherwise.
*/
public fun matchEntire(input: CharSequence): MatchResult? {
if (pattern.startsWith('^') && pattern.endsWith('$'))
return find(input)
else
return Regex("^${pattern.trimStart('^').trimEnd('$')}$", options).find(input)
}
/**
* Replaces all occurrences of this regular expression in the specified [input] string with specified [replacement] expression.
*
* @param replacement A replacement expression that can include substitutions. See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace] for details.
*/
public fun replace(input: CharSequence, replacement: String): String = input.toString().nativeReplace(nativePattern, replacement)
/**
* Replaces all occurrences of this regular expression in the specified [input] string with the result of
* the given function [transform] that takes [MatchResult] and returns a string to be used as a
* replacement for that match.
*/
public inline fun replace(input: CharSequence, transform: (MatchResult) -> CharSequence): String {
var match = find(input)
if (match == null) return input.toString()
var lastStart = 0
val length = input.length
val sb = StringBuilder(length)
do {
val foundMatch = match!!
sb.append(input, lastStart, foundMatch.range.start)
sb.append(transform(foundMatch))
lastStart = foundMatch.range.endInclusive + 1
match = foundMatch.next()
}
while (lastStart < length && match != null)
if (lastStart < length) {
sb.append(input, lastStart, length)
}
return sb.toString()
}
/**
* Replaces the first occurrence of this regular expression in the specified [input] string with specified [replacement] expression.
*
* @param replacement A replacement expression that can include substitutions. See [Matcher.appendReplacement] for details.
*/
public fun replaceFirst(input: CharSequence, replacement: String): String {
val nonGlobalOptions = options.map { it.value }.joinToString(separator = "")
return input.toString().nativeReplace(RegExp(pattern, nonGlobalOptions), replacement)
}
/**
* Splits this string around matches of the given regular expression.
*
* @param limit The maximum number of times the split can occur.
*/
public fun split(input: CharSequence, limit: Int = 0): List<String> {
require(limit >= 0) { "Limit must be non-negative, but was $limit" }
val matches = findAll(input).let { if (limit == 0) it else it.take(limit - 1) }
val result = mutableListOf<String>()
var lastStart = 0
for (match in matches) {
result.add(input.subSequence(lastStart, match.range.start).toString())
lastStart = match.range.endInclusive + 1
}
result.add(input.subSequence(lastStart, input.length).toString())
return result
}
/** Returns the string representation of this regular expression. */
public override fun toString(): String = nativePattern.toString()
companion object {
/** Returns a literal regex for the specified [literal] string. */
public fun fromLiteral(literal: String): Regex = Regex(escape(literal))
/** Returns a literal pattern for the specified [literal] string. */
public fun escape(literal: String): String = literal.nativeReplace(patternEscape, "\\$&")
/** Returns a literal replacement exression for the specified [literal] string. */
public fun escapeReplacement(literal: String): String = literal.nativeReplace(replacementEscape, "$$$$")
private val patternEscape = RegExp("""[-\\^$*+?.()|[\]{}]""", "g")
private val replacementEscape = RegExp("""\$""", "g")
}
}
/** Creates a regular expression from the specified [pattern] string and the specified single [option]. */
@Deprecated("Provided for binary compatibility", level = DeprecationLevel.HIDDEN)
@JsName("Regex_sb3q2\$")
public fun Regex_0(pattern: String, option: RegexOption): Regex = Regex(pattern, setOf(option))
/** Creates a regular expression from the specified [pattern] string and the default options. */
@Deprecated("Provided for binary compatibility", level = DeprecationLevel.HIDDEN)
@JsName("Regex_61zpoe\$")
public fun Regex_1(pattern: String): Regex = Regex(pattern, emptySet())
private fun RegExp.findNext(input: String, from: Int): MatchResult? {
this.lastIndex = from
val match = exec(input)
if (match == null) return null
val range = match.index..lastIndex - 1
return object : MatchResult {
override val range: IntRange = range
override val value: String
get() = match[0]!!
override val groups: MatchGroupCollection = object : MatchGroupCollection, AbstractCollection<MatchGroup?>() {
override val size: Int get() = match.length
override fun iterator(): Iterator<MatchGroup?> = indices.asSequence().map { this[it] }.iterator()
override fun get(index: Int): MatchGroup? = match[index]?.let { MatchGroup(it) }
}
private var groupValues_: List<String>? = null
override val groupValues: List<String>
get() {
if (groupValues_ == null) {
groupValues_ = object : AbstractList<String>() {
override val size: Int get() = match.length
override fun get(index: Int): String = match[index] ?: ""
}
}
return groupValues_!!
}
override fun next(): MatchResult? = this@findNext.findNext(input, if (range.isEmpty()) range.start + 1 else range.endInclusive + 1)
}
}
+67
View File
@@ -0,0 +1,67 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js
/**
* Exposes the JavaScript [RegExp object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to Kotlin.
*/
public external class RegExp(pattern: String, flags: String? = definedExternally) {
public fun test(str: String): Boolean
public fun exec(str: String): RegExpMatch?
public override fun toString(): String
/**
* The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match.
*/
public var lastIndex: Int
public val global: Boolean
public val ignoreCase: Boolean
public val multiline: Boolean
}
/**
* Resets the regular expression so that subsequent [RegExp.test] and [RegExp.exec] calls will match starting with the beginning of the input string.
*/
public fun RegExp.reset() {
lastIndex = 0
}
// TODO: Inherit from array or introduce asArray() extension
/**
* Represents the return value of [RegExp.exec].
*/
public external interface RegExpMatch {
public val index: Int
public val input: String
public val length: Int
}
/**
* Returns the entire text matched by [RegExp.exec] if the [index] parameter is 0, or the text matched by the capturing parenthesis
* at the given index.
*/
public inline operator fun RegExpMatch.get(index: Int): String? = asDynamic()[index]
/**
* Converts the result of [RegExp.exec] to an array where the first element contains the entire matched text and each subsequent
* element is the text matched by each capturing parenthesis.
*/
public inline fun RegExpMatch.asArray(): Array<out String?> = unsafeCast<Array<out String?>>()
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.sequences
internal class ConstrainedOnceSequence<T>(sequence: Sequence<T>) : Sequence<T> {
private var sequenceRef: Sequence<T>? = sequence
override fun iterator(): Iterator<T> {
val sequence = sequenceRef ?: throw IllegalStateException("This sequence can be consumed only once.")
sequenceRef = null
return sequence.iterator()
}
}
+43
View File
@@ -0,0 +1,43 @@
package kotlin.text
import kotlin.js.RegExp
@kotlin.internal.InlineOnly
public inline fun String.toUpperCase(): String = asDynamic().toUpperCase()
@kotlin.internal.InlineOnly
public inline fun String.toLowerCase(): String = asDynamic().toLowerCase()
@kotlin.internal.InlineOnly
internal inline fun String.nativeIndexOf(str: String, fromIndex: Int): Int = asDynamic().indexOf(str, fromIndex)
@kotlin.internal.InlineOnly
internal inline fun String.nativeLastIndexOf(str: String, fromIndex: Int): Int = asDynamic().lastIndexOf(str, fromIndex)
@kotlin.internal.InlineOnly
internal inline fun String.nativeStartsWith(s: String, position: Int): Boolean = asDynamic().startsWith(s, position)
@kotlin.internal.InlineOnly
internal inline fun String.nativeEndsWith(s: String): Boolean = asDynamic().endsWith(s)
@kotlin.internal.InlineOnly
public inline fun String.substring(startIndex: Int): String = asDynamic().substring(startIndex)
@kotlin.internal.InlineOnly
public inline fun String.substring(startIndex: Int, endIndex: Int): String = asDynamic().substring(startIndex, endIndex)
@kotlin.internal.InlineOnly
public inline fun String.concat(str: String): String = asDynamic().concat(str)
@kotlin.internal.InlineOnly
public inline fun String.match(regex: String): Array<String>? = asDynamic().match(regex)
//native public fun String.trim(): String
//TODO: String.replace to implement effective trimLeading and trimTrailing
@Deprecated("Use length property instead.", ReplaceWith("length"), level = DeprecationLevel.ERROR)
@kotlin.internal.InlineOnly
public inline val CharSequence.size: Int get() = length
@kotlin.internal.InlineOnly
internal inline fun String.nativeReplace(pattern: RegExp, replacement: String): String = asDynamic().replace(pattern, replacement)
@@ -0,0 +1,120 @@
package kotlin.text
import kotlin.js.RegExp
@kotlin.internal.InlineOnly
internal inline fun String.nativeIndexOf(ch: Char, fromIndex: Int): Int = nativeIndexOf(ch.toString(), fromIndex)
@kotlin.internal.InlineOnly
internal inline fun String.nativeLastIndexOf(ch: Char, fromIndex: Int): Int = nativeLastIndexOf(ch.toString(), fromIndex)
/**
* Returns `true` if this string starts with the specified prefix.
*/
public fun String.startsWith(prefix: String, ignoreCase: Boolean = false): Boolean {
if (!ignoreCase)
return nativeStartsWith(prefix, 0)
else
return regionMatches(0, prefix, 0, prefix.length, ignoreCase)
}
/**
* Returns `true` if a substring of this string starting at the specified offset [startIndex] starts with the specified prefix.
*/
public fun String.startsWith(prefix: String, startIndex: Int, ignoreCase: Boolean = false): Boolean {
if (!ignoreCase)
return nativeStartsWith(prefix, startIndex)
else
return regionMatches(startIndex, prefix, 0, prefix.length, ignoreCase)
}
/**
* Returns `true` if this string ends with the specified suffix.
*/
public fun String.endsWith(suffix: String, ignoreCase: Boolean = false): Boolean {
if (!ignoreCase)
return nativeEndsWith(suffix)
else
return regionMatches(length - suffix.length, suffix, 0, suffix.length, ignoreCase)
}
public fun String.matches(regex: String): Boolean {
val result = this.match(regex)
return result != null && result.size != 0
}
public fun CharSequence.isBlank(): Boolean = length == 0 || (if (this is String) this else this.toString()).matches("^[\\s\\xA0]+$")
public fun String?.equals(other: String?, ignoreCase: Boolean = false): Boolean =
if (this == null)
other == null
else if (!ignoreCase)
this == other
else
other != null && this.toLowerCase() == other.toLowerCase()
public fun CharSequence.regionMatches(thisOffset: Int, other: CharSequence, otherOffset: Int, length: Int, ignoreCase: Boolean = false): Boolean
= regionMatchesImpl(thisOffset, other, otherOffset, length, ignoreCase)
/**
* Returns a copy of this string capitalised if it is not empty or already starting with an uppper case letter, otherwise returns this
*
* @includeFunctionBody ../../test/StringTest.kt capitalize
*/
public fun String.capitalize(): String {
return if (isNotEmpty()) substring(0, 1).toUpperCase() + substring(1) else this
}
/**
* Returns a copy of this string with the first letter lower case if it is not empty or already starting with a lower case letter, otherwise returns this
*
* @includeFunctionBody ../../test/StringTest.kt decapitalize
*/
public fun String.decapitalize(): String {
return if (isNotEmpty()) substring(0, 1).toLowerCase() + substring(1) else this
}
/**
* Returns a string containing this char sequence repeated [n] times.
* @throws [IllegalArgumentException] when n < 0.
*/
public fun CharSequence.repeat(n: Int): String {
require(n >= 0) { "Count 'n' must be non-negative, but was $n." }
return when (n) {
0 -> ""
1 -> this.toString()
else -> {
var result = ""
if (!isEmpty()) {
var s = this.toString()
var count = n
while (true) {
if ((count and 1) == 1) {
result += s
}
count = count ushr 1
if (count == 0) {
break
}
s += s
}
}
return result
}
}
}
public fun String.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): String =
nativeReplace(RegExp(Regex.escape(oldValue), if (ignoreCase) "gi" else "g"), Regex.escapeReplacement(newValue))
public fun String.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String =
nativeReplace(RegExp(Regex.escape(oldChar.toString()), if (ignoreCase) "gi" else "g"), newChar.toString())
public fun String.replaceFirst(oldValue: String, newValue: String, ignoreCase: Boolean = false): String =
nativeReplace(RegExp(Regex.escape(oldValue), if (ignoreCase) "i" else ""), Regex.escapeReplacement(newValue))
public fun String.replaceFirst(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String =
nativeReplace(RegExp(Regex.escape(oldChar.toString()), if (ignoreCase) "i" else ""), newChar.toString())
+66
View File
@@ -0,0 +1,66 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.text
public interface Appendable {
fun append(csq: CharSequence?): Appendable
fun append(csq: CharSequence?, start: Int, end: Int): Appendable
fun append(c: Char): Appendable
}
public class StringBuilder(content: String = "") : Appendable, CharSequence {
constructor(@Suppress("UNUSED_PARAMETER") capacity: Int) : this() {}
constructor(content: CharSequence) : this(content.toString()) {}
private var string: String = content
override val length: Int
get() = string.asDynamic().length
override fun get(index: Int): Char = string[index]
override fun subSequence(start: Int, end: Int): CharSequence = string.substring(start, end)
override fun append(c: Char): StringBuilder {
string += c
return this
}
override fun append(csq: CharSequence?): StringBuilder {
string += csq.toString()
return this
}
override fun append(csq: CharSequence?, start: Int, end: Int): StringBuilder {
string += csq.toString().substring(start, end)
return this
}
fun append(obj: Any?): StringBuilder {
string += obj.toString()
return this
}
fun reverse(): StringBuilder {
string = string.asDynamic().split("").reverse().join("")
return this
}
override fun toString(): String = string
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,411 @@
/*
* Generated file
* DO NOT EDIT
*
* See libraries/tools/idl2k for details
*/
@file:Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
package org.w3c.dom.css
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
/**
* Exposes the JavaScript [CSSStyleDeclaration](https://developer.mozilla.org/en/docs/Web/API/CSSStyleDeclaration) to Kotlin
*/
public external abstract class CSSStyleDeclaration : ItemArrayLike<String> {
open var cssText: String
override val length: Int
open val parentRule: CSSRule?
open var cssFloat: String
open var _dashed_attribute: String
open var _camel_cased_attribute: String
open var _webkit_cased_attribute: String
open var alignContent: String
open var alignItems: String
open var alignSelf: String
open var animation: String
open var animationDelay: String
open var animationDirection: String
open var animationDuration: String
open var animationFillMode: String
open var animationIterationCount: String
open var animationName: String
open var animationPlayState: String
open var animationTimingFunction: String
open var backfaceVisibility: String
open var background: String
open var backgroundAttachment: String
open var backgroundClip: String
open var backgroundColor: String
open var backgroundImage: String
open var backgroundOrigin: String
open var backgroundPosition: String
open var backgroundRepeat: String
open var backgroundSize: String
open var border: String
open var borderBottom: String
open var borderBottomColor: String
open var borderBottomLeftRadius: String
open var borderBottomRightRadius: String
open var borderBottomStyle: String
open var borderBottomWidth: String
open var borderCollapse: String
open var borderColor: String
open var borderImage: String
open var borderImageOutset: String
open var borderImageRepeat: String
open var borderImageSlice: String
open var borderImageSource: String
open var borderImageWidth: String
open var borderLeft: String
open var borderLeftColor: String
open var borderLeftStyle: String
open var borderLeftWidth: String
open var borderRadius: String
open var borderRight: String
open var borderRightColor: String
open var borderRightStyle: String
open var borderRightWidth: String
open var borderSpacing: String
open var borderStyle: String
open var borderTop: String
open var borderTopColor: String
open var borderTopLeftRadius: String
open var borderTopRightRadius: String
open var borderTopStyle: String
open var borderTopWidth: String
open var borderWidth: String
open var bottom: String
open var boxDecorationBreak: String
open var boxShadow: String
open var boxSizing: String
open var breakAfter: String
open var breakBefore: String
open var breakInside: String
open var captionSide: String
open var clear: String
open var clip: String
open var color: String
open var columnCount: String
open var columnFill: String
open var columnGap: String
open var columnRule: String
open var columnRuleColor: String
open var columnRuleStyle: String
open var columnRuleWidth: String
open var columnSpan: String
open var columnWidth: String
open var columns: String
open var content: String
open var counterIncrement: String
open var counterReset: String
open var cursor: String
open var direction: String
open var display: String
open var emptyCells: String
open var filter: String
open var flex: String
open var flexBasis: String
open var flexDirection: String
open var flexFlow: String
open var flexGrow: String
open var flexShrink: String
open var flexWrap: String
open var font: String
open var fontFamily: String
open var fontFeatureSettings: String
open var fontKerning: String
open var fontLanguageOverride: String
open var fontSize: String
open var fontSizeAdjust: String
open var fontStretch: String
open var fontStyle: String
open var fontSynthesis: String
open var fontVariant: String
open var fontVariantAlternates: String
open var fontVariantCaps: String
open var fontVariantEastAsian: String
open var fontVariantLigatures: String
open var fontVariantNumeric: String
open var fontVariantPosition: String
open var fontWeight: String
open var hangingPunctuation: String
open var height: String
open var hyphens: String
open var imageOrientation: String
open var imageRendering: String
open var imageResolution: String
open var imeMode: String
open var justifyContent: String
open var left: String
open var letterSpacing: String
open var lineBreak: String
open var lineHeight: String
open var listStyle: String
open var listStyleImage: String
open var listStylePosition: String
open var listStyleType: String
open var margin: String
open var marginBottom: String
open var marginLeft: String
open var marginRight: String
open var marginTop: String
open var mark: String
open var markAfter: String
open var markBefore: String
open var marks: String
open var marqueeDirection: String
open var marqueePlayCount: String
open var marqueeSpeed: String
open var marqueeStyle: String
open var mask: String
open var maskType: String
open var maxHeight: String
open var maxWidth: String
open var minHeight: String
open var minWidth: String
open var navDown: String
open var navIndex: String
open var navLeft: String
open var navRight: String
open var navUp: String
open var objectFit: String
open var objectPosition: String
open var opacity: String
open var order: String
open var orphans: String
open var outline: String
open var outlineColor: String
open var outlineOffset: String
open var outlineStyle: String
open var outlineWidth: String
open var overflowWrap: String
open var overflowX: String
open var overflowY: String
open var padding: String
open var paddingBottom: String
open var paddingLeft: String
open var paddingRight: String
open var paddingTop: String
open var pageBreakAfter: String
open var pageBreakBefore: String
open var pageBreakInside: String
open var perspective: String
open var perspectiveOrigin: String
open var phonemes: String
open var position: String
open var quotes: String
open var resize: String
open var rest: String
open var restAfter: String
open var restBefore: String
open var right: String
open var tabSize: String
open var tableLayout: String
open var textAlign: String
open var textAlignLast: String
open var textCombineUpright: String
open var textDecoration: String
open var textDecorationColor: String
open var textDecorationLine: String
open var textDecorationStyle: String
open var textIndent: String
open var textJustify: String
open var textOrientation: String
open var textOverflow: String
open var textShadow: String
open var textTransform: String
open var textUnderlinePosition: String
open var top: String
open var transform: String
open var transformOrigin: String
open var transformStyle: String
open var transition: String
open var transitionDelay: String
open var transitionDuration: String
open var transitionProperty: String
open var transitionTimingFunction: String
open var unicodeBidi: String
open var verticalAlign: String
open var visibility: String
open var voiceBalance: String
open var voiceDuration: String
open var voicePitch: String
open var voicePitchRange: String
open var voiceRate: String
open var voiceStress: String
open var voiceVolume: String
open var whiteSpace: String
open var widows: String
open var width: String
open var wordBreak: String
open var wordSpacing: String
open var wordWrap: String
open var writingMode: String
open var zIndex: String
override fun item(index: Int): String
fun getPropertyValue(property: String): String
fun getPropertyPriority(property: String): String
fun setProperty(property: String, value: String, priority: String = definedExternally): Unit
fun setPropertyValue(property: String, value: String): Unit
fun setPropertyPriority(property: String, priority: String): Unit
fun removeProperty(property: String): String
}
@kotlin.internal.InlineOnly inline operator fun CSSStyleDeclaration.get(index: Int): String? = asDynamic()[index]
public external abstract class MediaList : ItemArrayLike<String> {
open var mediaText: String
override val length: Int
override fun item(index: Int): String?
fun appendMedium(medium: String): Unit
fun deleteMedium(medium: String): Unit
}
@kotlin.internal.InlineOnly inline operator fun MediaList.get(index: Int): String? = asDynamic()[index]
/**
* Exposes the JavaScript [StyleSheet](https://developer.mozilla.org/en/docs/Web/API/StyleSheet) to Kotlin
*/
public external abstract class StyleSheet {
open val type: String
open val href: String?
open val ownerNode: UnionElementOrProcessingInstruction?
open val parentStyleSheet: StyleSheet?
open val title: String?
open val media: MediaList
open var disabled: Boolean
}
/**
* Exposes the JavaScript [CSSStyleSheet](https://developer.mozilla.org/en/docs/Web/API/CSSStyleSheet) to Kotlin
*/
public external abstract class CSSStyleSheet : StyleSheet {
open val ownerRule: CSSRule?
open val cssRules: CSSRuleList
fun insertRule(rule: String, index: Int): Int
fun deleteRule(index: Int): Unit
}
/**
* Exposes the JavaScript [StyleSheetList](https://developer.mozilla.org/en/docs/Web/API/StyleSheetList) to Kotlin
*/
public external abstract class StyleSheetList : ItemArrayLike<StyleSheet> {
override val length: Int
override fun item(index: Int): StyleSheet?
}
@kotlin.internal.InlineOnly inline operator fun StyleSheetList.get(index: Int): StyleSheet? = asDynamic()[index]
/**
* Exposes the JavaScript [LinkStyle](https://developer.mozilla.org/en/docs/Web/API/LinkStyle) to Kotlin
*/
public external interface LinkStyle {
val sheet: StyleSheet?
}
/**
* Exposes the JavaScript [CSSRuleList](https://developer.mozilla.org/en/docs/Web/API/CSSRuleList) to Kotlin
*/
public external abstract class CSSRuleList : ItemArrayLike<CSSRule> {
override val length: Int
override fun item(index: Int): CSSRule?
}
@kotlin.internal.InlineOnly inline operator fun CSSRuleList.get(index: Int): CSSRule? = asDynamic()[index]
/**
* Exposes the JavaScript [CSSRule](https://developer.mozilla.org/en/docs/Web/API/CSSRule) to Kotlin
*/
public external abstract class CSSRule {
open val type: Short
open var cssText: String
open val parentRule: CSSRule?
open val parentStyleSheet: CSSStyleSheet?
companion object {
val STYLE_RULE: Short
val CHARSET_RULE: Short
val IMPORT_RULE: Short
val MEDIA_RULE: Short
val FONT_FACE_RULE: Short
val PAGE_RULE: Short
val MARGIN_RULE: Short
val NAMESPACE_RULE: Short
}
}
/**
* Exposes the JavaScript [CSSStyleRule](https://developer.mozilla.org/en/docs/Web/API/CSSStyleRule) to Kotlin
*/
public external abstract class CSSStyleRule : CSSRule {
open var selectorText: String
open val style: CSSStyleDeclaration
}
public external abstract class CSSImportRule : CSSRule {
open val href: String
open val media: MediaList
open val styleSheet: CSSStyleSheet
}
/**
* Exposes the JavaScript [CSSGroupingRule](https://developer.mozilla.org/en/docs/Web/API/CSSGroupingRule) to Kotlin
*/
public external abstract class CSSGroupingRule : CSSRule {
open val cssRules: CSSRuleList
fun insertRule(rule: String, index: Int): Int
fun deleteRule(index: Int): Unit
}
/**
* Exposes the JavaScript [CSSMediaRule](https://developer.mozilla.org/en/docs/Web/API/CSSMediaRule) to Kotlin
*/
public external abstract class CSSMediaRule : CSSGroupingRule {
open val media: MediaList
}
/**
* Exposes the JavaScript [CSSPageRule](https://developer.mozilla.org/en/docs/Web/API/CSSPageRule) to Kotlin
*/
public external abstract class CSSPageRule : CSSGroupingRule {
open var selectorText: String
open val style: CSSStyleDeclaration
}
public external abstract class CSSMarginRule : CSSRule {
open val name: String
open val style: CSSStyleDeclaration
}
/**
* Exposes the JavaScript [CSSNamespaceRule](https://developer.mozilla.org/en/docs/Web/API/CSSNamespaceRule) to Kotlin
*/
public external abstract class CSSNamespaceRule : CSSRule {
open val namespaceURI: String
open val prefix: String
}
public external interface ElementCSSInlineStyle {
val style: CSSStyleDeclaration
}
/**
* Exposes the JavaScript [CSS](https://developer.mozilla.org/en/docs/Web/API/CSS) to Kotlin
*/
public external abstract class CSS {
companion object {
fun escape(ident: String): String
}
}
@@ -0,0 +1,484 @@
/*
* Generated file
* DO NOT EDIT
*
* See libraries/tools/idl2k for details
*/
@file:Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
package org.w3c.dom.events
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.css.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
/**
* Exposes the JavaScript [UIEvent](https://developer.mozilla.org/en/docs/Web/API/UIEvent) to Kotlin
*/
public external open class UIEvent(type: String, eventInitDict: UIEventInit = definedExternally) : Event {
open val view: Window?
open val detail: Int
}
public external interface UIEventInit : EventInit {
var view: Window? /* = null */
get() = definedExternally
set(value) = definedExternally
var detail: Int? /* = 0 */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun UIEventInit(view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): UIEventInit {
val o = js("({})")
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
/**
* Exposes the JavaScript [FocusEvent](https://developer.mozilla.org/en/docs/Web/API/FocusEvent) to Kotlin
*/
public external open class FocusEvent(type: String, eventInitDict: FocusEventInit = definedExternally) : UIEvent {
open val relatedTarget: EventTarget?
}
public external interface FocusEventInit : UIEventInit {
var relatedTarget: EventTarget? /* = null */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun FocusEventInit(relatedTarget: EventTarget? = null, view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): FocusEventInit {
val o = js("({})")
o["relatedTarget"] = relatedTarget
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
/**
* Exposes the JavaScript [MouseEvent](https://developer.mozilla.org/en/docs/Web/API/MouseEvent) to Kotlin
*/
public external open class MouseEvent(type: String, eventInitDict: MouseEventInit = definedExternally) : UIEvent, UnionElementOrMouseEvent {
open val region: String?
open val screenX: Int
open val screenY: Int
open val pageX: Double
open val pageY: Double
open val clientX: Int
open val clientY: Int
open val offsetX: Double
open val offsetY: Double
open val ctrlKey: Boolean
open val shiftKey: Boolean
open val altKey: Boolean
open val metaKey: Boolean
open val button: Short
open val buttons: Short
open val relatedTarget: EventTarget?
fun getModifierState(keyArg: String): Boolean
}
public external interface MouseEventInit : EventModifierInit {
var screenX: Int? /* = 0 */
get() = definedExternally
set(value) = definedExternally
var screenY: Int? /* = 0 */
get() = definedExternally
set(value) = definedExternally
var clientX: Int? /* = 0 */
get() = definedExternally
set(value) = definedExternally
var clientY: Int? /* = 0 */
get() = definedExternally
set(value) = definedExternally
var button: Short? /* = 0 */
get() = definedExternally
set(value) = definedExternally
var buttons: Short? /* = 0 */
get() = definedExternally
set(value) = definedExternally
var relatedTarget: EventTarget? /* = null */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun MouseEventInit(screenX: Int? = 0, screenY: Int? = 0, clientX: Int? = 0, clientY: Int? = 0, button: Short? = 0, buttons: Short? = 0, relatedTarget: EventTarget? = null, ctrlKey: Boolean? = false, shiftKey: Boolean? = false, altKey: Boolean? = false, metaKey: Boolean? = false, modifierAltGraph: Boolean? = false, modifierCapsLock: Boolean? = false, modifierFn: Boolean? = false, modifierFnLock: Boolean? = false, modifierHyper: Boolean? = false, modifierNumLock: Boolean? = false, modifierScrollLock: Boolean? = false, modifierSuper: Boolean? = false, modifierSymbol: Boolean? = false, modifierSymbolLock: Boolean? = false, view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): MouseEventInit {
val o = js("({})")
o["screenX"] = screenX
o["screenY"] = screenY
o["clientX"] = clientX
o["clientY"] = clientY
o["button"] = button
o["buttons"] = buttons
o["relatedTarget"] = relatedTarget
o["ctrlKey"] = ctrlKey
o["shiftKey"] = shiftKey
o["altKey"] = altKey
o["metaKey"] = metaKey
o["modifierAltGraph"] = modifierAltGraph
o["modifierCapsLock"] = modifierCapsLock
o["modifierFn"] = modifierFn
o["modifierFnLock"] = modifierFnLock
o["modifierHyper"] = modifierHyper
o["modifierNumLock"] = modifierNumLock
o["modifierScrollLock"] = modifierScrollLock
o["modifierSuper"] = modifierSuper
o["modifierSymbol"] = modifierSymbol
o["modifierSymbolLock"] = modifierSymbolLock
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
public external interface EventModifierInit : UIEventInit {
var ctrlKey: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var shiftKey: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var altKey: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var metaKey: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierAltGraph: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierCapsLock: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierFn: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierFnLock: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierHyper: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierNumLock: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierScrollLock: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierSuper: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierSymbol: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var modifierSymbolLock: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun EventModifierInit(ctrlKey: Boolean? = false, shiftKey: Boolean? = false, altKey: Boolean? = false, metaKey: Boolean? = false, modifierAltGraph: Boolean? = false, modifierCapsLock: Boolean? = false, modifierFn: Boolean? = false, modifierFnLock: Boolean? = false, modifierHyper: Boolean? = false, modifierNumLock: Boolean? = false, modifierScrollLock: Boolean? = false, modifierSuper: Boolean? = false, modifierSymbol: Boolean? = false, modifierSymbolLock: Boolean? = false, view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): EventModifierInit {
val o = js("({})")
o["ctrlKey"] = ctrlKey
o["shiftKey"] = shiftKey
o["altKey"] = altKey
o["metaKey"] = metaKey
o["modifierAltGraph"] = modifierAltGraph
o["modifierCapsLock"] = modifierCapsLock
o["modifierFn"] = modifierFn
o["modifierFnLock"] = modifierFnLock
o["modifierHyper"] = modifierHyper
o["modifierNumLock"] = modifierNumLock
o["modifierScrollLock"] = modifierScrollLock
o["modifierSuper"] = modifierSuper
o["modifierSymbol"] = modifierSymbol
o["modifierSymbolLock"] = modifierSymbolLock
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
/**
* Exposes the JavaScript [WheelEvent](https://developer.mozilla.org/en/docs/Web/API/WheelEvent) to Kotlin
*/
public external open class WheelEvent(type: String, eventInitDict: WheelEventInit = definedExternally) : MouseEvent {
open val deltaX: Double
open val deltaY: Double
open val deltaZ: Double
open val deltaMode: Int
companion object {
val DOM_DELTA_PIXEL: Int
val DOM_DELTA_LINE: Int
val DOM_DELTA_PAGE: Int
}
}
public external interface WheelEventInit : MouseEventInit {
var deltaX: Double? /* = 0.0 */
get() = definedExternally
set(value) = definedExternally
var deltaY: Double? /* = 0.0 */
get() = definedExternally
set(value) = definedExternally
var deltaZ: Double? /* = 0.0 */
get() = definedExternally
set(value) = definedExternally
var deltaMode: Int? /* = 0 */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun WheelEventInit(deltaX: Double? = 0.0, deltaY: Double? = 0.0, deltaZ: Double? = 0.0, deltaMode: Int? = 0, screenX: Int? = 0, screenY: Int? = 0, clientX: Int? = 0, clientY: Int? = 0, button: Short? = 0, buttons: Short? = 0, relatedTarget: EventTarget? = null, ctrlKey: Boolean? = false, shiftKey: Boolean? = false, altKey: Boolean? = false, metaKey: Boolean? = false, modifierAltGraph: Boolean? = false, modifierCapsLock: Boolean? = false, modifierFn: Boolean? = false, modifierFnLock: Boolean? = false, modifierHyper: Boolean? = false, modifierNumLock: Boolean? = false, modifierScrollLock: Boolean? = false, modifierSuper: Boolean? = false, modifierSymbol: Boolean? = false, modifierSymbolLock: Boolean? = false, view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): WheelEventInit {
val o = js("({})")
o["deltaX"] = deltaX
o["deltaY"] = deltaY
o["deltaZ"] = deltaZ
o["deltaMode"] = deltaMode
o["screenX"] = screenX
o["screenY"] = screenY
o["clientX"] = clientX
o["clientY"] = clientY
o["button"] = button
o["buttons"] = buttons
o["relatedTarget"] = relatedTarget
o["ctrlKey"] = ctrlKey
o["shiftKey"] = shiftKey
o["altKey"] = altKey
o["metaKey"] = metaKey
o["modifierAltGraph"] = modifierAltGraph
o["modifierCapsLock"] = modifierCapsLock
o["modifierFn"] = modifierFn
o["modifierFnLock"] = modifierFnLock
o["modifierHyper"] = modifierHyper
o["modifierNumLock"] = modifierNumLock
o["modifierScrollLock"] = modifierScrollLock
o["modifierSuper"] = modifierSuper
o["modifierSymbol"] = modifierSymbol
o["modifierSymbolLock"] = modifierSymbolLock
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
/**
* Exposes the JavaScript [InputEvent](https://developer.mozilla.org/en/docs/Web/API/InputEvent) to Kotlin
*/
public external open class InputEvent(type: String, eventInitDict: InputEventInit = definedExternally) : UIEvent {
open val data: String
open val isComposing: Boolean
}
public external interface InputEventInit : UIEventInit {
var data: String? /* = "" */
get() = definedExternally
set(value) = definedExternally
var isComposing: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun InputEventInit(data: String? = "", isComposing: Boolean? = false, view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): InputEventInit {
val o = js("({})")
o["data"] = data
o["isComposing"] = isComposing
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
/**
* Exposes the JavaScript [KeyboardEvent](https://developer.mozilla.org/en/docs/Web/API/KeyboardEvent) to Kotlin
*/
public external open class KeyboardEvent(type: String, eventInitDict: KeyboardEventInit = definedExternally) : UIEvent {
open val key: String
open val code: String
open val location: Int
open val ctrlKey: Boolean
open val shiftKey: Boolean
open val altKey: Boolean
open val metaKey: Boolean
open val repeat: Boolean
open val isComposing: Boolean
open val charCode: Int
open val keyCode: Int
open val which: Int
fun getModifierState(keyArg: String): Boolean
companion object {
val DOM_KEY_LOCATION_STANDARD: Int
val DOM_KEY_LOCATION_LEFT: Int
val DOM_KEY_LOCATION_RIGHT: Int
val DOM_KEY_LOCATION_NUMPAD: Int
}
}
public external interface KeyboardEventInit : EventModifierInit {
var key: String? /* = "" */
get() = definedExternally
set(value) = definedExternally
var code: String? /* = "" */
get() = definedExternally
set(value) = definedExternally
var location: Int? /* = 0 */
get() = definedExternally
set(value) = definedExternally
var repeat: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var isComposing: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun KeyboardEventInit(key: String? = "", code: String? = "", location: Int? = 0, repeat: Boolean? = false, isComposing: Boolean? = false, ctrlKey: Boolean? = false, shiftKey: Boolean? = false, altKey: Boolean? = false, metaKey: Boolean? = false, modifierAltGraph: Boolean? = false, modifierCapsLock: Boolean? = false, modifierFn: Boolean? = false, modifierFnLock: Boolean? = false, modifierHyper: Boolean? = false, modifierNumLock: Boolean? = false, modifierScrollLock: Boolean? = false, modifierSuper: Boolean? = false, modifierSymbol: Boolean? = false, modifierSymbolLock: Boolean? = false, view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): KeyboardEventInit {
val o = js("({})")
o["key"] = key
o["code"] = code
o["location"] = location
o["repeat"] = repeat
o["isComposing"] = isComposing
o["ctrlKey"] = ctrlKey
o["shiftKey"] = shiftKey
o["altKey"] = altKey
o["metaKey"] = metaKey
o["modifierAltGraph"] = modifierAltGraph
o["modifierCapsLock"] = modifierCapsLock
o["modifierFn"] = modifierFn
o["modifierFnLock"] = modifierFnLock
o["modifierHyper"] = modifierHyper
o["modifierNumLock"] = modifierNumLock
o["modifierScrollLock"] = modifierScrollLock
o["modifierSuper"] = modifierSuper
o["modifierSymbol"] = modifierSymbol
o["modifierSymbolLock"] = modifierSymbolLock
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
/**
* Exposes the JavaScript [CompositionEvent](https://developer.mozilla.org/en/docs/Web/API/CompositionEvent) to Kotlin
*/
public external open class CompositionEvent(type: String, eventInitDict: CompositionEventInit = definedExternally) : UIEvent {
open val data: String
}
public external interface CompositionEventInit : UIEventInit {
var data: String? /* = "" */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun CompositionEventInit(data: String? = "", view: Window? = null, detail: Int? = 0, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): CompositionEventInit {
val o = js("({})")
o["data"] = data
o["view"] = view
o["detail"] = detail
o["bubbles"] = bubbles
o["cancelable"] = cancelable
o["composed"] = composed
return o
}
/**
* Exposes the JavaScript [Event](https://developer.mozilla.org/en/docs/Web/API/Event) to Kotlin
*/
public external open class Event(type: String, eventInitDict: EventInit = definedExternally) {
open val type: String
open val target: EventTarget?
open val currentTarget: EventTarget?
open val eventPhase: Short
open val bubbles: Boolean
open val cancelable: Boolean
open val defaultPrevented: Boolean
open val composed: Boolean
open val isTrusted: Boolean
open val timeStamp: Number
fun composedPath(): Array<EventTarget>
fun stopPropagation(): Unit
fun stopImmediatePropagation(): Unit
fun preventDefault(): Unit
fun initEvent(type: String, bubbles: Boolean, cancelable: Boolean): Unit
companion object {
val NONE: Short
val CAPTURING_PHASE: Short
val AT_TARGET: Short
val BUBBLING_PHASE: Short
}
}
/**
* Exposes the JavaScript [EventTarget](https://developer.mozilla.org/en/docs/Web/API/EventTarget) to Kotlin
*/
public external abstract class EventTarget {
fun addEventListener(type: String, callback: EventListener?, options: dynamic = definedExternally): Unit
fun addEventListener(type: String, callback: ((Event) -> Unit)?, options: dynamic = definedExternally): Unit
fun removeEventListener(type: String, callback: EventListener?, options: dynamic = definedExternally): Unit
fun removeEventListener(type: String, callback: ((Event) -> Unit)?, options: dynamic = definedExternally): Unit
fun dispatchEvent(event: Event): Boolean
}
/**
* Exposes the JavaScript [EventListener](https://developer.mozilla.org/en/docs/Web/API/EventListener) to Kotlin
*/
public external interface EventListener {
fun handleEvent(event: Event): Unit
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,38 @@
/*
* Generated file
* DO NOT EDIT
*
* See libraries/tools/idl2k for details
*/
@file:Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
package org.w3c.dom.parsing
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.css.*
import org.w3c.dom.events.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
/**
* Exposes the JavaScript [DOMParser](https://developer.mozilla.org/en/docs/Web/API/DOMParser) to Kotlin
*/
public external open class DOMParser {
fun parseFromString(str: String, type: dynamic): Document
}
/**
* Exposes the JavaScript [XMLSerializer](https://developer.mozilla.org/en/docs/Web/API/XMLSerializer) to Kotlin
*/
public external open class XMLSerializer {
fun serializeToString(root: Node): String
}
@@ -0,0 +1,840 @@
/*
* Generated file
* DO NOT EDIT
*
* See libraries/tools/idl2k for details
*/
@file:Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
package org.w3c.dom.svg
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.css.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
/**
* Exposes the JavaScript [SVGElement](https://developer.mozilla.org/en/docs/Web/API/SVGElement) to Kotlin
*/
public external abstract class SVGElement : Element, ElementCSSInlineStyle, GlobalEventHandlers, SVGElementInstance {
open val dataset: DOMStringMap
open val ownerSVGElement: SVGSVGElement?
open val viewportElement: SVGElement?
open var tabIndex: Int
fun focus(): Unit
fun blur(): Unit
}
public external interface SVGBoundingBoxOptions {
var fill: Boolean? /* = true */
get() = definedExternally
set(value) = definedExternally
var stroke: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var markers: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
var clipped: Boolean? /* = false */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun SVGBoundingBoxOptions(fill: Boolean? = true, stroke: Boolean? = false, markers: Boolean? = false, clipped: Boolean? = false): SVGBoundingBoxOptions {
val o = js("({})")
o["fill"] = fill
o["stroke"] = stroke
o["markers"] = markers
o["clipped"] = clipped
return o
}
/**
* Exposes the JavaScript [SVGGraphicsElement](https://developer.mozilla.org/en/docs/Web/API/SVGGraphicsElement) to Kotlin
*/
public external abstract class SVGGraphicsElement : SVGElement, SVGTests {
open val transform: SVGAnimatedTransformList
fun getBBox(options: SVGBoundingBoxOptions = definedExternally): DOMRect
fun getCTM(): DOMMatrix?
fun getScreenCTM(): DOMMatrix?
}
/**
* Exposes the JavaScript [SVGGeometryElement](https://developer.mozilla.org/en/docs/Web/API/SVGGeometryElement) to Kotlin
*/
public external abstract class SVGGeometryElement : SVGGraphicsElement {
open val pathLength: SVGAnimatedNumber
fun isPointInFill(point: DOMPoint): Boolean
fun isPointInStroke(point: DOMPoint): Boolean
fun getTotalLength(): Float
fun getPointAtLength(distance: Float): DOMPoint
}
/**
* Exposes the JavaScript [SVGNumber](https://developer.mozilla.org/en/docs/Web/API/SVGNumber) to Kotlin
*/
public external abstract class SVGNumber {
open var value: Float
}
/**
* Exposes the JavaScript [SVGLength](https://developer.mozilla.org/en/docs/Web/API/SVGLength) to Kotlin
*/
public external abstract class SVGLength {
open val unitType: Short
open var value: Float
open var valueInSpecifiedUnits: Float
open var valueAsString: String
fun newValueSpecifiedUnits(unitType: Short, valueInSpecifiedUnits: Float): Unit
fun convertToSpecifiedUnits(unitType: Short): Unit
companion object {
val SVG_LENGTHTYPE_UNKNOWN: Short
val SVG_LENGTHTYPE_NUMBER: Short
val SVG_LENGTHTYPE_PERCENTAGE: Short
val SVG_LENGTHTYPE_EMS: Short
val SVG_LENGTHTYPE_EXS: Short
val SVG_LENGTHTYPE_PX: Short
val SVG_LENGTHTYPE_CM: Short
val SVG_LENGTHTYPE_MM: Short
val SVG_LENGTHTYPE_IN: Short
val SVG_LENGTHTYPE_PT: Short
val SVG_LENGTHTYPE_PC: Short
}
}
/**
* Exposes the JavaScript [SVGAngle](https://developer.mozilla.org/en/docs/Web/API/SVGAngle) to Kotlin
*/
public external abstract class SVGAngle {
open val unitType: Short
open var value: Float
open var valueInSpecifiedUnits: Float
open var valueAsString: String
fun newValueSpecifiedUnits(unitType: Short, valueInSpecifiedUnits: Float): Unit
fun convertToSpecifiedUnits(unitType: Short): Unit
companion object {
val SVG_ANGLETYPE_UNKNOWN: Short
val SVG_ANGLETYPE_UNSPECIFIED: Short
val SVG_ANGLETYPE_DEG: Short
val SVG_ANGLETYPE_RAD: Short
val SVG_ANGLETYPE_GRAD: Short
}
}
public external abstract class SVGNameList {
open val length: Int
open val numberOfItems: Int
fun clear(): Unit
fun initialize(newItem: dynamic): dynamic
fun getItem(index: Int): dynamic
fun insertItemBefore(newItem: dynamic, index: Int): dynamic
fun replaceItem(newItem: dynamic, index: Int): dynamic
fun removeItem(index: Int): dynamic
fun appendItem(newItem: dynamic): dynamic
}
@kotlin.internal.InlineOnly inline operator fun SVGNameList.get(index: Int): dynamic = asDynamic()[index]
@kotlin.internal.InlineOnly inline operator fun SVGNameList.set(index: Int, newItem: dynamic): Unit { asDynamic()[index] = newItem; }
/**
* Exposes the JavaScript [SVGNumberList](https://developer.mozilla.org/en/docs/Web/API/SVGNumberList) to Kotlin
*/
public external abstract class SVGNumberList {
open val length: Int
open val numberOfItems: Int
fun clear(): Unit
fun initialize(newItem: SVGNumber): SVGNumber
fun getItem(index: Int): SVGNumber
fun insertItemBefore(newItem: SVGNumber, index: Int): SVGNumber
fun replaceItem(newItem: SVGNumber, index: Int): SVGNumber
fun removeItem(index: Int): SVGNumber
fun appendItem(newItem: SVGNumber): SVGNumber
}
@kotlin.internal.InlineOnly inline operator fun SVGNumberList.get(index: Int): SVGNumber? = asDynamic()[index]
@kotlin.internal.InlineOnly inline operator fun SVGNumberList.set(index: Int, newItem: SVGNumber): Unit { asDynamic()[index] = newItem; }
/**
* Exposes the JavaScript [SVGLengthList](https://developer.mozilla.org/en/docs/Web/API/SVGLengthList) to Kotlin
*/
public external abstract class SVGLengthList {
open val length: Int
open val numberOfItems: Int
fun clear(): Unit
fun initialize(newItem: SVGLength): SVGLength
fun getItem(index: Int): SVGLength
fun insertItemBefore(newItem: SVGLength, index: Int): SVGLength
fun replaceItem(newItem: SVGLength, index: Int): SVGLength
fun removeItem(index: Int): SVGLength
fun appendItem(newItem: SVGLength): SVGLength
}
@kotlin.internal.InlineOnly inline operator fun SVGLengthList.get(index: Int): SVGLength? = asDynamic()[index]
@kotlin.internal.InlineOnly inline operator fun SVGLengthList.set(index: Int, newItem: SVGLength): Unit { asDynamic()[index] = newItem; }
/**
* Exposes the JavaScript [SVGAnimatedBoolean](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedBoolean) to Kotlin
*/
public external abstract class SVGAnimatedBoolean {
open var baseVal: Boolean
open val animVal: Boolean
}
/**
* Exposes the JavaScript [SVGAnimatedEnumeration](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedEnumeration) to Kotlin
*/
public external abstract class SVGAnimatedEnumeration {
open var baseVal: Short
open val animVal: Short
}
/**
* Exposes the JavaScript [SVGAnimatedInteger](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedInteger) to Kotlin
*/
public external abstract class SVGAnimatedInteger {
open var baseVal: Int
open val animVal: Int
}
/**
* Exposes the JavaScript [SVGAnimatedNumber](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedNumber) to Kotlin
*/
public external abstract class SVGAnimatedNumber {
open var baseVal: Float
open val animVal: Float
}
/**
* Exposes the JavaScript [SVGAnimatedLength](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedLength) to Kotlin
*/
public external abstract class SVGAnimatedLength {
open val baseVal: SVGLength
open val animVal: SVGLength
}
/**
* Exposes the JavaScript [SVGAnimatedAngle](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedAngle) to Kotlin
*/
public external abstract class SVGAnimatedAngle {
open val baseVal: SVGAngle
open val animVal: SVGAngle
}
/**
* Exposes the JavaScript [SVGAnimatedString](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedString) to Kotlin
*/
public external abstract class SVGAnimatedString {
open var baseVal: String
open val animVal: String
}
/**
* Exposes the JavaScript [SVGAnimatedRect](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedRect) to Kotlin
*/
public external abstract class SVGAnimatedRect {
open val baseVal: DOMRect
open val animVal: DOMRectReadOnly
}
/**
* Exposes the JavaScript [SVGAnimatedNumberList](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedNumberList) to Kotlin
*/
public external abstract class SVGAnimatedNumberList {
open val baseVal: SVGNumberList
open val animVal: SVGNumberList
}
/**
* Exposes the JavaScript [SVGAnimatedLengthList](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedLengthList) to Kotlin
*/
public external abstract class SVGAnimatedLengthList {
open val baseVal: SVGLengthList
open val animVal: SVGLengthList
}
/**
* Exposes the JavaScript [SVGStringList](https://developer.mozilla.org/en/docs/Web/API/SVGStringList) to Kotlin
*/
public external abstract class SVGStringList {
open val length: Int
open val numberOfItems: Int
fun clear(): Unit
fun initialize(newItem: String): String
fun getItem(index: Int): String
fun insertItemBefore(newItem: String, index: Int): String
fun replaceItem(newItem: String, index: Int): String
fun removeItem(index: Int): String
fun appendItem(newItem: String): String
}
@kotlin.internal.InlineOnly inline operator fun SVGStringList.get(index: Int): String? = asDynamic()[index]
@kotlin.internal.InlineOnly inline operator fun SVGStringList.set(index: Int, newItem: String): Unit { asDynamic()[index] = newItem; }
public external interface SVGUnitTypes {
companion object {
val SVG_UNIT_TYPE_UNKNOWN: Short
val SVG_UNIT_TYPE_USERSPACEONUSE: Short
val SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: Short
}
}
/**
* Exposes the JavaScript [SVGTests](https://developer.mozilla.org/en/docs/Web/API/SVGTests) to Kotlin
*/
public external interface SVGTests {
val requiredExtensions: SVGStringList
val systemLanguage: SVGStringList
}
public external interface SVGFitToViewBox {
val viewBox: SVGAnimatedRect
val preserveAspectRatio: SVGAnimatedPreserveAspectRatio
}
public external interface SVGZoomAndPan {
var zoomAndPan: Short
companion object {
val SVG_ZOOMANDPAN_UNKNOWN: Short
val SVG_ZOOMANDPAN_DISABLE: Short
val SVG_ZOOMANDPAN_MAGNIFY: Short
}
}
public external interface SVGURIReference {
val href: SVGAnimatedString
}
/**
* Exposes the JavaScript [SVGSVGElement](https://developer.mozilla.org/en/docs/Web/API/SVGSVGElement) to Kotlin
*/
public external abstract class SVGSVGElement : SVGGraphicsElement, SVGFitToViewBox, SVGZoomAndPan, WindowEventHandlers {
open val x: SVGAnimatedLength
open val y: SVGAnimatedLength
open val width: SVGAnimatedLength
open val height: SVGAnimatedLength
open var currentScale: Float
open val currentTranslate: DOMPointReadOnly
fun getIntersectionList(rect: DOMRectReadOnly, referenceElement: SVGElement?): NodeList
fun getEnclosureList(rect: DOMRectReadOnly, referenceElement: SVGElement?): NodeList
fun checkIntersection(element: SVGElement, rect: DOMRectReadOnly): Boolean
fun checkEnclosure(element: SVGElement, rect: DOMRectReadOnly): Boolean
fun deselectAll(): Unit
fun createSVGNumber(): SVGNumber
fun createSVGLength(): SVGLength
fun createSVGAngle(): SVGAngle
fun createSVGPoint(): DOMPoint
fun createSVGMatrix(): DOMMatrix
fun createSVGRect(): DOMRect
fun createSVGTransform(): SVGTransform
fun createSVGTransformFromMatrix(matrix: DOMMatrixReadOnly): SVGTransform
fun getElementById(elementId: String): Element
fun suspendRedraw(maxWaitMilliseconds: Int): Int
fun unsuspendRedraw(suspendHandleID: Int): Unit
fun unsuspendRedrawAll(): Unit
fun forceRedraw(): Unit
companion object {
val SVG_ZOOMANDPAN_UNKNOWN: Short
val SVG_ZOOMANDPAN_DISABLE: Short
val SVG_ZOOMANDPAN_MAGNIFY: Short
}
}
/**
* Exposes the JavaScript [SVGGElement](https://developer.mozilla.org/en/docs/Web/API/SVGGElement) to Kotlin
*/
public external abstract class SVGGElement : SVGGraphicsElement {
}
public external abstract class SVGUnknownElement : SVGGraphicsElement {
}
/**
* Exposes the JavaScript [SVGDefsElement](https://developer.mozilla.org/en/docs/Web/API/SVGDefsElement) to Kotlin
*/
public external abstract class SVGDefsElement : SVGGraphicsElement {
}
/**
* Exposes the JavaScript [SVGDescElement](https://developer.mozilla.org/en/docs/Web/API/SVGDescElement) to Kotlin
*/
public external abstract class SVGDescElement : SVGElement {
}
public external abstract class SVGMetadataElement : SVGElement {
}
/**
* Exposes the JavaScript [SVGTitleElement](https://developer.mozilla.org/en/docs/Web/API/SVGTitleElement) to Kotlin
*/
public external abstract class SVGTitleElement : SVGElement {
}
/**
* Exposes the JavaScript [SVGSymbolElement](https://developer.mozilla.org/en/docs/Web/API/SVGSymbolElement) to Kotlin
*/
public external abstract class SVGSymbolElement : SVGGraphicsElement, SVGFitToViewBox {
}
/**
* Exposes the JavaScript [SVGUseElement](https://developer.mozilla.org/en/docs/Web/API/SVGUseElement) to Kotlin
*/
public external abstract class SVGUseElement : SVGGraphicsElement, SVGURIReference {
open val x: SVGAnimatedLength
open val y: SVGAnimatedLength
open val width: SVGAnimatedLength
open val height: SVGAnimatedLength
open val instanceRoot: SVGElement?
open val animatedInstanceRoot: SVGElement?
}
public external open class SVGUseElementShadowRoot : ShadowRoot {
override fun getElementById(elementId: String): Element?
override fun prepend(vararg nodes: dynamic): Unit
override fun append(vararg nodes: dynamic): Unit
override fun querySelector(selectors: String): Element?
override fun querySelectorAll(selectors: String): NodeList
}
public external interface SVGElementInstance {
val correspondingElement: SVGElement?
val correspondingUseElement: SVGUseElement?
}
public external open class ShadowAnimation(source: dynamic, newTarget: dynamic) {
open val sourceAnimation: dynamic
}
/**
* Exposes the JavaScript [SVGSwitchElement](https://developer.mozilla.org/en/docs/Web/API/SVGSwitchElement) to Kotlin
*/
public external abstract class SVGSwitchElement : SVGGraphicsElement {
}
public external interface GetSVGDocument {
fun getSVGDocument(): Document
}
/**
* Exposes the JavaScript [SVGStyleElement](https://developer.mozilla.org/en/docs/Web/API/SVGStyleElement) to Kotlin
*/
public external abstract class SVGStyleElement : SVGElement, LinkStyle {
open var type: String
open var media: String
open var title: String
}
/**
* Exposes the JavaScript [SVGTransform](https://developer.mozilla.org/en/docs/Web/API/SVGTransform) to Kotlin
*/
public external abstract class SVGTransform {
open val type: Short
open val matrix: DOMMatrix
open val angle: Float
fun setMatrix(matrix: DOMMatrixReadOnly): Unit
fun setTranslate(tx: Float, ty: Float): Unit
fun setScale(sx: Float, sy: Float): Unit
fun setRotate(angle: Float, cx: Float, cy: Float): Unit
fun setSkewX(angle: Float): Unit
fun setSkewY(angle: Float): Unit
companion object {
val SVG_TRANSFORM_UNKNOWN: Short
val SVG_TRANSFORM_MATRIX: Short
val SVG_TRANSFORM_TRANSLATE: Short
val SVG_TRANSFORM_SCALE: Short
val SVG_TRANSFORM_ROTATE: Short
val SVG_TRANSFORM_SKEWX: Short
val SVG_TRANSFORM_SKEWY: Short
}
}
/**
* Exposes the JavaScript [SVGTransformList](https://developer.mozilla.org/en/docs/Web/API/SVGTransformList) to Kotlin
*/
public external abstract class SVGTransformList {
open val length: Int
open val numberOfItems: Int
fun clear(): Unit
fun initialize(newItem: SVGTransform): SVGTransform
fun getItem(index: Int): SVGTransform
fun insertItemBefore(newItem: SVGTransform, index: Int): SVGTransform
fun replaceItem(newItem: SVGTransform, index: Int): SVGTransform
fun removeItem(index: Int): SVGTransform
fun appendItem(newItem: SVGTransform): SVGTransform
fun createSVGTransformFromMatrix(matrix: DOMMatrixReadOnly): SVGTransform
fun consolidate(): SVGTransform?
}
@kotlin.internal.InlineOnly inline operator fun SVGTransformList.get(index: Int): SVGTransform? = asDynamic()[index]
@kotlin.internal.InlineOnly inline operator fun SVGTransformList.set(index: Int, newItem: SVGTransform): Unit { asDynamic()[index] = newItem; }
/**
* Exposes the JavaScript [SVGAnimatedTransformList](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedTransformList) to Kotlin
*/
public external abstract class SVGAnimatedTransformList {
open val baseVal: SVGTransformList
open val animVal: SVGTransformList
}
/**
* Exposes the JavaScript [SVGPreserveAspectRatio](https://developer.mozilla.org/en/docs/Web/API/SVGPreserveAspectRatio) to Kotlin
*/
public external abstract class SVGPreserveAspectRatio {
open var align: Short
open var meetOrSlice: Short
companion object {
val SVG_PRESERVEASPECTRATIO_UNKNOWN: Short
val SVG_PRESERVEASPECTRATIO_NONE: Short
val SVG_PRESERVEASPECTRATIO_XMINYMIN: Short
val SVG_PRESERVEASPECTRATIO_XMIDYMIN: Short
val SVG_PRESERVEASPECTRATIO_XMAXYMIN: Short
val SVG_PRESERVEASPECTRATIO_XMINYMID: Short
val SVG_PRESERVEASPECTRATIO_XMIDYMID: Short
val SVG_PRESERVEASPECTRATIO_XMAXYMID: Short
val SVG_PRESERVEASPECTRATIO_XMINYMAX: Short
val SVG_PRESERVEASPECTRATIO_XMIDYMAX: Short
val SVG_PRESERVEASPECTRATIO_XMAXYMAX: Short
val SVG_MEETORSLICE_UNKNOWN: Short
val SVG_MEETORSLICE_MEET: Short
val SVG_MEETORSLICE_SLICE: Short
}
}
/**
* Exposes the JavaScript [SVGAnimatedPreserveAspectRatio](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedPreserveAspectRatio) to Kotlin
*/
public external abstract class SVGAnimatedPreserveAspectRatio {
open val baseVal: SVGPreserveAspectRatio
open val animVal: SVGPreserveAspectRatio
}
/**
* Exposes the JavaScript [SVGPathElement](https://developer.mozilla.org/en/docs/Web/API/SVGPathElement) to Kotlin
*/
public external abstract class SVGPathElement : SVGGeometryElement {
}
/**
* Exposes the JavaScript [SVGRectElement](https://developer.mozilla.org/en/docs/Web/API/SVGRectElement) to Kotlin
*/
public external abstract class SVGRectElement : SVGGeometryElement {
open val x: SVGAnimatedLength
open val y: SVGAnimatedLength
open val width: SVGAnimatedLength
open val height: SVGAnimatedLength
open val rx: SVGAnimatedLength
open val ry: SVGAnimatedLength
}
/**
* Exposes the JavaScript [SVGCircleElement](https://developer.mozilla.org/en/docs/Web/API/SVGCircleElement) to Kotlin
*/
public external abstract class SVGCircleElement : SVGGeometryElement {
open val cx: SVGAnimatedLength
open val cy: SVGAnimatedLength
open val r: SVGAnimatedLength
}
/**
* Exposes the JavaScript [SVGEllipseElement](https://developer.mozilla.org/en/docs/Web/API/SVGEllipseElement) to Kotlin
*/
public external abstract class SVGEllipseElement : SVGGeometryElement {
open val cx: SVGAnimatedLength
open val cy: SVGAnimatedLength
open val rx: SVGAnimatedLength
open val ry: SVGAnimatedLength
}
/**
* Exposes the JavaScript [SVGLineElement](https://developer.mozilla.org/en/docs/Web/API/SVGLineElement) to Kotlin
*/
public external abstract class SVGLineElement : SVGGeometryElement {
open val x1: SVGAnimatedLength
open val y1: SVGAnimatedLength
open val x2: SVGAnimatedLength
open val y2: SVGAnimatedLength
}
/**
* Exposes the JavaScript [SVGMeshElement](https://developer.mozilla.org/en/docs/Web/API/SVGMeshElement) to Kotlin
*/
public external abstract class SVGMeshElement : SVGGeometryElement, SVGURIReference {
}
/**
* Exposes the JavaScript [SVGAnimatedPoints](https://developer.mozilla.org/en/docs/Web/API/SVGAnimatedPoints) to Kotlin
*/
public external interface SVGAnimatedPoints {
val points: SVGPointList
val animatedPoints: SVGPointList
}
public external abstract class SVGPointList {
open val length: Int
open val numberOfItems: Int
fun clear(): Unit
fun initialize(newItem: DOMPoint): DOMPoint
fun getItem(index: Int): DOMPoint
fun insertItemBefore(newItem: DOMPoint, index: Int): DOMPoint
fun replaceItem(newItem: DOMPoint, index: Int): DOMPoint
fun removeItem(index: Int): DOMPoint
fun appendItem(newItem: DOMPoint): DOMPoint
}
@kotlin.internal.InlineOnly inline operator fun SVGPointList.get(index: Int): DOMPoint? = asDynamic()[index]
@kotlin.internal.InlineOnly inline operator fun SVGPointList.set(index: Int, newItem: DOMPoint): Unit { asDynamic()[index] = newItem; }
/**
* Exposes the JavaScript [SVGPolylineElement](https://developer.mozilla.org/en/docs/Web/API/SVGPolylineElement) to Kotlin
*/
public external abstract class SVGPolylineElement : SVGGeometryElement, SVGAnimatedPoints {
}
/**
* Exposes the JavaScript [SVGPolygonElement](https://developer.mozilla.org/en/docs/Web/API/SVGPolygonElement) to Kotlin
*/
public external abstract class SVGPolygonElement : SVGGeometryElement, SVGAnimatedPoints {
}
/**
* Exposes the JavaScript [SVGTextContentElement](https://developer.mozilla.org/en/docs/Web/API/SVGTextContentElement) to Kotlin
*/
public external abstract class SVGTextContentElement : SVGGraphicsElement {
open val textLength: SVGAnimatedLength
open val lengthAdjust: SVGAnimatedEnumeration
fun getNumberOfChars(): Int
fun getComputedTextLength(): Float
fun getSubStringLength(charnum: Int, nchars: Int): Float
fun getStartPositionOfChar(charnum: Int): DOMPoint
fun getEndPositionOfChar(charnum: Int): DOMPoint
fun getExtentOfChar(charnum: Int): DOMRect
fun getRotationOfChar(charnum: Int): Float
fun getCharNumAtPosition(point: DOMPoint): Int
fun selectSubString(charnum: Int, nchars: Int): Unit
companion object {
val LENGTHADJUST_UNKNOWN: Short
val LENGTHADJUST_SPACING: Short
val LENGTHADJUST_SPACINGANDGLYPHS: Short
}
}
/**
* Exposes the JavaScript [SVGTextPositioningElement](https://developer.mozilla.org/en/docs/Web/API/SVGTextPositioningElement) to Kotlin
*/
public external abstract class SVGTextPositioningElement : SVGTextContentElement {
open val x: SVGAnimatedLengthList
open val y: SVGAnimatedLengthList
open val dx: SVGAnimatedLengthList
open val dy: SVGAnimatedLengthList
open val rotate: SVGAnimatedNumberList
}
/**
* Exposes the JavaScript [SVGTextElement](https://developer.mozilla.org/en/docs/Web/API/SVGTextElement) to Kotlin
*/
public external abstract class SVGTextElement : SVGTextPositioningElement {
}
/**
* Exposes the JavaScript [SVGTSpanElement](https://developer.mozilla.org/en/docs/Web/API/SVGTSpanElement) to Kotlin
*/
public external abstract class SVGTSpanElement : SVGTextPositioningElement {
}
public external abstract class SVGTextPathElement : SVGTextContentElement, SVGURIReference {
open val startOffset: SVGAnimatedLength
open val method: SVGAnimatedEnumeration
open val spacing: SVGAnimatedEnumeration
companion object {
val TEXTPATH_METHODTYPE_UNKNOWN: Short
val TEXTPATH_METHODTYPE_ALIGN: Short
val TEXTPATH_METHODTYPE_STRETCH: Short
val TEXTPATH_SPACINGTYPE_UNKNOWN: Short
val TEXTPATH_SPACINGTYPE_AUTO: Short
val TEXTPATH_SPACINGTYPE_EXACT: Short
}
}
/**
* Exposes the JavaScript [SVGImageElement](https://developer.mozilla.org/en/docs/Web/API/SVGImageElement) to Kotlin
*/
public external abstract class SVGImageElement : SVGGraphicsElement, SVGURIReference, HTMLOrSVGImageElement {
open val x: SVGAnimatedLength
open val y: SVGAnimatedLength
open val width: SVGAnimatedLength
open val height: SVGAnimatedLength
open val preserveAspectRatio: SVGAnimatedPreserveAspectRatio
open var crossOrigin: String?
}
/**
* Exposes the JavaScript [SVGForeignObjectElement](https://developer.mozilla.org/en/docs/Web/API/SVGForeignObjectElement) to Kotlin
*/
public external abstract class SVGForeignObjectElement : SVGGraphicsElement {
open val x: SVGAnimatedLength
open val y: SVGAnimatedLength
open val width: SVGAnimatedLength
open val height: SVGAnimatedLength
}
public external abstract class SVGMarkerElement : SVGElement, SVGFitToViewBox {
open val refX: SVGAnimatedLength
open val refY: SVGAnimatedLength
open val markerUnits: SVGAnimatedEnumeration
open val markerWidth: SVGAnimatedLength
open val markerHeight: SVGAnimatedLength
open val orientType: SVGAnimatedEnumeration
open val orientAngle: SVGAnimatedAngle
open var orient: String
fun setOrientToAuto(): Unit
fun setOrientToAngle(angle: SVGAngle): Unit
companion object {
val SVG_MARKERUNITS_UNKNOWN: Short
val SVG_MARKERUNITS_USERSPACEONUSE: Short
val SVG_MARKERUNITS_STROKEWIDTH: Short
val SVG_MARKER_ORIENT_UNKNOWN: Short
val SVG_MARKER_ORIENT_AUTO: Short
val SVG_MARKER_ORIENT_ANGLE: Short
}
}
public external abstract class SVGSolidcolorElement : SVGElement {
}
/**
* Exposes the JavaScript [SVGGradientElement](https://developer.mozilla.org/en/docs/Web/API/SVGGradientElement) to Kotlin
*/
public external abstract class SVGGradientElement : SVGElement, SVGURIReference, SVGUnitTypes {
open val gradientUnits: SVGAnimatedEnumeration
open val gradientTransform: SVGAnimatedTransformList
open val spreadMethod: SVGAnimatedEnumeration
companion object {
val SVG_SPREADMETHOD_UNKNOWN: Short
val SVG_SPREADMETHOD_PAD: Short
val SVG_SPREADMETHOD_REFLECT: Short
val SVG_SPREADMETHOD_REPEAT: Short
val SVG_UNIT_TYPE_UNKNOWN: Short
val SVG_UNIT_TYPE_USERSPACEONUSE: Short
val SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: Short
}
}
/**
* Exposes the JavaScript [SVGLinearGradientElement](https://developer.mozilla.org/en/docs/Web/API/SVGLinearGradientElement) to Kotlin
*/
public external abstract class SVGLinearGradientElement : SVGGradientElement {
open val x1: SVGAnimatedLength
open val y1: SVGAnimatedLength
open val x2: SVGAnimatedLength
open val y2: SVGAnimatedLength
}
/**
* Exposes the JavaScript [SVGRadialGradientElement](https://developer.mozilla.org/en/docs/Web/API/SVGRadialGradientElement) to Kotlin
*/
public external abstract class SVGRadialGradientElement : SVGGradientElement {
open val cx: SVGAnimatedLength
open val cy: SVGAnimatedLength
open val r: SVGAnimatedLength
open val fx: SVGAnimatedLength
open val fy: SVGAnimatedLength
open val fr: SVGAnimatedLength
}
public external abstract class SVGMeshGradientElement : SVGGradientElement {
}
public external abstract class SVGMeshrowElement : SVGElement {
}
public external abstract class SVGMeshpatchElement : SVGElement {
}
/**
* Exposes the JavaScript [SVGStopElement](https://developer.mozilla.org/en/docs/Web/API/SVGStopElement) to Kotlin
*/
public external abstract class SVGStopElement : SVGElement {
open val offset: SVGAnimatedNumber
}
/**
* Exposes the JavaScript [SVGPatternElement](https://developer.mozilla.org/en/docs/Web/API/SVGPatternElement) to Kotlin
*/
public external abstract class SVGPatternElement : SVGElement, SVGFitToViewBox, SVGURIReference, SVGUnitTypes {
open val patternUnits: SVGAnimatedEnumeration
open val patternContentUnits: SVGAnimatedEnumeration
open val patternTransform: SVGAnimatedTransformList
open val x: SVGAnimatedLength
open val y: SVGAnimatedLength
open val width: SVGAnimatedLength
open val height: SVGAnimatedLength
companion object {
val SVG_UNIT_TYPE_UNKNOWN: Short
val SVG_UNIT_TYPE_USERSPACEONUSE: Short
val SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: Short
}
}
public external abstract class SVGHatchElement : SVGElement {
}
public external abstract class SVGHatchpathElement : SVGElement {
}
/**
* Exposes the JavaScript [SVGCursorElement](https://developer.mozilla.org/en/docs/Web/API/SVGCursorElement) to Kotlin
*/
public external abstract class SVGCursorElement : SVGElement, SVGURIReference {
open val x: SVGAnimatedLength
open val y: SVGAnimatedLength
}
/**
* Exposes the JavaScript [SVGScriptElement](https://developer.mozilla.org/en/docs/Web/API/SVGScriptElement) to Kotlin
*/
public external abstract class SVGScriptElement : SVGElement, SVGURIReference, HTMLOrSVGScriptElement {
open var type: String
open var crossOrigin: String?
}
/**
* Exposes the JavaScript [SVGAElement](https://developer.mozilla.org/en/docs/Web/API/SVGAElement) to Kotlin
*/
public external abstract class SVGAElement : SVGGraphicsElement, SVGURIReference {
open val target: SVGAnimatedString
open val download: SVGAnimatedString
open val rel: SVGAnimatedString
open val relList: SVGAnimatedString
open val hreflang: SVGAnimatedString
open val type: SVGAnimatedString
}
/**
* Exposes the JavaScript [SVGViewElement](https://developer.mozilla.org/en/docs/Web/API/SVGViewElement) to Kotlin
*/
public external abstract class SVGViewElement : SVGElement, SVGFitToViewBox, SVGZoomAndPan {
companion object {
val SVG_ZOOMANDPAN_UNKNOWN: Short
val SVG_ZOOMANDPAN_DISABLE: Short
val SVG_ZOOMANDPAN_MAGNIFY: Short
}
}
@@ -0,0 +1,62 @@
/*
* Generated file
* DO NOT EDIT
*
* See libraries/tools/idl2k for details
*/
@file:Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
package org.w3c.dom.url
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.css.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
/**
* Exposes the JavaScript [URL](https://developer.mozilla.org/en/docs/Web/API/URL) to Kotlin
*/
public external open class URL(url: String, base: String = definedExternally) {
var href: String
open val origin: String
var protocol: String
var username: String
var password: String
var host: String
var hostname: String
var port: String
var pathname: String
var search: String
open val searchParams: URLSearchParams
var hash: String
companion object {
fun createObjectURL(blob: Blob): String
fun createFor(blob: Blob): String
fun revokeObjectURL(url: String): Unit
fun domainToASCII(domain: String): String
fun domainToUnicode(domain: String): String
}
}
/**
* Exposes the JavaScript [URLSearchParams](https://developer.mozilla.org/en/docs/Web/API/URLSearchParams) to Kotlin
*/
public external open class URLSearchParams(init: dynamic = definedExternally) {
fun append(name: String, value: String): Unit
fun delete(name: String): Unit
fun get(name: String): String?
fun getAll(name: String): Array<String>
fun has(name: String): Boolean
fun set(name: String, value: String): Unit
}
@@ -0,0 +1,262 @@
/*
* Generated file
* DO NOT EDIT
*
* See libraries/tools/idl2k for details
*/
@file:Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
package org.w3c.fetch
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.css.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
/**
* Exposes the JavaScript [Headers](https://developer.mozilla.org/en/docs/Web/API/Headers) to Kotlin
*/
public external open class Headers(init: dynamic = definedExternally) {
fun append(name: String, value: String): Unit
fun delete(name: String): Unit
fun get(name: String): String?
fun has(name: String): Boolean
fun set(name: String, value: String): Unit
}
/**
* Exposes the JavaScript [Body](https://developer.mozilla.org/en/docs/Web/API/Body) to Kotlin
*/
public external interface Body {
val bodyUsed: Boolean
fun arrayBuffer(): Promise<ArrayBuffer>
fun blob(): Promise<Blob>
fun formData(): Promise<FormData>
fun json(): Promise<Any?>
fun text(): Promise<String>
}
/**
* Exposes the JavaScript [Request](https://developer.mozilla.org/en/docs/Web/API/Request) to Kotlin
*/
public external open class Request(input: dynamic, init: RequestInit = definedExternally) : Body {
open val method: String
open val url: String
open val headers: Headers
open val type: RequestType
open val destination: RequestDestination
open val referrer: String
open val referrerPolicy: dynamic
open val mode: RequestMode
open val credentials: RequestCredentials
open val cache: RequestCache
open val redirect: RequestRedirect
open val integrity: String
open val keepalive: Boolean
override val bodyUsed: Boolean
fun clone(): Request
override fun arrayBuffer(): Promise<ArrayBuffer>
override fun blob(): Promise<Blob>
override fun formData(): Promise<FormData>
override fun json(): Promise<Any?>
override fun text(): Promise<String>
}
public external interface RequestInit {
var method: String?
get() = definedExternally
set(value) = definedExternally
var headers: dynamic
get() = definedExternally
set(value) = definedExternally
var body: dynamic
get() = definedExternally
set(value) = definedExternally
var referrer: String?
get() = definedExternally
set(value) = definedExternally
var referrerPolicy: dynamic
get() = definedExternally
set(value) = definedExternally
var mode: RequestMode?
get() = definedExternally
set(value) = definedExternally
var credentials: RequestCredentials?
get() = definedExternally
set(value) = definedExternally
var cache: RequestCache?
get() = definedExternally
set(value) = definedExternally
var redirect: RequestRedirect?
get() = definedExternally
set(value) = definedExternally
var integrity: String?
get() = definedExternally
set(value) = definedExternally
var keepalive: Boolean?
get() = definedExternally
set(value) = definedExternally
var window: Any?
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun RequestInit(method: String? = null, headers: dynamic = null, body: dynamic = null, referrer: String? = null, referrerPolicy: dynamic = null, mode: RequestMode? = null, credentials: RequestCredentials? = null, cache: RequestCache? = null, redirect: RequestRedirect? = null, integrity: String? = null, keepalive: Boolean? = null, window: Any? = null): RequestInit {
val o = js("({})")
o["method"] = method
o["headers"] = headers
o["body"] = body
o["referrer"] = referrer
o["referrerPolicy"] = referrerPolicy
o["mode"] = mode
o["credentials"] = credentials
o["cache"] = cache
o["redirect"] = redirect
o["integrity"] = integrity
o["keepalive"] = keepalive
o["window"] = window
return o
}
/**
* Exposes the JavaScript [Response](https://developer.mozilla.org/en/docs/Web/API/Response) to Kotlin
*/
public external open class Response(body: dynamic = definedExternally, init: ResponseInit = definedExternally) : Body {
open val type: ResponseType
open val url: String
open val redirected: Boolean
open val status: Short
open val ok: Boolean
open val statusText: String
open val headers: Headers
open val body: dynamic
open val trailer: Promise<Headers>
override val bodyUsed: Boolean
fun clone(): Response
override fun arrayBuffer(): Promise<ArrayBuffer>
override fun blob(): Promise<Blob>
override fun formData(): Promise<FormData>
override fun json(): Promise<Any?>
override fun text(): Promise<String>
companion object {
fun error(): Response
fun redirect(url: String, status: Short = definedExternally): Response
}
}
public external interface ResponseInit {
var status: Short? /* = 200 */
get() = definedExternally
set(value) = definedExternally
var statusText: String? /* = "OK" */
get() = definedExternally
set(value) = definedExternally
var headers: dynamic
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun ResponseInit(status: Short? = 200, statusText: String? = "OK", headers: dynamic = null): ResponseInit {
val o = js("({})")
o["status"] = status
o["statusText"] = statusText
o["headers"] = headers
return o
}
/* please, don't implement this interface! */
public external interface RequestType {
companion object
}
public inline val RequestType.Companion.EMPTY: RequestType get() = "".asDynamic().unsafeCast<RequestType>()
public inline val RequestType.Companion.AUDIO: RequestType get() = "audio".asDynamic().unsafeCast<RequestType>()
public inline val RequestType.Companion.FONT: RequestType get() = "font".asDynamic().unsafeCast<RequestType>()
public inline val RequestType.Companion.IMAGE: RequestType get() = "image".asDynamic().unsafeCast<RequestType>()
public inline val RequestType.Companion.SCRIPT: RequestType get() = "script".asDynamic().unsafeCast<RequestType>()
public inline val RequestType.Companion.STYLE: RequestType get() = "style".asDynamic().unsafeCast<RequestType>()
public inline val RequestType.Companion.TRACK: RequestType get() = "track".asDynamic().unsafeCast<RequestType>()
public inline val RequestType.Companion.VIDEO: RequestType get() = "video".asDynamic().unsafeCast<RequestType>()
/* please, don't implement this interface! */
public external interface RequestDestination {
companion object
}
public inline val RequestDestination.Companion.EMPTY: RequestDestination get() = "".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.DOCUMENT: RequestDestination get() = "document".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.EMBED: RequestDestination get() = "embed".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.FONT: RequestDestination get() = "font".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.IMAGE: RequestDestination get() = "image".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.MANIFEST: RequestDestination get() = "manifest".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.MEDIA: RequestDestination get() = "media".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.OBJECT: RequestDestination get() = "object".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.REPORT: RequestDestination get() = "report".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.SCRIPT: RequestDestination get() = "script".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.SERVICEWORKER: RequestDestination get() = "serviceworker".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.SHAREDWORKER: RequestDestination get() = "sharedworker".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.STYLE: RequestDestination get() = "style".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.WORKER: RequestDestination get() = "worker".asDynamic().unsafeCast<RequestDestination>()
public inline val RequestDestination.Companion.XSLT: RequestDestination get() = "xslt".asDynamic().unsafeCast<RequestDestination>()
/* please, don't implement this interface! */
public external interface RequestMode {
companion object
}
public inline val RequestMode.Companion.NAVIGATE: RequestMode get() = "navigate".asDynamic().unsafeCast<RequestMode>()
public inline val RequestMode.Companion.SAME_ORIGIN: RequestMode get() = "same-origin".asDynamic().unsafeCast<RequestMode>()
public inline val RequestMode.Companion.NO_CORS: RequestMode get() = "no-cors".asDynamic().unsafeCast<RequestMode>()
public inline val RequestMode.Companion.CORS: RequestMode get() = "cors".asDynamic().unsafeCast<RequestMode>()
/* please, don't implement this interface! */
public external interface RequestCredentials {
companion object
}
public inline val RequestCredentials.Companion.OMIT: RequestCredentials get() = "omit".asDynamic().unsafeCast<RequestCredentials>()
public inline val RequestCredentials.Companion.SAME_ORIGIN: RequestCredentials get() = "same-origin".asDynamic().unsafeCast<RequestCredentials>()
public inline val RequestCredentials.Companion.INCLUDE: RequestCredentials get() = "include".asDynamic().unsafeCast<RequestCredentials>()
/* please, don't implement this interface! */
public external interface RequestCache {
companion object
}
public inline val RequestCache.Companion.DEFAULT: RequestCache get() = "default".asDynamic().unsafeCast<RequestCache>()
public inline val RequestCache.Companion.NO_STORE: RequestCache get() = "no-store".asDynamic().unsafeCast<RequestCache>()
public inline val RequestCache.Companion.RELOAD: RequestCache get() = "reload".asDynamic().unsafeCast<RequestCache>()
public inline val RequestCache.Companion.NO_CACHE: RequestCache get() = "no-cache".asDynamic().unsafeCast<RequestCache>()
public inline val RequestCache.Companion.FORCE_CACHE: RequestCache get() = "force-cache".asDynamic().unsafeCast<RequestCache>()
public inline val RequestCache.Companion.ONLY_IF_CACHED: RequestCache get() = "only-if-cached".asDynamic().unsafeCast<RequestCache>()
/* please, don't implement this interface! */
public external interface RequestRedirect {
companion object
}
public inline val RequestRedirect.Companion.FOLLOW: RequestRedirect get() = "follow".asDynamic().unsafeCast<RequestRedirect>()
public inline val RequestRedirect.Companion.ERROR: RequestRedirect get() = "error".asDynamic().unsafeCast<RequestRedirect>()
public inline val RequestRedirect.Companion.MANUAL: RequestRedirect get() = "manual".asDynamic().unsafeCast<RequestRedirect>()
/* please, don't implement this interface! */
public external interface ResponseType {
companion object
}
public inline val ResponseType.Companion.BASIC: ResponseType get() = "basic".asDynamic().unsafeCast<ResponseType>()
public inline val ResponseType.Companion.CORS: ResponseType get() = "cors".asDynamic().unsafeCast<ResponseType>()
public inline val ResponseType.Companion.DEFAULT: ResponseType get() = "default".asDynamic().unsafeCast<ResponseType>()
public inline val ResponseType.Companion.ERROR: ResponseType get() = "error".asDynamic().unsafeCast<ResponseType>()
public inline val ResponseType.Companion.OPAQUE: ResponseType get() = "opaque".asDynamic().unsafeCast<ResponseType>()
public inline val ResponseType.Companion.OPAQUEREDIRECT: ResponseType get() = "opaqueredirect".asDynamic().unsafeCast<ResponseType>()
@@ -0,0 +1,119 @@
/*
* Generated file
* DO NOT EDIT
*
* See libraries/tools/idl2k for details
*/
@file:Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
package org.w3c.files
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.css.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
/**
* Exposes the JavaScript [Blob](https://developer.mozilla.org/en/docs/Web/API/Blob) to Kotlin
*/
public external open class Blob(blobParts: Array<dynamic> = definedExternally, options: BlobPropertyBag = definedExternally) {
open val size: Int
open val type: String
open val isClosed: Boolean
fun slice(start: Int = definedExternally, end: Int = definedExternally, contentType: String = definedExternally): Blob
fun close(): Unit
}
public external interface BlobPropertyBag {
var type: String? /* = "" */
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun BlobPropertyBag(type: String? = ""): BlobPropertyBag {
val o = js("({})")
o["type"] = type
return o
}
/**
* Exposes the JavaScript [File](https://developer.mozilla.org/en/docs/Web/API/File) to Kotlin
*/
public external open class File(fileBits: Array<dynamic>, fileName: String, options: FilePropertyBag = definedExternally) : Blob {
open val name: String
open val lastModified: Int
}
public external interface FilePropertyBag : BlobPropertyBag {
var lastModified: Int?
get() = definedExternally
set(value) = definedExternally
}
@kotlin.internal.InlineOnly
public inline fun FilePropertyBag(lastModified: Int? = null, type: String? = ""): FilePropertyBag {
val o = js("({})")
o["lastModified"] = lastModified
o["type"] = type
return o
}
/**
* Exposes the JavaScript [FileList](https://developer.mozilla.org/en/docs/Web/API/FileList) to Kotlin
*/
public external abstract class FileList : ItemArrayLike<File> {
override val length: Int
override fun item(index: Int): File?
}
@kotlin.internal.InlineOnly inline operator fun FileList.get(index: Int): File? = asDynamic()[index]
/**
* Exposes the JavaScript [FileReader](https://developer.mozilla.org/en/docs/Web/API/FileReader) to Kotlin
*/
public external open class FileReader : EventTarget {
open val readyState: Short
open val result: dynamic
open val error: dynamic
var onloadstart: ((Event) -> dynamic)?
var onprogress: ((Event) -> dynamic)?
var onload: ((Event) -> dynamic)?
var onabort: ((Event) -> dynamic)?
var onerror: ((Event) -> dynamic)?
var onloadend: ((Event) -> dynamic)?
fun readAsArrayBuffer(blob: Blob): Unit
fun readAsBinaryString(blob: Blob): Unit
fun readAsText(blob: Blob, label: String = definedExternally): Unit
fun readAsDataURL(blob: Blob): Unit
fun abort(): Unit
companion object {
val EMPTY: Short
val LOADING: Short
val DONE: Short
}
}
/**
* Exposes the JavaScript [FileReaderSync](https://developer.mozilla.org/en/docs/Web/API/FileReaderSync) to Kotlin
*/
public external open class FileReaderSync {
fun readAsArrayBuffer(blob: Blob): ArrayBuffer
fun readAsBinaryString(blob: Blob): String
fun readAsText(blob: Blob, label: String = definedExternally): String
fun readAsDataURL(blob: Blob): String
}

Some files were not shown because too many files have changed in this diff Show More