[Init]Init commit

This commit is contained in:
kenyeh
2023-05-19 17:13:53 +08:00
parent f670fe1a11
commit 10690ac902
135 changed files with 59831 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "44443e53-f038-4bec-8259-5066ddcd16ba",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "8e87240d-d769-40a6-9083-aa9ddfa1073d",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "a59cdffd-7c45-4b05-8094-dd13ba8fc7a4",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+20
View File
@@ -0,0 +1,20 @@
import { IDerivation } from "../internal";
export declare function createAction(actionName: string, fn: Function, autoAction?: boolean, ref?: Object): Function;
export declare function executeAction(actionName: string, canRunAsDerivation: boolean, fn: Function, scope?: any, args?: IArguments): any;
export interface IActionRunInfo {
prevDerivation_: IDerivation | null;
prevAllowStateChanges_: boolean;
prevAllowStateReads_: boolean;
notifySpy_: boolean;
startTime_: number;
error_?: any;
parentActionId_: number;
actionId_: number;
runAsAction_?: boolean;
}
export declare function _startAction(actionName: string, canRunAsDerivation: boolean, // true for autoAction
scope: any, args?: IArguments): IActionRunInfo;
export declare function _endAction(runInfo: IActionRunInfo): void;
export declare function allowStateChanges<T>(allowStateChanges: boolean, func: () => T): T;
export declare function allowStateChangesStart(allowStateChanges: boolean): boolean;
export declare function allowStateChangesEnd(prev: boolean): void;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "1f7b61f1-19cd-47f0-a89f-15fa99caa5be",
"subMetas": {}
}
+36
View File
@@ -0,0 +1,36 @@
import { IDerivationState_, IObservable, IDerivation, Lambda } from "../internal";
export declare const $mobx: unique symbol;
export interface IAtom extends IObservable {
reportObserved(): any;
reportChanged(): any;
}
export declare class Atom implements IAtom {
name_: string;
isPendingUnobservation_: boolean;
isBeingObserved_: boolean;
observers_: Set<IDerivation>;
diffValue_: number;
lastAccessedBy_: number;
lowestObserverState_: IDerivationState_;
/**
* Create a new atom. For debugging purposes it is recommended to give it a name.
* The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.
*/
constructor(name_?: string);
onBOL: Set<Lambda> | undefined;
onBUOL: Set<Lambda> | undefined;
onBO(): void;
onBUO(): void;
/**
* Invoke this method to notify mobx that your atom has been used somehow.
* Returns true if there is currently a reactive context.
*/
reportObserved(): boolean;
/**
* Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.
*/
reportChanged(): void;
toString(): string;
}
export declare const isAtom: (x: any) => x is Atom;
export declare function createAtom(name: string, onBecomeObservedHandler?: () => void, onBecomeUnobservedHandler?: () => void): IAtom;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "6c21e329-0ffd-43d8-9ac8-fe6a7c7b5c2f",
"subMetas": {}
}
+100
View File
@@ -0,0 +1,100 @@
import { CaughtException, IDerivation, IDerivationState_, IEqualsComparer, IObservable, Lambda, TraceMode } from "../internal";
export interface IComputedValue<T> {
get(): T;
set(value: T): void;
observe_(listener: (change: IComputedDidChange<T>) => void, fireImmediately?: boolean): Lambda;
}
export interface IComputedValueOptions<T> {
get?: () => T;
set?: (value: T) => void;
name?: string;
equals?: IEqualsComparer<T>;
context?: any;
requiresReaction?: boolean;
keepAlive?: boolean;
}
export declare type IComputedDidChange<T = any> = {
type: "update";
observableKind: "computed";
object: unknown;
debugObjectName: string;
newValue: T;
oldValue: T | undefined;
};
/**
* A node in the state dependency root that observes other nodes, and can be observed itself.
*
* ComputedValue will remember the result of the computation for the duration of the batch, or
* while being observed.
*
* During this time it will recompute only when one of its direct dependencies changed,
* but only when it is being accessed with `ComputedValue.get()`.
*
* Implementation description:
* 1. First time it's being accessed it will compute and remember result
* give back remembered result until 2. happens
* 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.
* 3. When it's being accessed, recompute if any shallow dependency changed.
* if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.
* go to step 2. either way
*
* If at any point it's outside batch and it isn't observed: reset everything and go to 1.
*/
export declare class ComputedValue<T> implements IObservable, IComputedValue<T>, IDerivation {
dependenciesState_: IDerivationState_;
observing_: IObservable[];
newObserving_: null;
isBeingObserved_: boolean;
isPendingUnobservation_: boolean;
observers_: Set<IDerivation>;
diffValue_: number;
runId_: number;
lastAccessedBy_: number;
lowestObserverState_: IDerivationState_;
unboundDepsCount_: number;
protected value_: T | undefined | CaughtException;
name_: string;
triggeredBy_?: string;
isComputing_: boolean;
isRunningSetter_: boolean;
derivation: () => T;
setter_?: (value: T) => void;
isTracing_: TraceMode;
scope_: Object | undefined;
private equals_;
private requiresReaction_;
keepAlive_: boolean;
/**
* Create a new computed value based on a function expression.
*
* The `name` property is for debug purposes only.
*
* The `equals` property specifies the comparer function to use to determine if a newly produced
* value differs from the previous value. Two comparers are provided in the library; `defaultComparer`
* compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.
* Structural comparison can be convenient if you always produce a new aggregated object and
* don't want to notify observers if it is structurally the same.
* This is useful for working with vectors, mouse coordinates etc.
*/
constructor(options: IComputedValueOptions<T>);
onBecomeStale_(): void;
onBOL: Set<Lambda> | undefined;
onBUOL: Set<Lambda> | undefined;
onBO(): void;
onBUO(): void;
/**
* Returns the current value of this computed value.
* Will evaluate its computation first if needed.
*/
get(): T;
set(value: T): void;
trackAndCompute(): boolean;
computeValue_(track: boolean): T | CaughtException;
suspend_(): void;
observe_(listener: (change: IComputedDidChange<T>) => void, fireImmediately?: boolean): Lambda;
warnAboutUntrackedRead_(): void;
toString(): string;
valueOf(): T;
[Symbol.toPrimitive](): T;
}
export declare const isComputedValue: (x: any) => x is ComputedValue<unknown>;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "bc86d0fa-d8e2-4505-a93c-b03e92666c14",
"subMetas": {}
}
+73
View File
@@ -0,0 +1,73 @@
import { IAtom, IDepTreeNode, IObservable } from "../internal";
export declare enum IDerivationState_ {
NOT_TRACKING_ = -1,
UP_TO_DATE_ = 0,
POSSIBLY_STALE_ = 1,
STALE_ = 2
}
export declare enum TraceMode {
NONE = 0,
LOG = 1,
BREAK = 2
}
/**
* A derivation is everything that can be derived from the state (all the atoms) in a pure manner.
* See https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74
*/
export interface IDerivation extends IDepTreeNode {
observing_: IObservable[];
newObserving_: null | IObservable[];
dependenciesState_: IDerivationState_;
/**
* Id of the current run of a derivation. Each time the derivation is tracked
* this number is increased by one. This number is globally unique
*/
runId_: number;
/**
* amount of dependencies used by the derivation in this run, which has not been bound yet.
*/
unboundDepsCount_: number;
onBecomeStale_(): void;
isTracing_: TraceMode;
/**
* warn if the derivation has no dependencies after creation/update
*/
requiresObservable_?: boolean;
}
export declare class CaughtException {
cause: any;
constructor(cause: any);
}
export declare function isCaughtException(e: any): e is CaughtException;
/**
* Finds out whether any dependency of the derivation has actually changed.
* If dependenciesState is 1 then it will recalculate dependencies,
* if any dependency changed it will propagate it by changing dependenciesState to 2.
*
* By iterating over the dependencies in the same order that they were reported and
* stopping on the first change, all the recalculations are only called for ComputedValues
* that will be tracked by derivation. That is because we assume that if the first x
* dependencies of the derivation doesn't change then the derivation should run the same way
* up until accessing x-th dependency.
*/
export declare function shouldCompute(derivation: IDerivation): boolean;
export declare function isComputingDerivation(): boolean;
export declare function checkIfStateModificationsAreAllowed(atom: IAtom): void;
export declare function checkIfStateReadsAreAllowed(observable: IObservable): void;
/**
* Executes the provided function `f` and tracks which observables are being accessed.
* The tracking information is stored on the `derivation` object and the derivation is registered
* as observer of any of the accessed observables.
*/
export declare function trackDerivedFunction<T>(derivation: IDerivation, f: () => T, context: any): any;
export declare function clearObserving(derivation: IDerivation): void;
export declare function untracked<T>(action: () => T): T;
export declare function untrackedStart(): IDerivation | null;
export declare function untrackedEnd(prev: IDerivation | null): void;
export declare function allowStateReadsStart(allowStateReads: boolean): boolean;
export declare function allowStateReadsEnd(prev: boolean): void;
/**
* needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0
*
*/
export declare function changeDependenciesStateTo0(derivation: IDerivation): void;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "62978fe5-ca25-43a9-b3d4-3e5d55fdf89d",
"subMetas": {}
}
+112
View File
@@ -0,0 +1,112 @@
import { IDerivation, IObservable, Reaction } from "../internal";
import { ComputedValue } from "./computedvalue";
export declare type IUNCHANGED = {};
export declare class MobXGlobals {
/**
* MobXGlobals version.
* MobX compatiblity with other versions loaded in memory as long as this version matches.
* It indicates that the global state still stores similar information
*
* N.B: this version is unrelated to the package version of MobX, and is only the version of the
* internal state storage of MobX, and can be the same across many different package versions
*/
version: number;
/**
* globally unique token to signal unchanged
*/
UNCHANGED: IUNCHANGED;
/**
* Currently running derivation
*/
trackingDerivation: IDerivation | null;
/**
* Currently running reaction. This determines if we currently have a reactive context.
* (Tracking derivation is also set for temporal tracking of computed values inside actions,
* but trackingReaction can only be set by a form of Reaction)
*/
trackingContext: Reaction | ComputedValue<any> | null;
/**
* Each time a derivation is tracked, it is assigned a unique run-id
*/
runId: number;
/**
* 'guid' for general purpose. Will be persisted amongst resets.
*/
mobxGuid: number;
/**
* Are we in a batch block? (and how many of them)
*/
inBatch: number;
/**
* Observables that don't have observers anymore, and are about to be
* suspended, unless somebody else accesses it in the same batch
*
* @type {IObservable[]}
*/
pendingUnobservations: IObservable[];
/**
* List of scheduled, not yet executed, reactions.
*/
pendingReactions: Reaction[];
/**
* Are we currently processing reactions?
*/
isRunningReactions: boolean;
/**
* Is it allowed to change observables at this point?
* In general, MobX doesn't allow that when running computations and React.render.
* To ensure that those functions stay pure.
*/
allowStateChanges: boolean;
/**
* Is it allowed to read observables at this point?
* Used to hold the state needed for `observableRequiresReaction`
*/
allowStateReads: boolean;
/**
* If strict mode is enabled, state changes are by default not allowed
*/
enforceActions: boolean | "always";
/**
* Spy callbacks
*/
spyListeners: {
(change: any): void;
}[];
/**
* Globally attached error handlers that react specifically to errors in reactions
*/
globalReactionErrorHandlers: ((error: any, derivation: IDerivation) => void)[];
/**
* Warn if computed values are accessed outside a reactive context
*/
computedRequiresReaction: boolean;
/**
* (Experimental)
* Warn if you try to create to derivation / reactive context without accessing any observable.
*/
reactionRequiresObservable: boolean;
/**
* (Experimental)
* Warn if observables are accessed outside a reactive context
*/
observableRequiresReaction: boolean;
disableErrorBoundaries: boolean;
suppressReactionErrors: boolean;
useProxies: boolean;
verifyProxies: boolean;
/**
* False forces all object's descriptors to
* writable: true
* configurable: true
*/
safeDescriptors: boolean;
}
export declare let globalState: MobXGlobals;
export declare function isolateGlobalState(): void;
export declare function getGlobalState(): any;
/**
* For testing purposes only; this will break the internal state of existing observables,
* but can be used to get back at a stable state after throwing errors
*/
export declare function resetGlobalState(): void;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "c635e75d-4b5d-40c0-b877-ed547746a404",
"subMetas": {}
}
+45
View File
@@ -0,0 +1,45 @@
import { Lambda, IDerivation, IDerivationState_ } from "../internal";
export interface IDepTreeNode {
name_: string;
observing_?: IObservable[];
}
export interface IObservable extends IDepTreeNode {
diffValue_: number;
/**
* Id of the derivation *run* that last accessed this observable.
* If this id equals the *run* id of the current derivation,
* the dependency is already established
*/
lastAccessedBy_: number;
isBeingObserved_: boolean;
lowestObserverState_: IDerivationState_;
isPendingUnobservation_: boolean;
observers_: Set<IDerivation>;
onBUO(): void;
onBO(): void;
onBUOL: Set<Lambda> | undefined;
onBOL: Set<Lambda> | undefined;
}
export declare function hasObservers(observable: IObservable): boolean;
export declare function getObservers(observable: IObservable): Set<IDerivation>;
export declare function addObserver(observable: IObservable, node: IDerivation): void;
export declare function removeObserver(observable: IObservable, node: IDerivation): void;
export declare function queueForUnobservation(observable: IObservable): void;
/**
* Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.
* During a batch `onBecomeUnobserved` will be called at most once per observable.
* Avoids unnecessary recalculations.
*/
export declare function startBatch(): void;
export declare function endBatch(): void;
export declare function reportObserved(observable: IObservable): boolean;
/**
* NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly
* It will propagate changes to observers from previous run
* It's hard or maybe impossible (with reasonable perf) to get it right with current approach
* Hopefully self reruning autoruns aren't a feature people should depend on
* Also most basic use cases should be ok
*/
export declare function propagateChanged(observable: IObservable): void;
export declare function propagateChangeConfirmed(observable: IObservable): void;
export declare function propagateMaybeChanged(observable: IObservable): void;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "259a7031-1e0d-4e2e-9049-f10290d5e3ac",
"subMetas": {}
}
+62
View File
@@ -0,0 +1,62 @@
import { IDerivation, IDerivationState_, IObservable, Lambda, TraceMode } from "../internal";
/**
* Reactions are a special kind of derivations. Several things distinguishes them from normal reactive computations
*
* 1) They will always run, whether they are used by other computations or not.
* This means that they are very suitable for triggering side effects like logging, updating the DOM and making network requests.
* 2) They are not observable themselves
* 3) They will always run after any 'normal' derivations
* 4) They are allowed to change the state and thereby triggering themselves again, as long as they make sure the state propagates to a stable state in a reasonable amount of iterations.
*
* The state machine of a Reaction is as follows:
*
* 1) after creating, the reaction should be started by calling `runReaction` or by scheduling it (see also `autorun`)
* 2) the `onInvalidate` handler should somehow result in a call to `this.track(someFunction)`
* 3) all observables accessed in `someFunction` will be observed by this reaction.
* 4) as soon as some of the dependencies has changed the Reaction will be rescheduled for another run (after the current mutation or transaction). `isScheduled` will yield true once a dependency is stale and during this period
* 5) `onInvalidate` will be called, and we are back at step 1.
*
*/
export interface IReactionPublic {
dispose(): void;
trace(enterBreakPoint?: boolean): void;
}
export interface IReactionDisposer {
(): void;
$mobx: Reaction;
}
export declare class Reaction implements IDerivation, IReactionPublic {
name_: string;
private onInvalidate_;
private errorHandler_?;
requiresObservable_: boolean;
observing_: IObservable[];
newObserving_: IObservable[];
dependenciesState_: IDerivationState_;
diffValue_: number;
runId_: number;
unboundDepsCount_: number;
isDisposed_: boolean;
isScheduled_: boolean;
isTrackPending_: boolean;
isRunning_: boolean;
isTracing_: TraceMode;
constructor(name_: string, onInvalidate_: () => void, errorHandler_?: ((error: any, derivation: IDerivation) => void) | undefined, requiresObservable_?: boolean);
onBecomeStale_(): void;
schedule_(): void;
isScheduled(): boolean;
/**
* internal, use schedule() if you intend to kick off a reaction
*/
runReaction_(): void;
track(fn: () => void): void;
reportExceptionInDerivation_(error: any): void;
dispose(): void;
getDisposer_(): IReactionDisposer;
toString(): string;
trace(enterBreakPoint?: boolean): void;
}
export declare function onReactionError(handler: (error: any, derivation: IDerivation) => void): Lambda;
export declare function runReactions(): void;
export declare const isReaction: (x: any) => x is Reaction;
export declare function setReactionScheduler(fn: (f: () => void) => void): void;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "639733f7-5764-4d38-aa3a-aea86a3d2a83",
"subMetas": {}
}
+37
View File
@@ -0,0 +1,37 @@
import { IComputedDidChange } from "./computedvalue";
import { IValueDidChange, IBoxDidChange } from "../types/observablevalue";
import { IObjectDidChange } from "../types/observableobject";
import { IArrayDidChange } from "../types/observablearray";
import { Lambda, ISetDidChange, IMapDidChange } from "../internal";
export declare function isSpyEnabled(): boolean;
export declare type PureSpyEvent = {
type: "action";
name: string;
object: unknown;
arguments: unknown[];
} | {
type: "scheduled-reaction";
name: string;
} | {
type: "reaction";
name: string;
} | {
type: "error";
name: string;
message: string;
error: string;
} | IComputedDidChange<unknown> | IObjectDidChange<unknown> | IArrayDidChange<unknown> | IMapDidChange<unknown, unknown> | ISetDidChange<unknown> | IValueDidChange<unknown> | IBoxDidChange<unknown> | {
type: "report-end";
spyReportEnd: true;
time?: number;
};
declare type SpyEvent = PureSpyEvent & {
spyReportStart?: true;
};
export declare function spyReport(event: SpyEvent): void;
export declare function spyReportStart(event: PureSpyEvent): void;
export declare function spyReportEnd(change?: {
time?: number;
}): void;
export declare function spy(listener: (change: SpyEvent) => void): Lambda;
export {};
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "86e2f566-eaf3-4d09-a093-2a2cc5bda60c",
"subMetas": {}
}
+2
View File
@@ -0,0 +1,2 @@
export { IObservable, IDepTreeNode, Reaction, IReactionPublic, IReactionDisposer, untracked, IAtom, createAtom, spy, IComputedValue, IEqualsComparer, comparer, IEnhancer, IInterceptable, IInterceptor, IListenable, IObjectWillChange, IObjectDidChange, isObservableObject, IValueDidChange, IValueWillChange, IObservableValue, isObservableValue as isBoxedObservable, IObservableArray, IArrayWillChange, IArrayWillSplice, IArraySplice, IArrayUpdate, IArrayDidChange, isObservableArray, IKeyValueMap, ObservableMap, IMapEntries, IMapEntry, IMapWillChange, IMapDidChange, isObservableMap, IObservableMapInitialValues, ObservableSet, isObservableSet, ISetDidChange, ISetWillChange, IObservableSetInitialValues, transaction, observable, IObservableFactory, CreateObservableOptions, computed, IComputedFactory, isObservable, isObservableProp, isComputed, isComputedProp, extendObservable, observe, intercept, autorun, IAutorunOptions, reaction, IReactionOptions, when, IWhenOptions, action, isAction, runInAction, IActionFactory, keys, values, entries, set, remove, has, get, apiOwnKeys as ownKeys, apiDefineProperty as defineProperty, configure, onBecomeObserved, onBecomeUnobserved, flow, isFlow, flowResult, FlowCancellationError, isFlowCancellationError, toJS, trace, IObserverTree, IDependencyTree, getDependencyTree, getObserverTree, resetGlobalState as _resetGlobalState, getGlobalState as _getGlobalState, getDebugName, getAtom, getAdministration as _getAdministration, allowStateChanges as _allowStateChanges, runInAction as _allowStateChangesInsideComputed, // This has become the default behavior in Mobx 6
Lambda, $mobx, isComputingDerivation as _isComputingDerivation, onReactionError, interceptReads as _interceptReads, IComputedValueOptions, IActionRunInfo, _startAction, _endAction, allowStateReadsStart as _allowStateReadsStart, allowStateReadsEnd as _allowStateReadsEnd, makeObservable, makeAutoObservable, autoAction as _autoAction, AnnotationsMap, AnnotationMapEntry, override } from "./internal";
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "c6cb122f-9b4c-4143-bf06-e06973ff9c2f",
"subMetas": {}
}
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "af6f62f0-e12d-472d-a765-bb7ffe629b40",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "d56e8877-9f71-433b-a53c-6e1453b32598",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
@@ -0,0 +1,8 @@
import { ObservableObjectAdministration, Annotation } from "../internal";
export declare function createActionAnnotation(name: string, options?: object): Annotation;
export declare function createActionDescriptor(adm: ObservableObjectAdministration, annotation: Annotation, key: PropertyKey, descriptor: PropertyDescriptor, safeDescriptors?: boolean): {
value: Function;
configurable: boolean;
enumerable: boolean;
writable: boolean;
};
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "c0ada3a6-5516-4e26-8353-0c975edc4d2f",
"subMetas": {}
}
+3
View File
@@ -0,0 +1,3 @@
import { Annotation } from "../internal";
export declare const autoAnnotation: Annotation;
export declare function createAutoAnnotation(options?: object): Annotation;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "6521ff91-a040-4005-8a99-f42c7fca07c1",
"subMetas": {}
}
@@ -0,0 +1,2 @@
import { Annotation } from "../internal";
export declare function createComputedAnnotation(name: string, options?: object): Annotation;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "de9c8a46-03e7-4072-b819-da7ec0de1757",
"subMetas": {}
}
+2
View File
@@ -0,0 +1,2 @@
import { IIsObservableObject, CreateObservableOptions } from "../internal";
export declare function asDynamicObservableObject(target: any, options?: CreateObservableOptions): IIsObservableObject;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "5bb30ab7-8eda-4bbe-8998-f53641952b5d",
"subMetas": {}
}
+2
View File
@@ -0,0 +1,2 @@
import { Annotation } from "../internal";
export declare function createFlowAnnotation(name: string, options?: object): Annotation;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "14decc35-0378-458f-aff4-495d5b7fbec1",
"subMetas": {}
}
+8
View File
@@ -0,0 +1,8 @@
import { Lambda } from "../internal";
export declare type IInterceptor<T> = (change: T) => T | null;
export interface IInterceptable<T> {
interceptors_: IInterceptor<T>[] | undefined;
}
export declare function hasInterceptors(interceptable: IInterceptable<any>): boolean;
export declare function registerInterceptor<T>(interceptable: IInterceptable<T>, handler: IInterceptor<T>): Lambda;
export declare function interceptChange<T>(interceptable: IInterceptable<T | null>, change: T | null): T | null;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "446c1efb-8e52-4043-be6d-6122f7f53a18",
"subMetas": {}
}
@@ -0,0 +1,3 @@
import { IEnhancer, IObservableArray } from "../internal";
export declare function reserveArrayBuffer(max: number): void;
export declare function createLegacyArray<T>(initialValues: T[] | undefined, enhancer: IEnhancer<T>, name?: string): IObservableArray<T>;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "f1282bbe-0b16-4535-9d48-a6552f513d0b",
"subMetas": {}
}
+7
View File
@@ -0,0 +1,7 @@
import { Lambda } from "../internal";
export interface IListenable {
changeListeners_: Function[] | undefined;
}
export declare function hasListeners(listenable: IListenable): boolean;
export declare function registerListener(listenable: IListenable, handler: Function): Lambda;
export declare function notifyListeners<T>(listenable: IListenable, change: T): void;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "3a5529da-5699-4263-ab46-4176f987b912",
"subMetas": {}
}
+7
View File
@@ -0,0 +1,7 @@
export interface IEnhancer<T> {
(newValue: T, oldValue: T | undefined, name: string): T;
}
export declare function deepEnhancer(v: any, _: any, name: any): any;
export declare function shallowEnhancer(v: any, _: any, name: any): any;
export declare function referenceEnhancer(newValue?: any): any;
export declare function refStructEnhancer(v: any, oldValue: any): any;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "508746dd-67ff-4e8a-a311-22ded66981e7",
"subMetas": {}
}
@@ -0,0 +1,2 @@
import { Annotation } from "../internal";
export declare function createObservableAnnotation(name: string, options?: object): Annotation;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "b12e6389-80f4-4b7e-86ba-f89172396ed5",
"subMetas": {}
}
+85
View File
@@ -0,0 +1,85 @@
import { IAtom, IEnhancer, IInterceptable, IInterceptor, IListenable, Lambda } from "../internal";
export declare const UPDATE = "update";
export declare const MAX_SPLICE_SIZE = 10000;
export interface IObservableArray<T = any> extends Array<T> {
spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[];
clear(): T[];
replace(newItems: T[]): T[];
remove(value: T): boolean;
toJSON(): T[];
}
interface IArrayBaseChange<T> {
object: IObservableArray<T>;
observableKind: "array";
debugObjectName: string;
index: number;
}
export declare type IArrayDidChange<T = any> = IArrayUpdate<T> | IArraySplice<T>;
export interface IArrayUpdate<T = any> extends IArrayBaseChange<T> {
type: "update";
newValue: T;
oldValue: T;
}
export interface IArraySplice<T = any> extends IArrayBaseChange<T> {
type: "splice";
added: T[];
addedCount: number;
removed: T[];
removedCount: number;
}
export interface IArrayWillChange<T = any> {
object: IObservableArray<T>;
index: number;
type: "update";
newValue: T;
}
export interface IArrayWillSplice<T = any> {
object: IObservableArray<T>;
index: number;
type: "splice";
added: T[];
removedCount: number;
}
export declare class ObservableArrayAdministration implements IInterceptable<IArrayWillChange<any> | IArrayWillSplice<any>>, IListenable {
owned_: boolean;
legacyMode_: boolean;
atom_: IAtom;
readonly values_: any[];
interceptors_: any;
changeListeners_: any;
enhancer_: (newV: any, oldV: any | undefined) => any;
dehancer: any;
proxy_: IObservableArray<any>;
lastKnownLength_: number;
constructor(name: string | undefined, enhancer: IEnhancer<any>, owned_: boolean, legacyMode_: boolean);
dehanceValue_(value: any): any;
dehanceValues_(values: any[]): any[];
intercept_(handler: IInterceptor<IArrayWillChange<any> | IArrayWillSplice<any>>): Lambda;
observe_(listener: (changeData: IArrayDidChange<any>) => void, fireImmediately?: boolean): Lambda;
getArrayLength_(): number;
setArrayLength_(newLength: number): void;
updateArrayLength_(oldLength: number, delta: number): void;
spliceWithArray_(index: number, deleteCount?: number, newItems?: any[]): any[];
spliceItemsIntoValues_(index: number, deleteCount: number, newItems: any[]): any[];
notifyArrayChildUpdate_(index: number, newValue: any, oldValue: any): void;
notifyArraySplice_(index: number, added: any[], removed: any[]): void;
get_(index: number): any | undefined;
set_(index: number, newValue: any): void;
}
export declare function createObservableArray<T>(initialValues: T[] | undefined, enhancer: IEnhancer<T>, name?: string, owned?: boolean): IObservableArray<T>;
export declare var arrayExtensions: {
clear(): any[];
replace(newItems: any[]): any[];
toJSON(): any[];
splice(index: number, deleteCount?: number | undefined, ...newItems: any[]): any[];
spliceWithArray(index: number, deleteCount?: number | undefined, newItems?: any[] | undefined): any[];
push(...items: any[]): number;
pop(): any;
shift(): any;
unshift(...items: any[]): number;
reverse(): any[];
sort(): any[];
remove(value: any): boolean;
};
export declare function isObservableArray(thing: any): thing is IObservableArray<any>;
export {};
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "24aca4bb-1d07-4a91-8fab-6cad31267a17",
"subMetas": {}
}
+76
View File
@@ -0,0 +1,76 @@
import { $mobx, IEnhancer, IInterceptable, IInterceptor, IListenable, Lambda, ObservableValue, IAtom } from "../internal";
export interface IKeyValueMap<V = any> {
[key: string]: V;
}
export declare type IMapEntry<K = any, V = any> = [K, V];
export declare type IMapEntries<K = any, V = any> = IMapEntry<K, V>[];
export declare type IMapDidChange<K = any, V = any> = {
observableKind: "map";
debugObjectName: string;
} & ({
object: ObservableMap<K, V>;
name: K;
type: "update";
newValue: V;
oldValue: V;
} | {
object: ObservableMap<K, V>;
name: K;
type: "add";
newValue: V;
} | {
object: ObservableMap<K, V>;
name: K;
type: "delete";
oldValue: V;
});
export interface IMapWillChange<K = any, V = any> {
object: ObservableMap<K, V>;
type: "update" | "add" | "delete";
name: K;
newValue?: V;
}
export declare const ADD = "add";
export declare const DELETE = "delete";
export declare type IObservableMapInitialValues<K = any, V = any> = IMapEntries<K, V> | IKeyValueMap<V> | Map<K, V>;
export declare class ObservableMap<K = any, V = any> implements Map<K, V>, IInterceptable<IMapWillChange<K, V>>, IListenable {
enhancer_: IEnhancer<V>;
name_: string;
[$mobx]: {};
data_: Map<K, ObservableValue<V>>;
hasMap_: Map<K, ObservableValue<boolean>>;
keysAtom_: IAtom;
interceptors_: any;
changeListeners_: any;
dehancer: any;
constructor(initialData?: IObservableMapInitialValues<K, V>, enhancer_?: IEnhancer<V>, name_?: string);
private has_;
has(key: K): boolean;
set(key: K, value: V): this;
delete(key: K): boolean;
private updateValue_;
private addValue_;
get(key: K): V | undefined;
private dehanceValue_;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
entries(): IterableIterator<IMapEntry<K, V>>;
[Symbol.iterator](): IterableIterator<IMapEntry<K, V>>;
forEach(callback: (value: V, key: K, object: Map<K, V>) => void, thisArg?: any): void;
/** Merge another object into this object, returns this. */
merge(other: ObservableMap<K, V> | IKeyValueMap<V> | any): ObservableMap<K, V>;
clear(): void;
replace(values: ObservableMap<K, V> | IKeyValueMap<V> | any): ObservableMap<K, V>;
get size(): number;
toString(): string;
toJSON(): [K, V][];
get [Symbol.toStringTag](): string;
/**
* Observes this object. Triggers for the events 'add', 'update' and 'delete'.
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
* for callback details
*/
observe_(listener: (changes: IMapDidChange<K, V>) => void, fireImmediately?: boolean): Lambda;
intercept_(handler: IInterceptor<IMapWillChange<K, V>>): Lambda;
}
export declare var isObservableMap: (thing: any) => thing is ObservableMap<any, any>;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "fb311371-fcd5-4109-aa9f-fe75163d972d",
"subMetas": {}
}
+98
View File
@@ -0,0 +1,98 @@
import { CreateObservableOptions, Annotation, ComputedValue, IAtom, IComputedValueOptions, IEnhancer, IInterceptable, IListenable, Lambda, ObservableValue } from "../internal";
export declare type IObjectDidChange<T = any> = {
observableKind: "object";
name: PropertyKey;
object: T;
debugObjectName: string;
} & ({
type: "add";
newValue: any;
} | {
type: "update";
oldValue: any;
newValue: any;
} | {
type: "remove";
oldValue: any;
});
export declare type IObjectWillChange<T = any> = {
object: T;
type: "update" | "add";
name: PropertyKey;
newValue: any;
} | {
object: T;
type: "remove";
name: PropertyKey;
};
export declare class ObservableObjectAdministration implements IInterceptable<IObjectWillChange>, IListenable {
target_: any;
values_: Map<string | number | symbol, ObservableValue<any> | ComputedValue<any>>;
name_: string;
defaultAnnotation_: Annotation;
keysAtom_: IAtom;
changeListeners_: any;
interceptors_: any;
proxy_: any;
isPlainObject_: boolean;
appliedAnnotations_?: object;
private pendingKeys_;
constructor(target_: any, values_: Map<string | number | symbol, ObservableValue<any> | ComputedValue<any>>, name_: string, defaultAnnotation_?: Annotation);
getObservablePropValue_(key: PropertyKey): any;
setObservablePropValue_(key: PropertyKey, newValue: any): boolean | null;
get_(key: PropertyKey): any;
/**
* @param {PropertyKey} key
* @param {any} value
* @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
set_(key: PropertyKey, value: any, proxyTrap?: boolean): boolean | null;
has_(key: PropertyKey): boolean;
/**
* @param {PropertyKey} key
* @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop
*/
make_(key: PropertyKey, annotation: Annotation | boolean): void;
/**
* @param {PropertyKey} key
* @param {PropertyDescriptor} descriptor
* @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
extend_(key: PropertyKey, descriptor: PropertyDescriptor, annotation: Annotation | boolean, proxyTrap?: boolean): boolean | null;
/**
* @param {PropertyKey} key
* @param {PropertyDescriptor} descriptor
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
defineProperty_(key: PropertyKey, descriptor: PropertyDescriptor, proxyTrap?: boolean): boolean | null;
defineObservableProperty_(key: PropertyKey, value: any, enhancer: IEnhancer<any>, proxyTrap?: boolean): boolean | null;
defineComputedProperty_(key: PropertyKey, options: IComputedValueOptions<any>, proxyTrap?: boolean): boolean | null;
/**
* @param {PropertyKey} key
* @param {PropertyDescriptor} descriptor
* @param {boolean} proxyTrap whether it's called from proxy trap
* @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
*/
delete_(key: PropertyKey, proxyTrap?: boolean): boolean | null;
/**
* Observes this object. Triggers for the events 'add', 'update' and 'delete'.
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
* for callback details
*/
observe_(callback: (changes: IObjectDidChange) => void, fireImmediately?: boolean): Lambda;
intercept_(handler: any): Lambda;
notifyPropertyAddition_(key: PropertyKey, value: any): void;
ownKeys_(): PropertyKey[];
keys_(): PropertyKey[];
}
export interface IIsObservableObject {
$mobx: ObservableObjectAdministration;
}
export declare function asObservableObject(target: any, options?: CreateObservableOptions): IIsObservableObject;
export declare function isObservableObject(thing: any): boolean;
export declare function recordAnnotationApplied(adm: ObservableObjectAdministration, annotation: Annotation, key: PropertyKey): void;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "e4d03fba-32fc-4f0f-8fe6-1361d03b7ea7",
"subMetas": {}
}
+53
View File
@@ -0,0 +1,53 @@
import { $mobx, IEnhancer, IListenable, Lambda, IInterceptable, IInterceptor } from "../internal";
export declare type IObservableSetInitialValues<T> = Set<T> | readonly T[];
export declare type ISetDidChange<T = any> = {
object: ObservableSet<T>;
observableKind: "set";
debugObjectName: string;
type: "add";
newValue: T;
} | {
object: ObservableSet<T>;
observableKind: "set";
debugObjectName: string;
type: "delete";
oldValue: T;
};
export declare type ISetWillChange<T = any> = {
type: "delete";
object: ObservableSet<T>;
oldValue: T;
} | {
type: "add";
object: ObservableSet<T>;
newValue: T;
};
export declare class ObservableSet<T = any> implements Set<T>, IInterceptable<ISetWillChange>, IListenable {
name_: string;
[$mobx]: {};
private data_;
private atom_;
changeListeners_: any;
interceptors_: any;
dehancer: any;
enhancer_: (newV: any, oldV: any | undefined) => any;
constructor(initialData?: IObservableSetInitialValues<T>, enhancer?: IEnhancer<T>, name_?: string);
private dehanceValue_;
clear(): void;
forEach(callbackFn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
get size(): number;
add(value: T): this;
delete(value: any): boolean;
has(value: any): boolean;
entries(): IterableIterator<[T, T]>;
keys(): IterableIterator<T>;
values(): IterableIterator<T>;
replace(other: ObservableSet<T> | IObservableSetInitialValues<T>): ObservableSet<T>;
observe_(listener: (changes: ISetDidChange<T>) => void, fireImmediately?: boolean): Lambda;
intercept_(handler: IInterceptor<ISetWillChange<T>>): Lambda;
toJSON(): T[];
toString(): string;
[Symbol.iterator](): IterableIterator<T>;
get [Symbol.toStringTag](): string;
}
export declare var isObservableSet: (thing: any) => thing is ObservableSet<any>;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "23fb3467-d0f9-4d8d-bb04-8f805287ec45",
"subMetas": {}
}
+51
View File
@@ -0,0 +1,51 @@
import { Atom, IEnhancer, IInterceptable, IEqualsComparer, IInterceptor, IListenable, Lambda } from "../internal";
export interface IValueWillChange<T> {
object: IObservableValue<T>;
type: "update";
newValue: T;
}
export declare type IValueDidChange<T = any> = {
type: "update";
observableKind: "value";
object: IObservableValue<T>;
debugObjectName: string;
newValue: unknown;
oldValue: unknown;
};
export declare type IBoxDidChange<T = any> = {
type: "create";
observableKind: "value";
object: IObservableValue<T>;
debugObjectName: string;
newValue: unknown;
} | IValueDidChange<T>;
export interface IObservableValue<T> {
get(): T;
set(value: T): void;
intercept_(handler: IInterceptor<IValueWillChange<T>>): Lambda;
observe_(listener: (change: IValueDidChange<T>) => void, fireImmediately?: boolean): Lambda;
}
export declare class ObservableValue<T> extends Atom implements IObservableValue<T>, IInterceptable<IValueWillChange<T>>, IListenable {
enhancer: IEnhancer<T>;
name_: string;
private equals;
hasUnreportedChange_: boolean;
interceptors_: any;
changeListeners_: any;
value_: any;
dehancer: any;
constructor(value: T, enhancer: IEnhancer<T>, name_?: string, notifySpy?: boolean, equals?: IEqualsComparer<any>);
private dehanceValue;
set(newValue: T): void;
private prepareNewValue_;
setNewValue_(newValue: T): void;
get(): T;
intercept_(handler: IInterceptor<IValueWillChange<T>>): Lambda;
observe_(listener: (change: IValueDidChange<T>) => void, fireImmediately?: boolean): Lambda;
raw(): any;
toJSON(): T;
toString(): string;
valueOf(): T;
[Symbol.toPrimitive](): T;
}
export declare const isObservableValue: (x: any) => x is IObservableValue<any>;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "ad823519-6e73-4152-9ca3-427f9005e931",
"subMetas": {}
}
@@ -0,0 +1,3 @@
import { Annotation } from "../internal";
export declare const override: Annotation & PropertyDecorator;
export declare function isOverride(annotation: Annotation): boolean;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "4e95b329-5014-44e0-846b-edca61351db8",
"subMetas": {}
}
+4
View File
@@ -0,0 +1,4 @@
import { IDepTreeNode } from "../internal";
export declare function getAtom(thing: any, property?: PropertyKey): IDepTreeNode;
export declare function getAdministration(thing: any, property?: string): any;
export declare function getDebugName(thing: any, property?: string): string;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "7ff0915c-3e0e-4ef9-97c8-dfe200b5d48e",
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "f1962802-cc62-433a-8ffb-edad2bb1dc61",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+14
View File
@@ -0,0 +1,14 @@
export interface IEqualsComparer<T> {
(a: T, b: T): boolean;
}
declare function identityComparer(a: any, b: any): boolean;
declare function structuralComparer(a: any, b: any): boolean;
declare function shallowComparer(a: any, b: any): boolean;
declare function defaultComparer(a: any, b: any): boolean;
export declare const comparer: {
identity: typeof identityComparer;
structural: typeof structuralComparer;
default: typeof defaultComparer;
shallow: typeof shallowComparer;
};
export {};
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "6bc63ec0-afa0-430d-8f19-f51cfd6d788a",
"subMetas": {}
}
+1
View File
@@ -0,0 +1 @@
export declare function deepEqual(a: any, b: any, depth?: number): boolean;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "0ee281b6-48ef-40c3-ad96-6078a6672d15",
"subMetas": {}
}
+1
View File
@@ -0,0 +1 @@
export declare function getGlobal(): any;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "d81c6f2c-0566-44a8-9856-27497801d925",
"subMetas": {}
}
+1
View File
@@ -0,0 +1 @@
export declare function makeIterable<T>(iterator: Iterator<T>): IterableIterator<T>;
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "4524da62-f78d-4dfd-9a3d-0a3036e6ce7d",
"subMetas": {}
}
+45
View File
@@ -0,0 +1,45 @@
export declare const assign: {
<T, U>(target: T, source: U): T & U;
<T_1, U_1, V>(target: T_1, source1: U_1, source2: V): T_1 & U_1 & V;
<T_2, U_2, V_1, W>(target: T_2, source1: U_2, source2: V_1, source3: W): T_2 & U_2 & V_1 & W;
(target: object, ...sources: any[]): any;
};
export declare const getDescriptor: (o: any, p: string | number | symbol) => PropertyDescriptor | undefined;
export declare const defineProperty: (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType<any>) => any;
export declare const objectPrototype: Object;
export declare const EMPTY_ARRAY: never[];
export declare const EMPTY_OBJECT: {};
export interface Lambda {
(): void;
name?: string;
}
export declare function assertProxies(): void;
export declare function warnAboutProxyRequirement(msg: string): void;
export declare function getNextId(): number;
/**
* Makes sure that the provided function is invoked at most once.
*/
export declare function once(func: Lambda): Lambda;
export declare const noop: () => void;
export declare function isFunction(fn: any): fn is Function;
export declare function isString(value: any): value is string;
export declare function isStringish(value: any): value is string | number | symbol;
export declare function isObject(value: any): value is Object;
export declare function isPlainObject(value: any): boolean;
export declare function isGenerator(obj: any): boolean;
export declare function addHiddenProp(object: any, propName: PropertyKey, value: any): void;
export declare function addHiddenFinalProp(object: any, propName: PropertyKey, value: any): void;
export declare function createInstanceofPredicate<T>(name: string, theClass: new (...args: any[]) => T): (x: any) => x is T;
export declare function isES6Map(thing: any): boolean;
export declare function isES6Set(thing: any): thing is Set<any>;
/**
* Returns the following: own enumerable keys and symbols.
*/
export declare function getPlainObjectKeys(object: any): (string | symbol)[];
export declare const ownKeys: (target: any) => PropertyKey[];
export declare function stringifyKey(key: any): string;
export declare function toPrimitive(value: any): any;
export declare function hasProp(target: Object, prop: PropertyKey): boolean;
export declare const getOwnPropertyDescriptors: <T>(o: T) => { [P in keyof T]: TypedPropertyDescriptor<T[P]>; } & {
[x: string]: PropertyDescriptor;
};
@@ -0,0 +1,5 @@
{
"ver": "2.0.0",
"uuid": "b5a51edd-92c4-4928-9054-11a2640c7bee",
"subMetas": {}
}
+121
View File
@@ -0,0 +1,121 @@
import { Drone_Event } from "./define/Event";
import { IDroneInfo, IDroneLocationInfo } from "./define/Interface";
import BaseComp from "./external/BaseComp";
const { ccclass, property } = cc._decorator;
@ccclass
export default class TestFakeData extends BaseComp {
protected onLoad(): void {
console.log('ken666::TestFakeData::onLoad()')
cc.tween(new cc.Node())
.delay(3)
.call(() => {
let data: Array<IDroneInfo> = [
{
droneName: '無人機A',
sort: 0,
id: 'Fly-A'
},
{
droneName: '無人機F',
sort: 5,
id: 'Fly-F'
},
{
droneName: '無人機E',
sort: 4,
id: 'Fly-E'
},
{
droneName: '無人機D',
sort: 3,
id: 'Fly-D'
},
{
droneName: '無人機H',
sort: 7,
id: 'Fly-H'
},
{
droneName: '無人機G',
sort: 6,
id: 'Fly-G'
},
{
droneName: '無人機B',
sort: 1,
id: 'Fly-B'
},
{
droneName: '無人機C',
sort: 2,
id: 'Fly-C'
},
]
console.log('ken666::delay3 send Drone_Event.DRONE_LIST')
this.emit(Drone_Event.DRONE_LIST, data)
})
.start()
cc.tween(new cc.Node())
.delay(1)
.call(() => {
let data: Array<IDroneLocationInfo> = [
{
id: 'Fly-A',
bettery: 10,
locationN: `12'34'56.7""`,
locationE: `98'76'54.0123""`
},
{
id: 'Fly-B',
bettery: 87,
locationN: `64'31'3.14""`,
locationE: `55'66'11""`
},
{
id: 'Fly-C',
bettery: 49,
locationN: `72'38'18.2""`,
locationE: `47'10'2.01""`
},
{
id: 'Fly-D',
bettery: 51,
locationN: `25'68'54.1""`,
locationE: `12'14'74""`
},
{
id: 'Fly-E',
bettery: 50,
locationN: `19'85'12.14""`,
locationE: `7'4'12.14""`
},
{
id: 'Fly-F',
bettery: 100,
locationN: `91'20'3.1""`,
locationE: `700'600'5.2""`
},
{
id: 'Fly-G',
bettery: 0,
locationN: `10'20'3.0""`,
locationE: `4'5'9.99""`
},
{
id: 'Fly-H',
bettery: 1,
locationN: `8'7'8.7""`,
locationE: `3'3'1.2""`
},
]
console.log('ken666::delay3 send Drone_Event.DRONE_DETAIL')
this.emit(Drone_Event.DRONE_DETAIL, data)
})
.start()
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "b116657e-0d07-4780-be00-745ebc450ded",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "b8c4541e-6396-48e4-81c1-00cb769f6488",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+5
View File
@@ -0,0 +1,5 @@
export enum Drone_Event {
DRONE_LIST = "DRONE_LIST",
DRONE_CLICK = "DRONE_CLICK",
DRONE_DETAIL = "DRONE_DETAIL"
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "cdb1cc38-359d-4018-bea6-be9719742642",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+19
View File
@@ -0,0 +1,19 @@
export interface IDroneInfo {
droneName: string
sort: number
id: string
}
export interface IDroneLocationInfo {
id: string
bettery: number
locationN: string
locationE: string
}
// export interface IRespose {
// success: boolean
// msg: string
// code: number
// t: IGameData
// }
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "193b039c-3e47-4399-923a-db6d86a6b41b",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "59cc8110-afbe-4cbb-915a-b20ca6dcffc0",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+58
View File
@@ -0,0 +1,58 @@
import { Drone_Event } from "../define/Event";
import { IDroneInfo, IDroneLocationInfo } from "../define/Interface";
import EmitterBase from "../external/EmitterBase";
import { Utils } from "../external/Utils";
import { makeAutoObservable } from "../Library/mobx/mobx";
export class CommonModel extends EmitterBase {
public static _instance: CommonModel = null;
public static get inst() {
if (CommonModel._instance == null) {
CommonModel._instance = new CommonModel()
}
return CommonModel._instance;
}
droneInfo: Array<IDroneInfo> = []
droneDetail: Array<IDroneLocationInfo> = []
constructor() {
super();
this.on(Drone_Event.DRONE_LIST, this.setDrone.bind(this))
this.on(Drone_Event.DRONE_DETAIL, this.setDroneDetail.bind(this))
makeAutoObservable(this)
}
private setDrone(droneInfo: Array<IDroneInfo>) {
console.log('setDrone')
droneInfo.sort((a, b) => a.sort - b.sort)
// this.droneInfo = Utils.deepClone(droneInfo)
this.droneInfo = droneInfo
}
private setDroneDetail(droneDetail: Array<IDroneLocationInfo>) {
console.log('setDroneDetail')
this.droneDetail = Utils.deepClone(droneDetail)
}
// async init() {
// const response = await httpSender.sendGet<IRespose>('/api/front/index/init', { deviceType: DeviceTypeCode[Common.curSkin] })
// if (response && response.success) {
// let gameData = response.t;
// cc.log(`init response:`, response);
// await this.setBanners(gameData.banners);
// // GameSocket.inst.connect(Common.brokerURL, Common.token)
// this.initGameData(gameData);
// this.followDealerInfo = gameData.userFollowInfoVO;
// this.userInfo.data = gameData;
// this.chipPrice = this.userInfo.chipInfo[0];
// LocalDataMgr.inst.resetLocalData();
// this.on(ClientEvents.LanguageChanged, this.onLanguageChanged.bind(this));
// return true;
// }
// else {
// cc.log(response);
// }
// return false;
// }
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "8643ce66-08cf-48f8-bcb3-20a64be2ed35",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+52
View File
@@ -0,0 +1,52 @@
import { Drone_Event } from "../define/Event";
import { IDroneInfo } from "../define/Interface";
import BaseComp from "../external/BaseComp";
import { autorun, Lambda, observe, reaction } from "../Library/mobx/mobx";
import { CommonModel } from "./CommonModel";
import SingleDroneItem from "./SingleDroneItem";
const { ccclass, property } = cc._decorator;
@ccclass
export default class DroneListManager extends BaseComp {
@property(cc.Node)
contentNode: cc.Node = null
@property(cc.Prefab)
dronePrefab: cc.Prefab = null
// private droneInfoDisposer: Lambda = null
onEnable() {
super.onEnable()
this._pool.push(reaction(this.initDroneList.bind(this), { fireImmediately: true }))
// this._pool.push(autorun( this.initDroneList.bind(this)))
// this.cancelObserve()
// this.droneInfoDisposer = observe(CommonModel, 'droneInfo', () => {
// this.initDroneList()
// })
}
onDisable() {
// this.off(Drone_Event.DRONE_LIST)
super.onDisable();
}
initDroneList() {
console.log('ken666::DroneListManager::initDroneList()')
this.contentNode.removeAllChildren()
CommonModel.inst.droneInfo.forEach(data => {
const {droneName, id} = data
let droneItem = cc.instantiate(this.dronePrefab)
let droneComponent = droneItem.getComponent(SingleDroneItem)
droneComponent.setData(droneName, id)
droneItem.parent = this.contentNode
})
}
// private cancelObserve() {
// if (this.droneInfoDisposer) {
// this.droneInfoDisposer()
// this.droneInfoDisposer = null;
// }
// }
}
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "d6fd8eb4-36e2-45ec-9bac-a15c73676c4b",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
@@ -0,0 +1,52 @@
import { Drone_Event } from "../define/Event";
import BaseComp from "../external/BaseComp";
import { CommonModel } from "./CommonModel";
const { ccclass, property } = cc._decorator;
@ccclass
export default class SingleDroneIfnoManager extends BaseComp {
@property(cc.Label)
idLabel: cc.Label = null
@property(cc.Label)
percetnLabel: cc.Label = null
@property(cc.Label)
locationNLabel: cc.Label = null
@property(cc.Label)
locationELabel: cc.Label = null
@property(cc.Sprite)
powerBarSprite: cc.Sprite = null
@property(cc.Color)
barColor: Array<cc.Color> = []
onEnable(): void {
super.onEnable()
this.on(Drone_Event.DRONE_CLICK, this.setSingleInfo.bind(this))
}
onDisable(): void {
this.off(Drone_Event.DRONE_CLICK)
super.onDisable()
}
setSingleInfo(id: string) {
console.log('setSingleInfo::id = ',id)
let detail = CommonModel.inst.droneDetail.find(data => data.id === id)
if (detail) {
const { droneName } = CommonModel.inst.droneInfo.find(data => data.id === id)
const { bettery, locationE, locationN } = detail
this.idLabel.string = droneName
this.percetnLabel.string = `${bettery}`
this.locationNLabel.string = locationN
this.locationELabel.string = locationE
this.powerBarSprite.fillRange = bettery / 100
if(bettery >= 80) {
this.powerBarSprite.node.color = this.barColor[2]
} else if(bettery <= 30) {
this.powerBarSprite.node.color = this.barColor[0]
} else {
this.powerBarSprite.node.color = this.barColor[1]
}
}
}
}
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "572d4d3c-1a65-4f19-8f22-1c41a1620942",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+24
View File
@@ -0,0 +1,24 @@
import { Drone_Event } from "../define/Event";
import BaseComp from "../external/BaseComp";
const {ccclass, property} = cc._decorator;
@ccclass
export default class SingleDroneItem extends BaseComp {
@property(cc.Label)
nameLabel: cc.Label = null
name: string
id: string
setData(name:string, id: string) {
this.name = name
this.id = id
this.nameLabel.string = name
}
onClick() {
console.log('SingleDroneItem::onClick::this.id = ',this.id)
this.emit(Drone_Event.DRONE_CLICK, this.id)
}
}
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "f5fa2c10-14fa-4dbf-9668-ea768669f61e",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "b4ca66eb-0d93-4dc6-9a6f-8ff7ba03bf19",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+97
View File
@@ -0,0 +1,97 @@
export interface IDisposer {
(): void
}
import { LocalEmitter } from "../external/LocalEmitter";
const { ccclass, property } = cc._decorator;
@ccclass
export default class BaseComp extends cc.Component {
_comp_id_: number = LocalEmitter.newCompId();
protected _pool: Array<IDisposer> = []
_frameCount = 0;
_frameLimit = 3;
canUpdate(){
this._frameCount++;
if(this._frameCount < this._frameLimit){
return false;
}
this._frameCount = 0;
return true;
}
getCompId() {
return this._comp_id_;
}
//注册监听
on(event: string, fn: Function) {
LocalEmitter.inst.on(this.getCompId(), event, fn);
}
//移除监听
off(event: string = null, fn: Function = null) {
LocalEmitter.inst.off(this.getCompId(), event, fn);
}
// 发送事件
emit(event: string = null, obj: any = null, obj2: any = null) {
LocalEmitter.inst.emit(event, obj, obj2);
}
initListener(config:{[key:string]:number}){
for(let key in config){
this.on(config[key].toString(), this[key].bind(this));
}
}
onDestroy() {
this.removeAllListeners();
}
removeAllListeners(){
LocalEmitter.inst.off(this.getCompId());
}
showPopWait(msg: string = "Vui lòng chờ..."): void {
LocalEmitter.inst.emit("showPopWait",{prompt:msg})
}
hidePopWait(): void {
LocalEmitter.inst.emit("hidePopWait")
}
mute(){
this._pool && this._pool.forEach((d) => d())
this._pool = [];
}
onDisable(){
this.mute();
}
onEnable(){
this.mute();
}
//加载图片资源
loadSpriteFrame(PrefabUrl, fun: Function): void {
cc.resources.load(PrefabUrl, cc.SpriteFrame, function (err, res) {
//检查资源加载
if (err) {
return
}
if (fun) {
fun(res)
}
})
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "a03bb1c4-40fd-4523-98d8-56698a9cd3cb",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+173
View File
@@ -0,0 +1,173 @@
/*
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @module ui
*/
import { CustomToggle } from './CustomToggleItem'
const { property, ccclass, help, executeInEditMode, executionOrder, menu } = cc._decorator
/**
* @en
* ToggleContainer is not a visible UI component but a way to modify the behavior of a set of Toggles. <br/>
* Toggles that belong to the same group could only have one of them to be switched on at a time.<br/>
* Note: All the first layer child node containing the toggle component will auto be added to the container.
*
* @zh
* ToggleGroup 不是一个可见的 UI 组件,它可以用来修改一组 Toggle 组件的行为。当一组 Toggle 属于同一个 ToggleGroup 的时候,<br/>
* 任何时候只能有一个 Toggle 处于选中状态。
*/
@ccclass
@executionOrder(110)
@menu('UI/CustomToggleGroup')
@executeInEditMode
export class CustomToggleGroup extends cc.Component {
@property(cc.Boolean)
protected _allowSwitchOff = false
/**
* @en
* If this setting is true, a toggle could be switched off and on when pressed.
* If it is false, it will make sure there is always only one toggle could be switched on
* and the already switched on toggle can't be switched off.
*
* @zh
* 如果这个设置为 true,那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。
*/
@property({ tooltip: 'i18n:toggle_group.allowSwitchOff' })
get allowSwitchOff() {
return this._allowSwitchOff
}
set allowSwitchOff(value) {
this._allowSwitchOff = value
}
/**
* @en
* If Toggle is clicked, it will trigger event's handler.
*
* @zh
* Toggle 按钮的点击事件列表。
*/
@property({ type: [cc.Component.EventHandler], tooltip: 'i18n:toggle_group.check_events' })
public checkEvents: cc.Component.EventHandler[] = []
/**
* @en
* Read only property, return the toggle items array reference managed by ToggleContainer.
*
* @zh
* 只读属性,返回 toggleContainer 管理的 toggle 数组引用。
*/
get toggleItems() {
return this.node.children
.map((item) => {
const toggle = item.getComponent(CustomToggle)
if (toggle && toggle.enabled) {
return toggle
}
})
.filter(Boolean)
}
public onEnable() {
this.ensureValidState()
this.node.on(cc.Node.EventType.CHILD_ADDED, this.ensureValidState, this)
this.node.on(cc.Node.EventType.CHILD_REMOVED, this.ensureValidState, this)
}
public onDisable() {
this.node.off(cc.Node.EventType.CHILD_ADDED, this.ensureValidState, this)
this.node.off(cc.Node.EventType.CHILD_REMOVED, this.ensureValidState, this)
}
public activeToggles() {
return this.toggleItems.filter((x) => x!.isChecked)
}
public anyTogglesChecked() {
return !!this.toggleItems.find((x) => x!.isChecked)
}
/**
* @en
* Refresh the state of the managed toggles.
*
* @zh
* 刷新管理的 toggle 状态。
*
* @param toggle - 需要被更新的 toggle。
* @param emitEvent - 是否需要触发事件
*/
public notifyToggleCheck(toggle: CustomToggle, emitEvent = true) {
if (!this.enabledInHierarchy) {
return
}
for (let i = 0; i < this.toggleItems.length; i++) {
const item = this.toggleItems[i]!
if (item === toggle) {
continue
}
if (emitEvent) {
item.isChecked = false
} else {
item.setIsCheckedWithoutNotify(false)
}
}
if (this.checkEvents) {
cc.Component.EventHandler.emitEvents(this.checkEvents, toggle)
}
}
public ensureValidState() {
const toggles = this.toggleItems
if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) {
const toggle = toggles[0]!
toggle.isChecked = true
this.notifyToggleCheck(toggle)
}
const activeToggles = this.activeToggles()
if (activeToggles.length > 1) {
const firstToggle = activeToggles[0]
for (let i = 0; i < activeToggles.length; ++i) {
const toggle = activeToggles[i]
if (toggle === firstToggle) {
continue
}
toggle!.isChecked = false
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "9e433cb7-86b6-4361-8b44-5e13446638fc",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+179
View File
@@ -0,0 +1,179 @@
/**
* @packageDocumentation
* @module ui
*/
import { CustomToggleGroup } from "./CustomToggleGroup"
const { property, ccclass, requireComponent, executionOrder, menu } = cc._decorator
export enum ToggleSwitchType {
active,
animation
}
/**
* @en
* The toggle component is a CheckBox, when it used together with a ToggleGroup,
* it could be treated as a RadioButton.
*
* @zh
* Toggle 是一个 CheckBox,当它和 ToggleGroup 一起使用的时候,可以变成 RadioButton。
*/
@ccclass
@executionOrder(110)
@menu('UI/CustomToggle')
export class CustomToggle extends cc.Component {
/**
* @en
* When this value is true, the check mark component will be enabled,
* otherwise the check mark component will be disabled.
*
* @zh
* 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。
*/
@property
get isChecked() {
return this._isChecked
}
set isChecked(value) {
this._set(value)
}
set _resizeToTarget(value: boolean) {
// if (value) {
// this._resizeNodeToTargetNode();
// }
}
get _toggleContainer() {
const parent = this.node.parent!
if (parent instanceof cc.Node) {
return parent.getComponent(CustomToggleGroup)
}
return null
}
/**
* @en
* If Toggle is clicked, it will trigger event's handler.
*
* @zh
* Toggle 按钮的点击事件列表。
*/
@property({ type: [cc.Component.EventHandler], tooltip: 'i18n:toggle.check_events' })
public checkEvents: cc.Component.EventHandler[] = []
@property(cc.Boolean)
protected _isChecked = true
@property([cc.Node])
protected onNodeList: cc.Node[] = []
@property([cc.Node])
protected offNodeList: cc.Node[] = []
@property({ type: cc.Enum(ToggleSwitchType) })
toggleSwitchType: ToggleSwitchType = ToggleSwitchType.active
//是否關閉點擊事件
@property(cc.Boolean)
isDoNotEmitToggle = false
private toggleEventMap: Map<ToggleSwitchType, Function> = new Map([
[ToggleSwitchType.active, this.switchByActive.bind(this)],
[ToggleSwitchType.animation, this.switchByAnimation.bind(this)]
])
protected _internalToggle() {
if (this.isDoNotEmitToggle) {
return
}
this.isChecked = !this.isChecked
}
protected _set(value: boolean, emitEvent = true) {
if (this._isChecked == value) return
this._isChecked = value
const group = this._toggleContainer
if (group && group.enabled && this.enabled) {
if (value || (!group.anyTogglesChecked() && !group.allowSwitchOff)) {
this._isChecked = true
group.notifyToggleCheck(this as any, emitEvent)
}
}
this.playEffect()
if (emitEvent) {
this._emitToggleEvents()
}
}
//
public playEffect() {
this.toggleEventMap.get(this.toggleSwitchType)()
}
switchByActive() {
this.onNodeList.forEach((node) => {
node.active = this._isChecked
})
this.offNodeList.forEach((node) => {
node.active = !this._isChecked
})
}
switchByAnimation() { }
/**
* @en
* Set isChecked without invoking checkEvents.
*
* @zh
* 设置 isChecked 而不调用 checkEvents 回调。
*
* @param value - 是否被按下
*/
public setIsCheckedWithoutNotify(value: boolean) {
this._set(value, false)
}
onEnable() {
this.playEffect()
if (!CC_EDITOR || CC_PREVIEW) {
this.node.on(cc.Node.EventType.TOUCH_END, this._internalToggle, this)
}
}
onDisable() {
if (!CC_EDITOR || CC_PREVIEW) {
this.node.off(cc.Node.EventType.TOUCH_END, this._internalToggle, this)
}
}
public OnDestroy() {
const group = this._toggleContainer
if (group) {
group.ensureValidState()
}
}
protected _emitToggleEvents() {
this.node.emit("toggle", this)
if (this.checkEvents) {
cc.Component.EventHandler.emitEvents(this.checkEvents, this)
}
}
}
/**
* @en
* Note: This event is emitted from the node to which the component belongs.
*
* @zh
* 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
* @event toggle
* @param {Event.EventCustom} event
* @param {Toggle} toggle - The Toggle component.
*/
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "c9005f79-10ad-41fb-8a54-3db4fd21e6c6",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+39
View File
@@ -0,0 +1,39 @@
import { LocalEmitter } from "./LocalEmitter";
const { ccclass, property } = cc._decorator;
@ccclass
export default class EmitterBase {
_comp_id_: number = LocalEmitter.newCompId();
getCompId() {
return this._comp_id_;
}
//注册监听
on(event: string, fn: Function) {
LocalEmitter.inst.on(this.getCompId(), event, fn);
}
//移除监听
off(event: string = null, fn: Function = null) {
LocalEmitter.inst.off(this.getCompId(), event, fn);
}
// 发送事件
emit(event: string = null, obj: any = null) {
LocalEmitter.inst.emit(event, obj);
}
removeAllListeners() {
LocalEmitter.inst.off(this.getCompId());
}
initListener(config:{[key:string]:number}){
for(let key in config){
this.on(config[key].toString(), this[key].bind(this));
}
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "88513ced-6c4a-41d1-a9b2-30b61f99e0a9",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+123
View File
@@ -0,0 +1,123 @@
/**
* class Emitter.
*
*/
export class LocalEmitter {
public static _instance: LocalEmitter = null;
public static get inst() {
if (LocalEmitter._instance == null) {
LocalEmitter._instance = new LocalEmitter();
}
return LocalEmitter._instance;
}
private static _g_comp_id: number = 1;
public static newCompId() {
return LocalEmitter._g_comp_id++;
}
/**
* callbacks for event.
*/
_callbacks = {};
_onceCallbacks = {};
/**
* Listen on the given `event` with `fn`.
*/
on(tag: number, event: string, fn: Function) {
let callbacks = this._callbacks[event];
if (null == callbacks) {
callbacks = this._callbacks[event] = {};
}
let calls = callbacks[tag];
if (null == calls) {
calls = callbacks[tag] = [];
}
calls.push(fn);
return this;
};
once(event: string, fn: Function) {
if(event == null){
return;
}
if(this._onceCallbacks[event] == null){
this._onceCallbacks[event] = [];
}
this._onceCallbacks[event].push(fn);
}
/**
* Remove the given callback for `event` or all
* registered callbacks.
*/
off(tag: number = null, event: string = null, fn: Function = null) {
// all
if (null == tag) {
this._callbacks = {};
return this;
}
if (null == event) {
for (let event in this._callbacks) {
delete this._callbacks[event][tag];
}
return this;
}
if (null == fn) {
if (null != this._callbacks[event]) {
delete this._callbacks[event][tag];
}
return this;
}
// specific event
let callbacks = this._callbacks[event];
if (!callbacks) return this;
let calls = callbacks[tag];
if (!calls) return this;
// remove specific handler
let i = calls.indexOf(fn);
if (~i) calls.splice(i, 1);
return this;
};
/**
* Emit `event` with the given args.
*
*/
emit(event: string, obj: any = null, obj2: any = null) {
let callbacks = this._callbacks[event];
let onceCallback = this._onceCallbacks[event];
if (null != callbacks) {
for (let id in callbacks) {
let calls = callbacks[id];
for (let i = 0, len = calls.length; i < len; ++i) {
calls[i].call(this, obj, obj2);
}
}
}
if (onceCallback != null) {
onceCallback.filter((callback)=>{
callback(null, obj, obj2);
})
delete this._onceCallbacks[event];
}
return this;
};
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "1f410cf5-01b4-48a2-af1c-5504f2293207",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+467
View File
@@ -0,0 +1,467 @@
const oneMinuteSeconds = 60
const onehourSeconds = oneMinuteSeconds * 60
const oneDaySeconds = onehourSeconds * 24
let forbiddenWords: string[] = undefined
export class Utils {
//是否空值
public static isNull(o: any): boolean {
let type = Object.prototype.toString.call(o);
return ("[object Null]" === type || "[object Undefined]" === type);
}
//是否字符串
public static isString(o: any): boolean {
return ("[object String]" === Object.prototype.toString.call(o));
}
//是否数字
public static isNumber(o: any): boolean {
return ("[object Number]" === Object.prototype.toString.call(o));
}
//是否数组
public static isArray(o: any): boolean {
return ("[object Array]" === Object.prototype.toString.call(o));
}
//是否字典
public static isObject(o: any): boolean {
return ("[object Object]" === Object.prototype.toString.call(o));
}
//是否方法
public static isFunction(o: any): boolean {
return ("[object Function]" === Object.prototype.toString.call(o));
}
//继承
public static inherit(base: Function, obj: Function) {
for (let key in base.prototype) {
obj.prototype[key] = base.prototype[key];
}
return obj;
}
//继承
public static queryUrl(url: string) {
let querys = {};
let index = url.indexOf("?")
cc.log(index)
if (index >= 0) {
let strs = url.substr(index + 1).split("&")
for (let i = 0, len = strs.length; i < len; i++) {
if (strs[i].indexOf("=") > 0) {
let params = strs[i].split("=");
if (params[0].trim() != "") {
querys[params[0]] = params[1];
}
}
}
}
return querys;
}
// 将base64字符串转换成图片
public static getSpritFrameFromBase64(base64: string): cc.SpriteFrame {
base64 = "data:image/jpeg;base64," + base64;
let img = new Image();
img.src = base64;
let texture = new cc.Texture2D();
texture.initWithElement(img);
texture.handleLoadedTexture();
return new cc.SpriteFrame(texture);
}
//生成uuid
public static uuid(length: number) {
let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
let uuid = [], i = 0;
let radix = chars.length;
if (length > 0) {
// Compact form
for (i = 0; i < length; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
let r: number = 0;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
//复制文本
public static onCopyText(copyText: string): boolean {
if (cc.sys.isBrowser) {
let input = document.createElement("input");
input.setAttribute("readonly", "readonly");
input.setAttribute("value", copyText);
input.style.position = "absolute";
input.style.left = "-9999px";
input.style.fontSize = "12pt"; // Prevent zooming on iOS
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, 128);
let success = false;
try {
if (document.execCommand("Copy")) {
success = true;
}
} catch (e) {
console.log(e)
}
document.body.removeChild(input);
return success;
} else {
// if (Common.OpenFunction.COPYTEXT) {
// if (cc.sys.os == cc.sys.OS_ANDROID) {
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "JavaCopy", "(Ljava/lang/String;)V", copyText);
// return true
// }
// else if (cc.sys.os == cc.sys.OS_IOS) {
// let IOS_API = "AppController";
// jsb.reflection.callStaticMethod(IOS_API, "JavaCopy:", copyText);
// return true
// }
// }
}
return false
}
//复制文本
public static getCopyText(): string {
let copyText = ""
// if (Common.OpenFunction.COPYTEXT) {
// if (cc.sys.os == cc.sys.OS_ANDROID) {
// copyText = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getDuplicateContent", "()Ljava/lang/String;");
// }
// else if (cc.sys.os == cc.sys.OS_IOS) {
// let IOS_API = "AppController";
// copyText = jsb.reflection.callStaticMethod(IOS_API, "getDuplicateContent:", "");
// }
// }
return copyText
}
/**
* 尋找當前scrollView滑動百分比
* @param scrollView
*/
public static judgeScrollPercent(scrollView: cc.ScrollView) {
const offset = scrollView.getScrollOffset()
const maxOffset = scrollView.getMaxScrollOffset()
const offsetArray = [offset.x, offset.y]
const maxOffsetArray = [maxOffset.x, maxOffset.y, maxOffset.y]
const index = maxOffsetArray.indexOf(Math.max(...maxOffsetArray))
offsetArray[index] = Math.abs(offsetArray[index])
offsetArray[index] = offsetArray[index] < 0 ? 0 : offsetArray[index]
offsetArray[index] = offsetArray[index] > maxOffsetArray[index] ? maxOffsetArray[index] : offsetArray[index]
return offsetArray[index] / maxOffsetArray[index]
}
/**
* 轉換錢幣
*/
public static moneyUnitConvert(money: number) {
if (money < 1000) {
return money + ''
} else {
return money / 1000 + 'K'
}
}
/**
* 三位一撇
*/
public static numberWithCommas(number: number) {
let parts = number.toFixed(2).split('.')
let decimal = parts[1].slice();
for (let i = parts[1].length - 1; i >= 0; i--) {
if (parts[1][i] != '0') {
break;
}
else {
decimal = decimal.substr(0, i);
}
}
parts[1] = decimal;
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',') + (parts[1] ? '.' + parts[1] : '')
}
/**
* 無條件捨去
*/
public static roundDown(number: number) {
return Number(String(number).split(".")[0])
}
public static deepClone(data: any) {
if (data === undefined || data === null) {
return data
}
return JSON.parse(JSON.stringify(data || {}))
}
/**
* 閃爍動畫
* @param node 閃爍節點
* @param duration 間隔
* @param repeat 重複次數(-1為無限)
* @param callBack 回調函式
*/
public static blink(node: cc.Node, duration: number, repeat = 0, endShow: boolean = true, callBack?: Function) {
// cc.log(`blick duration:${duration} repeat:${repeat}`);
node.active = true
cc.Tween.stopAllByTarget(node)
node.opacity = 0;
const show = endShow ? 255 : 0;
let action = cc.tween()
.to(duration, { opacity: 0 }, { easing: 'quadIn' })
.to(duration, { opacity: 255 }, { easing: 'quadOut' })
cc.tween(node).repeat(repeat, action).call(() => { node.opacity = show; callBack && callBack() }).start();
}
public static currencyFilter(value: number) {
if (value < 1000) {
return `${value}`
}
value = value - (value % 100)
return `${value / 1000}K`
}
public static getCanvasInParent(node: cc.Node): cc.Canvas {
if (!node) {
return undefined
}
let canvas = undefined
let parent = node.parent
while (!canvas) {
if (!parent) {
break
}
canvas = parent.getComponent(cc.Canvas)
parent = parent.parent
}
return canvas
}
public static clamp(val: number, min: number, max: number): number {
return val < min ? min : (val > max ? max : val)
}
public static copyString(str: string) {
const el = document.createElement('textarea')
el.value = str
el.setAttribute('readonly', '')
// el.style.contain = 'strict';
el.style.position = 'absolute'
el.style.left = '-9999px'
el.style.fontSize = '12pt' // Prevent zooming on iOS
const selection = getSelection()
let originalRange = null
if (selection.rangeCount > 0) {
originalRange = selection.getRangeAt(0)
}
document.body.appendChild(el)
el.select()
el.selectionStart = 0
el.selectionEnd = str.length
let success = false
try {
success = document.execCommand('copy')
} catch (err) { }
document.body.removeChild(el)
if (originalRange) {
selection.removeAllRanges()
selection.addRange(originalRange)
}
if (success) {
console.log('复制成功')
} else {
console.log('复制失败')
}
return success
}
public static setButtonInteractable(button: cc.Button, value: boolean) {
if (!button) {
return
}
button.interactable = value
}
public static changeNodeParent(node, parent) {
if (!node) {
cc.error("changeNodeParent node is null");
return;
}
if (!parent) {
cc.error("changeNodeParent parent is null");
return;
}
let pos = node.parent.convertToWorldSpaceAR(node.getPosition());
let changePos = parent.convertToNodeSpaceAR(pos);
node.parent = parent;
node.setPosition(changePos);
}
public static tweenNumberLabel(label: cc.Label, num: number, suffix: string = '') {
const currentNum = Number(label.string.replace(/,/g, '').replace(suffix, ''))
if (!Utils.isNumber(currentNum)) {
console.warn('label is not number:', label.string)
return
}
if (currentNum >= num) {
label.string = Utils.numberWithCommas(num) + suffix
return
}
const plusNum = num - currentNum
const betweenTime = 0.01
const count = 80
let currentCount = 0
label.unscheduleAllCallbacks()
label.schedule(
() => {
if (!label) {
return
}
currentCount += 1
label.string = Utils.numberWithCommas(Math.round(currentNum + (plusNum / count) * currentCount)) + suffix
if (currentCount === count) {
label.string = Utils.numberWithCommas(num) + suffix
}
},
betweenTime,
count - 1
)
}
public static tweenSpriteFillrange(sprite: cc.Sprite, percent: number) {
// cc.log("tweenSpriteFillrange ", percent)
let changeTotal = percent - sprite.fillRange;
const count = 80;
const betweenTime = 0.01
let per = changeTotal / count;
let curRange = sprite.fillRange;
sprite.unscheduleAllCallbacks();
sprite.schedule(() => {
curRange += per;
sprite.fillRange = curRange;
}, betweenTime, count - 1);
}
// 計算字符長度 (英文數字當成1 其他當成2)
public static countMultiLangStrLength(str: string): number {
const originalSize = str.length
const digitNLetter = str.replace(/[^a-zA-Z0-9]/g, '')
const englishSize = digitNLetter.length
const otherLength = (originalSize - digitNLetter.length) * 2
return englishSize + otherLength
}
public static formatNickname(str: string, maxLen = 6) {
let len = Utils.countMultiLangStrLength(str);
let subLen = len;
while (subLen > maxLen) {
str = str.substr(0, str.length - 1);
subLen = Utils.countMultiLangStrLength(str);
}
return len > 6 ? (str + "...") : str;
}
/**
* 數字換行(奇數上排數字大於下排, 偶數對半)
* @param numStr 欲轉換數字
* @param limitNum 幾位後要換行
*/
public static convertChipStr(numStr: string, limitNum: number = 3) {
const len = numStr.length
if (len > limitNum) {
const sliceLen = Math.ceil(len * 0.5)
return `${numStr.slice(0, sliceLen)}\n${numStr.slice(sliceLen)}`
} else {
return numStr
}
}
/** 發送訊息提示 */
public static showSendLog(eventName: string, message?: any) {
if (CC_DEBUG) {
message = message || {};
const time = this.convertTimestamp(new Date().getTime());
let data = JSON.parse(JSON.stringify(message)); // Deep Copy
console.log("%s %c %s", time, "background: Green; color: White;", "發送 " + eventName + " ", data);
}
}
/** 回傳訊息提示 */
public static showResponseLog(eventName: string, message?: any) {
if (CC_DEBUG) {
message = message || {};
const time = this.convertTimestamp(new Date().getTime());
let data = JSON.parse(JSON.stringify(message)); // Deep Copy
console.log("%s %c %s", time, "background: Green; color: White;", "回應 " + eventName + " ", data);
}
}
/** 廣播訊息提示 */
public static showPushLog(eventName: string, message: any) {
if (CC_DEBUG) {
message = message || {};
const time = this.convertTimestamp(new Date().getTime());
let data = JSON.parse(JSON.stringify(message)); // Deep Copy
console.log("%s %c %s", time, "background: Blue; color: White;", "廣播 " + eventName + " ", data);
}
}
private static convertTimestamp(value: number): string {
const t = new Date(value);
// const yyyy = t.getFullYear();
// const MM = t.getMonth() < 9 ? "0" + (t.getMonth()+1):t.getMonth()+1;
// const DD = t.getDate() < 10 ? "0" + t.getDate() : t.getDate();
const hh = t.getHours() < 10 ? "0" + t.getHours() : t.getHours();
const mm = t.getMinutes() < 10 ? "0" + t.getMinutes() : t.getMinutes()
const ss = t.getSeconds() < 10 ? "0" + t.getSeconds() : t.getSeconds()
return `${hh}:${mm}:${ss}`;
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.0.8",
"uuid": "85b3afaa-64ef-46e6-9e0d-54055039a8a6",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"ver": "1.1.2",
"uuid": "19d51859-0e44-4b12-9bc2-8452475a8af4",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {},
"subMetas": {}
}
+151
View File
@@ -0,0 +1,151 @@
// import { CommonCtrl } from "../CommonCtrl";
// import { GameSocket } from "../GameSocket";
// import TableMgr from "../managers/TableMgr";
// import { CommonUIs, UIManager } from "../managers/UIManager";
// import { Socket } from "./Socket/Socket";
// import { VideoFilterList } from "./VideoFilterList";
// const {ccclass, property} = cc._decorator;
// @ccclass
// export default class BaseVideoPlayer extends cc.Component {
// public sprite: cc.Sprite = null;
// protected loadingNode: cc.Node = null;
// protected videoBg: cc.Node = null;
// protected _filterName: string = "";
// protected url: string = '';
// public isPlaying: boolean = false;
// protected isReady: boolean = false;
// protected timeoutHandler: any;
// protected videoErrorCounts: number = 0;
// protected videoElementList: Array<HTMLElement> = [];
// private _m00: number = 0;
// private _m01: number = 0;
// private _m04: number = 0;
// private _m05: number = 0;
// private _m12: number = 0;
// private _m13: number = 0;
// private _w: number = 0;
// private _h: number = 0;
// protected get checkURLValid(): boolean {
// return new Date().getTime() < CommonCtrl.inst.videoConfig.lTime;
// }
// // init set video Sprite or Node
// public setSprite(sprite: cc.Sprite, loadingNode: cc.Node, videoBg: cc.Node = null): void {
// this.loadingNode = loadingNode;
// this.sprite = sprite;
// this.videoBg = videoBg;
// }
// // videoBg show
// protected setVideoBg(flag: boolean): void {
// this.videoBg && (this.videoBg.active = flag);
// }
// // load icon show
// protected setLoading(flag: boolean): void {
// this.loadingNode && (this.loadingNode.active = flag);
// }
// /** set video bg with load icon */
// protected setVideoBgWithLoad(flag: boolean): void {
// this.setVideoBg(flag);
// this.setLoading(flag);
// }
// protected stop(): void {}
// protected updateUrl(url: string): void {}
// public updateVideoCanvas(): void {
// // cc.log("updateVideoCanvas", CommonCtrl.inst.curDeviceType.isLandscape);
// const node = this.sprite?.node;
// if (!node) return;
// let _mat4_temp = cc.mat4();
// node.getWorldMatrix(_mat4_temp);
// let renderCamera = cc.Camera['_findRendererCamera'](node);
// if (renderCamera) {
// renderCamera.worldMatrixToScreen(_mat4_temp, _mat4_temp, cc.game.canvas.width, cc.game.canvas.height);
// }
// let _mat4_tempm = _mat4_temp.m;
// if (
// this._m00 === _mat4_tempm[0] && this._m01 === _mat4_tempm[1] &&
// this._m04 === _mat4_tempm[4] && this._m05 === _mat4_tempm[5] &&
// this._m12 === _mat4_tempm[12] && this._m13 === _mat4_tempm[13] &&
// this._w === node['_contentSize'].width && this._h === node['_contentSize'].height) {
// return;
// }
// this._m00 = _mat4_tempm[0];
// this._m01 = _mat4_tempm[1];
// this._m04 = _mat4_tempm[4];
// this._m05 = _mat4_tempm[5];
// this._m12 = _mat4_tempm[12];
// this._m13 = _mat4_tempm[13];
// this._w = node['_contentSize'].width;
// this._h = node['_contentSize'].height;
// let dpr = cc.view.getDevicePixelRatio();
// let scaleX = 1 / dpr;
// let scaleY = 1 / dpr;
// let a = _mat4_tempm[0] * scaleX,
// b = _mat4_tempm[1],
// c = _mat4_tempm[4],
// d = _mat4_tempm[5] * scaleY;
// let container = cc.game.container;
// let offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0;
// let offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0;
// let w = this._w * scaleX;
// let h = this._h * scaleY;
// let appx = (w * _mat4_tempm[0]) * node['_anchorPoint'].x;
// let appy = (h * _mat4_tempm[5]) * node['_anchorPoint'].y;
// let tx = _mat4_tempm[12] * scaleX - appx + offsetX, ty = _mat4_tempm[13] * scaleY - appy + offsetY;
// let matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
// this.videoElementList.forEach(item => {
// const video = item;
// video.style.width = this._w + 'px';
// video.style.height = this._h + 'px';
// video.style['transform'] = matrix;
// video.style['-webkit-transform'] = matrix;
// video.style['transform-origin'] = '0px 100% 0px';
// video.style['-webkit-transform-origin'] = '0px 100% 0px';
// })
// }
// private updateFilter(tableNo: string = "", data = { brightness: 100, contrast: 100, saturate: 100 }): void {
// cc.warn(`${tableNo} video filter`, data);
// this.videoElementList.forEach(video => {
// video.style.filter =
// `brightness(${data.brightness}%) ` +
// `contrast(${data.contrast}%) ` +
// `saturate(${data.saturate}%) ` +
// ``;
// })
// }
// public updateFilterByTableNo(tableNo: string = ""): void {
// if (this._filterName != tableNo) {
// this._filterName = tableNo;
// this.updateFilter(tableNo, VideoFilterList.get(tableNo));
// }
// }
// public retry(): void{
// this.stop();
// this.setLoading(true);
// this.scheduleOnce(()=>{
// this.updateUrl(CommonCtrl.inst.videoConfig.url);
// }, 10)
// GameSocket.inst.C2S_QueryLiveUrl();
// }
// }

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