index.uts 13.1 KB
Newer Older
1
import { RequestTask, SyncOptions, AsyncOptions, SyntaxResult, SyncResult, TestOptions } from "./interface.uts";
fxy060608's avatar
fxy060608 已提交
2 3
import { log } from "./utils.uts";

杜庆泉's avatar
杜庆泉 已提交
4 5 6
// #ifdef APP-IOS
import { UTSPromiseAggregateError, UTSPromiseFulfilledResult, UTSPromiseRejectedResult} from "DCloudUTSFoundation";
// #endif
fxy060608's avatar
fxy060608 已提交
7 8 9 10 11 12 13 14 15 16 17

/**
 * 导出一个属性
 */
export const MAX = 100;

/**
 * 导出一个同步方法
 * @returns
 */
export function testSync(msg : string) : SyncResult {
18 19 20 21 22 23 24 25 26 27
  console.log("log test");
  log("log test1");

  const res : SyncResult = {
    msg: `hello ${msg}`
  }
  return res
  // return {
  //   msg: `hello ${msg}`,
  // };
fxy060608's avatar
fxy060608 已提交
28 29 30 31 32
}
/**
 * 导出一个同步方法(触发了数组越界异常)
 */
export function testSyncError() {
33 34
  const arr : string[] = [];
  console.log(arr[1]);
fxy060608's avatar
fxy060608 已提交
35 36 37 38 39 40
}
/**
 * 导出一个带callback的同步方法
 * @param opts
 */
export function testSyncWithCallback(opts : AsyncOptions) : SyntaxResult {
41 42 43 44 45 46 47 48 49 50 51 52
  if (opts.type == "success") {
    opts.success("success");
  } else {
    opts.fail("fail");
  }
  opts.complete("complete");

  const res : SyntaxResult = {
    name: "testSyncWithCallback"
  }
  return res;
  // return { name: "testSyncWithCallback" };
fxy060608's avatar
fxy060608 已提交
53
}
Q
qiang 已提交
54 55 56



杜庆泉's avatar
杜庆泉 已提交
57 58 59 60 61 62
async function testAwaitPromise(res : SyntaxResult) : Promise<SyntaxResult> {
  return await new Promise(function (resolve : (res : SyntaxResult) => void) {
    setTimeout(() => {
      resolve(res)
    }, 2000)
  })
Q
qiang 已提交
63
}
fxy060608's avatar
fxy060608 已提交
64 65 66 67 68
/**
 * 导出一个异步方法
 * @returns
 */
export async function testAsync(opts : AsyncOptions) : Promise<SyntaxResult> {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  if (opts.type == "success") {
    opts.success("success");
  } else {
    opts.fail("fail");
  }
  opts.complete("complete");

  const res : SyntaxResult = {
    name: "testAsync"
  }
  return await testAwaitPromise(res);
  // return { name: "testAsync" };
}


export async function testAsyncParam3(id : number, name : string, opts : AsyncOptions) : Promise<SyntaxResult> {
  console.log("id", id, "name", name)
  if (opts.type == "success") {
    opts.success("success");
  } else {
    opts.fail("fail");
  }
  opts.complete("complete");

  const res : SyntaxResult = {
    name: "testUtsAsyncMulitParam"
  }
  return await testAwaitPromise(res);
  // return { name: "testAsync" };
}
杜庆泉's avatar
杜庆泉 已提交
99

fxy060608's avatar
fxy060608 已提交
100 101

export class Test {
102
  id : number;
杜庆泉's avatar
杜庆泉 已提交
103
  name : string;
lizhongyi_'s avatar
lizhongyi_ 已提交
104
  
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  static type : string = "Test";
  constructor(id : number, options : TestOptions) {
    this.id = id;
    this.name = options.name;
    options.callback("Test.constructor");
  }
  static testClassStaticSyncWithCallback(opts : AsyncOptions) : SyntaxResult {
    return testSyncWithCallback(opts);
  }
  static async testClassStaticAsync(opts : AsyncOptions) : Promise<SyntaxResult> {
    const res = await testAsync(opts);
    return res;
  }
  testClassSyncWithCallback(opts : AsyncOptions) : SyntaxResult {
    return testSyncWithCallback(opts);
  }
  async testClassAsync(opts : AsyncOptions) : Promise<SyntaxResult> {
    const res = await testAsync(opts);
    return res;
  }
杜庆泉's avatar
杜庆泉 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
}

// #ifdef APP-IOS
// #ifdef UNI-APP-X

export function testPromiseStaticMethod() {
	 let p0 = new Promise<SyntaxResult | null>((resolve, reject) => {
		 let success = true
		 setTimeout(() => {
			 if (success) {
			 	const res : SyntaxResult = {
			 	  name: "pomise 0",
			 	}
			 	resolve(res);
			 } else{
			 	reject(new Error("this is promise 0 reject reasion"))
			 }

		 }, 1000);
	 });
	 
	 let p1 = new Promise<SyntaxResult  | null>((resolve, reject) => {
	 		 let success = true
	 		 setTimeout(() => {
	 			 if (success) {
	 			 	resolve(null);
	 			 } else{
	 			 	reject(new Error("this is promise 1 reject reasion"))
	 			 }
	 
	 		 }, 2000);
	 });
	 
	 let p2 = new Promise<SyntaxResult | null>((resolve, reject) => {
	 		 let success = false
	 		 setTimeout(() => {
	 			 if (success) {
	 			 	resolve(null);
	 			 } else{
	 			 	// reject(new Error("this is promise 2 reject reasion"))
					reject(null)
	 			 }
	 
	 		 }, 2500);
	 });
	 
	 // test for any
	 let pt = Promise.any([p0, p1, p2]);
	 pt.then( (res) => {
		 console.log("promise.any test success", res)
	 })
	 .catch( (error: any | null) => {
		 if (error instanceof UTSPromiseAggregateError) {
		 	let err = error as UTSPromiseAggregateError
			console.log(err.name, err.message, err.errors);
		 }else {
			 console.log(error);
		 }
	 })
	 
	 // test for allSettled
	 Promise.allSettled([p0, p1, p2])
	 .then((res) => {
		 res.forEach((item, index) => {
			 if (item instanceof UTSPromiseFulfilledResult<SyntaxResult  | null >) {
			 	let item0 = item as UTSPromiseFulfilledResult
				console.log(item0.value, "UTSPromiseFulfilledResult value")
			 } else if (item instanceof UTSPromiseRejectedResult<SyntaxResult | null>) {
			 	let item0 = item as UTSPromiseRejectedResult
			 	console.log(item0.reason, "UTSPromiseRejectedResult reason")
			 }
		 })
	 })
	 .catch((error:  any | null) => {   
		 console.log(error, "rejected test for promise.allSettled")
	 })
	 
	 // test for all 
	 Promise.all([p0, p1, p2])
	 .then((res)=> {
		 console.log(res, res.count)
	 })
	 .catch( (error: any | null) => {
		 console.log(error, "rejected test for promise.all")
	 })
	 
	 // test for race
	 Promise.race([p0, p1, p2])
	 .then((res) => {
		 console.log(res, "resolved test for promise.race");
	 })
	 .catch((error: any | null) => {
		 console.log(error, "catch test for promise.race")
	 })
}


// #endif
// #endif

export class SetterTest {
  
  private _nickName: string = '';
  
  get nickName (): string {
    console.log('get nickName');
    return this._nickName;
  }
  set nickName (value: string) {
    console.log('set nickName');
    this._nickName = value;
  }
  
fxy060608's avatar
fxy060608 已提交
238 239 240
}

class RequestTaskImpl implements RequestTask {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  url : string
  constructor(url : string) {
    this.url = url
  }
  abort() : RequestTask {
    return this
  }
  onCallback(callback : (res : string) => void) {
    callback("onCallback")
  }
  sync(options : SyncOptions) : string {
    options.success?.("success")
    options.complete?.("success")
    return "sync"
  }
fxy060608's avatar
fxy060608 已提交
256 257
}

258
export function request(url : string) : RequestTask | null {
259
  return new RequestTaskImpl(url)
杜庆泉's avatar
杜庆泉 已提交
260 261 262 263 264
}


// #ifdef APP-ANDROID

265 266
export function callKotlinMethodGetInfo():String {
	return NativeCode.getPhoneInfo()
杜庆泉's avatar
杜庆泉 已提交
267 268
}

269 270
export function callJavaMethodGetInfo():String {
	return new JavaUser("jack",12).name
杜庆泉's avatar
杜庆泉 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
}

export function callKotlinCallbackUTS(callback: (res: string) => void) {
	NativeCode.kotlinCallbackUTS(function(res:string){
    console.log(res)
    callback(res)
  })
}

export function callKotlinStopCallbackUTS() {
	NativeCode.kotlinStopMemListenTest()
}

// #endif

// #ifdef APP-ANDROID
// #ifdef UNI-APP-X
288

289 290 291 292 293 294 295 296 297
import KeyEvent from 'android.view.KeyEvent';
import Configuration from 'android.content.res.Configuration';
import Bundle from 'android.os.Bundle';
import Menu from 'android.view.Menu';
import KeyboardShortcutGroup from 'android.view.KeyboardShortcutGroup';
import WindowManager from 'android.view.WindowManager';
import ActionMode from 'android.view.ActionMode';
// export let onCallBackChange: (event: string) => void = (res) => {};

杜庆泉's avatar
杜庆泉 已提交
298
let callback : (eventLog : string) => void = (_) => { };
299

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
export function onCallbackChange(fn : (eventLog : string) => void) {
  callback = fn
}

export class UTSAcvitiyLifeCycleCallback extends UniActivityLifeCycleCallback {
  constructor() {
    super()
  }
  override onCreate(params : UniActivityParams, savedInstanceState : Bundle | null) {
    console.log('UTSAcvitiyLifeCycle', 'onCreate', savedInstanceState)
    callback('onCreate')
  }

  override onResume(params : UniActivityParams) {
    console.log('UTSAcvitiyLifeCycle', 'onResume', params)
    callback('onResume')
  }
  override onPreResume(params : UniActivityParams) {
    console.log('UTSAcvitiyLifeCycle', 'onPreResume', params)
    callback('onPreResume')
  }
  override onStart(params : UniActivityParams) {
    console.log('UTSAcvitiyLifeCycle', 'onStart', params)
    callback('onStart')
  }
  override onPreStart(params : UniActivityParams) {
    console.log('UTSAcvitiyLifeCycle', 'onPreStart', params)
    callback('onPreStart')
  }
}
export class UTSAcvitiyKeyEventCallback extends UniActivityKeyEventCallback {
  constructor() {
    super()
  }
  override onKeyDown(params : UniActivityParams, keyCode : Int, event : KeyEvent | null) {
    console.log('UTSAcvitiyKeyEvent', 'onKeyDown', params, keyCode, '' + event)
    callback('onKeyDown')
  }
  override onPreKeyDown(params : UniActivityParams, keyCode : Int, event : KeyEvent | null) {
    console.log('UTSAcvitiyKeyEvent', 'onPreKeyDown', params, keyCode, '' + event)
    callback('onPreKeyDown')
  }
  override onKeyLongPress(params : UniActivityParams, keyCode : Int, event : KeyEvent | null) {
    console.log('UTSAcvitiyKeyEvent', 'onKeyLongPress', params, keyCode, '' + event)
    callback('onKeyLongPress')
  }
  override onPreKeyLongPress(params : UniActivityParams, keyCode : Int, event : KeyEvent | null) {
    console.log('UTSAcvitiyKeyEvent', 'onPreKeyLongPress', params, keyCode, '' + event)
    callback('onPreKeyLongPress')
  }
}

export class UTSActivityWindowCallback extends UniActivityWindowCallback {
  constructor() {
    super()
  }
  override dispatchPreKeyEvent(params : UniActivityParams, event : KeyEvent | null) {
    console.log('UTSActivityWindowCallback', 'dispatchPreKeyEvent', params, '' + event)
    callback('dispatchPreKeyEvent')
  }
  override dispatchKeyEvent(params : UniActivityParams, event : KeyEvent | null) {
    console.log('UTSActivityWindowCallback', 'dispatchKeyEvent', params, '' + event)
    callback('dispatchKeyEvent')
  }
  override  onWindowAttributesChanged(params : UniActivityParams, attrs : WindowManager.LayoutParams) {
    console.log('UTSActivityWindowCallback', 'onWindowAttributesChanged', '' + attrs)
    callback('onWindowAttributesChanged')

  }
  override onAttachedToWindow(params : UniActivityParams) {
    console.log('UTSActivityWindowCallback', 'onAttachedToWindow', params)
    callback('onAttachedToWindow')

  }
  override onPanelClosed(params : UniActivityParams, featureId : Int, menu : Menu) {
    console.log('UTSActivityWindowCallback', 'onPanelClosed', featureId, menu)
    callback('onPanelClosed')

  }
  override onWindowStartingActionMode(params : UniActivityParams, callback : ActionMode.Callback | null) {
    console.log('UTSActivityWindowCallback', 'onWindowStartingActionMode', callback)
    callback('onWindowStartingActionMode')
  }
  override onProvideKeyboardShortcuts(params : UniActivityParams, data : MutableList<KeyboardShortcutGroup> | null, menu : Menu | null, deviceId : Int) {
    console.log('UTSActivityWindowCallback', 'onProvideKeyboardShortcuts', data, menu)
    callback('onProvideKeyboardShortcuts')
  }
  override  onPreWindowAttributesChanged(params : UniActivityParams, attrs : WindowManager.LayoutParams) {
    console.log('UTSActivityWindowCallback', 'onPreWindowAttributesChanged', attrs)
    callback('onPreWindowAttributesChanged')
  }
  override  onPrePanelClosed(params : UniActivityParams, featureId : Int, menu : Menu) {
    console.log('UTSActivityWindowCallback', 'onPrePanelClosed', featureId, menu)
    callback('onPrePanelClosed')
  }
}

export class UTSActivityCallback extends UniActivityCallback {
  constructor() {
    super()
  }
  override onBackPressed(params : UniActivityParams) {
    console.log('UTSActivityCallback', 'onBackPressed', params)
    callback('onBackPressed')
  }
  override onPreBackPressed(params : UniActivityParams) {
    console.log('UTSActivityCallback', 'onPreBackPressed', params)
    callback('onPreBackPressed')
  }

  override onRequestPermissionsResult(params : UniActivityParams, requestCode : Int, permissions : MutableList<String>, grantResults : IntArray) {
    console.log('UTSActivityCallback', 'onRequestPermissionsResult', params)
    callback('onRequestPermissionsResult')
  }

}

export class UTSActivityComponentCallback extends UniActivityComponentCallback {
  constructor() {
    super()
  }
  override onConfigurationChanged(params : UniActivityParams, newConfig : Configuration) {
    console.log('UTSActivityComponentCallback', 'onConfigurationChanged', params, '' + newConfig)
    callback('onConfigurationChanged')
  }
  override onPreConfigurationChanged(params : UniActivityParams, newConfig : Configuration) {
    console.log('UTSActivityComponentCallback', 'onPreConfigurationChanged', params, '' + newConfig)
    callback('onPreConfigurationChanged')
  }
}
// #endif
杜庆泉's avatar
杜庆泉 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
// #endif

export function Scan(timeMillis : Number = 60000):number {
	console.log("Scan", timeMillis)
	return timeMillis
}

export function Scan1(timeMillis ?: Number):string {
	console.log("Scan", timeMillis)
	if(timeMillis == null){
		return "null"
	}
	return timeMillis!.toString()
}

export function Scan2(timeMillis ?: Number | null):string {
	console.log("Scan", timeMillis)
	if(timeMillis == null){
		return "null"
	}
	return timeMillis!.toString()
}

export class myClass {
	constructor() {
		
	}
	
	to(name: String):string {
		console.log(name);
		return name
	}
	
	to1(name?: String):string {
		if(name == null){
			return "null"
		}
		console.log(name);
		return name!
	}
}