text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import aceEvent, { AceEvent } from "@wowts/ace_event-3.0";
import { LuaArray, LuaObj, next, pairs, truthy, unpack } from "@wowts/lua";
import { find } from "@wowts/string";
import { AceModule } from "@wowts/tsaddon";
import {
COMBATLOG_OBJECT_AFFILIATION_MINE,
COMBATLOG_OBJECT_AFFILIATION_PARTY,
COMBATLOG_OBJECT_AFFILIATION_RAID,
COMBATLOG_OBJECT_REACTION_FRIENDLY,
CombatLogGetCurrentEventInfo,
Enum,
} from "@wowts/wow-mock";
import { OvaleClass } from "../Ovale";
import { DebugTools, Tracer } from "./debug";
// from Interface/AddOns/Blizzard_CombatLog/Blizzard_CombatLog.lua
export type CombatLogSubEvent =
| "ENVIRONMENTAL_DAMAGE"
| "SWING_DAMAGE"
| "SWING_MISSED"
| "RANGE_DAMAGE"
| "RANGE_MISSED"
| "SPELL_CAST_START"
| "SPELL_CAST_SUCCESS"
| "SPELL_CAST_FAILED"
| "SPELL_MISSED"
| "SPELL_DAMAGE"
| "SPELL_HEAL"
| "SPELL_ENERGIZE"
| "SPELL_DRAIN"
| "SPELL_LEECH"
| "SPELL_SUMMON"
| "SPELL_RESURRECT"
| "SPELL_CREATE"
| "SPELL_INSTAKILL"
| "SPELL_INTERRUPT"
| "SPELL_EXTRA_ATTACKS"
| "SPELL_DURABILITY_DAMAGE"
| "SPELL_DURABILITY_DAMAGE_ALL"
| "SPELL_AURA_APPLIED"
| "SPELL_AURA_APPLIED_DOSE"
| "SPELL_AURA_REMOVED"
| "SPELL_AURA_REMOVED_DOSE"
| "SPELL_AURA_BROKEN"
| "SPELL_AURA_BROKEN_SPELL"
| "SPELL_AURA_REFRESH"
| "SPELL_DISPEL"
| "SPELL_STOLEN"
| "ENCHANT_APPLIED"
| "ENCHANT_REMOVED"
| "SPELL_PERIODIC_MISSED"
| "SPELL_PERIODIC_DAMAGE"
| "SPELL_PERIODIC_HEAL"
| "SPELL_PERIODIC_ENERGIZE"
| "SPELL_PERIODIC_DRAIN"
| "SPELL_PERIODIC_LEECH"
| "SPELL_DISPEL_FAILED"
| "DAMAGE_SHIELD"
| "DAMAGE_SHIELD_MISSED"
| "DAMAGE_SPLIT"
| "PARTY_KILL"
| "UNIT_DIED"
| "UNIT_DESTROYED"
| "SPELL_BUILDING_DAMAGE"
| "SPELL_BUILDING_HEAL"
| "UNIT_DISSIPATES";
export type EventPrefix =
| "SWING"
| "RANGE"
| "SPELL"
| "SPELL_PERIODIC"
| "SPELL_BUILDING"
| "ENVIRONMENTAL"
| "ENCHANT_APPLIED"
| "ENCHANT_REMOVED"
| "PARTY_KILL"
| "UNIT_DIED"
| "UNIT_DESTROYED"
| "UNIT_DISSIPATES";
export interface PayloadHeader {
type: EventPrefix;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface SwingPayloadHeader extends PayloadHeader {}
export interface RangePayloadHeader extends PayloadHeader {
spellId: number;
spellName: string;
school: number;
}
export interface SpellPayloadHeader extends PayloadHeader {
spellId: number;
spellName: string;
school: number;
}
export interface SpellPeriodicPayloadHeader extends PayloadHeader {
spellId: number;
spellName: string;
school: number;
}
export interface SpellBuildingPayloadHeader extends PayloadHeader {
spellId: number;
spellName: string;
school: number;
}
export interface EnchantAppliedPayloadHeader extends PayloadHeader {
spellName: string;
itemId: number;
itemName: string;
}
export interface EnchantRemovedPayloadHeader extends PayloadHeader {
spellName: string;
itemId: number;
itemName: string;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface PartyKillPayloadHeader extends PayloadHeader {}
export interface UnitDiedPayloadHeader extends PayloadHeader {
recapId: number;
unconsciousOnDeath: boolean;
}
export interface UnitDestroyedPayloadHeader extends PayloadHeader {
recapId: number;
unconsciousOnDeath: boolean;
}
export interface UnitDissipatesPayloadHeader extends PayloadHeader {
recapId: number;
unconsciousOnDeath: boolean;
}
type EnvironmentalType =
| "Drowning"
| "Falling"
| "Fatigue"
| "Fire"
| "Lava"
| "Slime";
export interface EnvironmentalPayloadHeader extends PayloadHeader {
environmentalType: EnvironmentalType;
}
export type EventSuffix =
| "DAMAGE"
| "MISSED"
| "HEAL"
| "HEAL_ABSORBED"
| "ENERGIZE"
| "DRAIN"
| "LEECH"
| "INTERRUPT"
| "DISPEL"
| "DISPEL_FAILED"
| "STOLEN"
| "EXTRA_ATTACKS"
| "AURA_APPLIED"
| "AURA_REMOVED"
| "AURA_APPLIED_DOSE"
| "AURA_REMOVED_DOSE"
| "AURA_REFRESH"
| "AURA_BROKEN"
| "AURA_BROKEN_SPELL"
| "CAST_START"
| "CAST_SUCCESS"
| "CAST_FAILED"
| "INSTAKILL"
| "DURABILITY_DAMAGE"
| "DURABILITY_DAMAGE_ALL"
| "CREATE"
| "SUMMON"
| "DISSIPATES";
type AuraType = "BUFF" | "DEBUFF";
type MissType =
| "ABSORB"
| "BLOCK"
| "DEFLECT"
| "DODGE"
| "EVADE"
| "IMMUNE"
| "MISS"
| "PARRY"
| "REFLECT"
| "RESIST";
export interface Payload {
type: EventSuffix;
}
export interface DamagePayload extends Payload {
amount: number;
overkill: number;
school: number;
resisted: number;
blocked: number;
absorbed: number;
critical: boolean;
glancing: boolean;
crushing: boolean;
isOffHand: boolean;
}
export interface MissedPayload extends Payload {
missType: MissType;
isOffHand: boolean;
amountMissed: number;
critical: boolean;
}
export interface HealPayload extends Payload {
amount: number;
overhealing: number;
absorbed: number;
critical: boolean;
}
export interface HealAbsorbedPayload extends Payload {
guid: string;
name: string;
flags: number;
raidFlags: number;
spellId: number;
spellName: string;
school: number;
amount: number;
}
export interface EnergizePayload extends Payload {
amount: number;
overEnergize: number;
powerType: number; // Enum.PowerType
alternatePowerType: number; // Enum.PowerType
}
export interface DrainPayload extends Payload {
amount: number;
powerType: number; // Enum.PowerType
extraAmount: number;
}
export interface LeechPayload extends Payload {
amount: number;
powerType: number; // Enum.PowerType
extraAmount: number;
}
export interface InterruptPayload extends Payload {
spellId: number;
spellName: string;
school: number;
}
export interface DispelPayload extends Payload {
spellId: number;
spellName: string;
school: number;
auraType: AuraType;
}
export interface DispelFailedPayload extends Payload {
spellId: number;
spellName: string;
school: number;
}
export interface StolenPayload extends Payload {
spellId: number;
spellName: string;
school: number;
auraType: AuraType;
}
export interface ExtraAttacksPayload extends Payload {
amount: number;
}
export interface AuraAppliedPayload extends Payload {
auraType: AuraType;
amount: number;
}
export interface AuraRemovedPayload extends Payload {
auraType: AuraType;
amount: number;
}
export interface AuraAppliedDosePayload extends Payload {
auraType: AuraType;
amount: number;
}
export interface AuraRemovedDosePayload extends Payload {
auraType: AuraType;
amount: number;
}
export interface AuraRefreshPayload extends Payload {
auraType: AuraType;
amount: number;
}
export interface AuraBrokenPayload extends Payload {
auraType: AuraType;
}
export interface AuraBrokenSpellPayload extends Payload {
spellId: number;
spellName: string;
school: number;
auraType: AuraType;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CastStartPayload extends Payload {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CastSuccessPayload extends Payload {}
export interface CastFailedPayload extends Payload {
failedType: string;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface InstaKillPayload extends Payload {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DurabilityDamagePayload extends Payload {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DurabilityDamageAllPayload extends Payload {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CreatePayload extends Payload {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface SummonPayload extends Payload {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DissipatesPayload extends Payload {}
export const unitFlag: LuaObj<LuaObj<number>> = {
type: {
mask: 0xfc00, // COMBATLOG_OBJECT_TYPE_MASK
object: 0x4000, // COMBATLOG_OBJECT_TYPE_OBJECT
guardian: 0x2000, // COMBATLOG_OBJECT_TYPE_GUARDIAN
pet: 0x1000, // COMBATLOG_OBJECT_TYPE_PET
npc: 0x800, // COMBATLOG_OBJECT_TYPE_NPC
player: 0x400, // COMBATLOG_OBJECT_TYPE_PLAYER
},
controller: {
mask: 0x300, // COMBATLOG_OBJECT_CONTROL_MASK
npc: 0x200, // COMBATLOG_OBJECT_CONTROL_NPC
player: 0x100, // COMBATLOG_OBJECT_CONTROL_PLAYER
},
reaction: {
mask: 0xf0, // COMBATLOG_OBJECT_REACTION_MASK
hostile: 0x40, // COMBATLOG_OBJECT_REACTION_HOSTILE
neutral: 0x20, // COMBATLOG_OBJECT_REACTION_NEUTRAL
friendly: COMBATLOG_OBJECT_REACTION_FRIENDLY,
},
affiliation: {
mask: 0xf, // COMBATLOG_OBJECT_AFFILIATION_MASK
outsider: 0x8, // COMBATLOG_OBJECT_AFFILIATION_MASK
raid: COMBATLOG_OBJECT_AFFILIATION_RAID,
party: COMBATLOG_OBJECT_AFFILIATION_PARTY,
mine: COMBATLOG_OBJECT_AFFILIATION_MINE,
},
};
export const raidFlag: LuaObj<LuaObj<number>> = {
raidTarget: {
mask: 0xff, // COMBATLOG_OBJECT_RAIDTARGET_MASK
skull: 0x80, // COMBATLOG_OBJECT_RAIDTARGET8
cross: 0x40, // COMBATLOG_OBJECT_RAIDTARGET7
square: 0x20, // COMBATLOG_OBJECT_RAIDTARGET6
moon: 0x10, // COMBATLOG_OBJECT_RAIDTARGET5
triangle: 0x8, // COMBATLOG_OBJECT_RAIDTARGET4
diamond: 0x4, // COMBATLOG_OBJECT_RAIDTARGET3
circle: 0x2, // COMBATLOG_OBJECT_RAIDTARGET2
star: 0x1, // COMBATLOG_OBJECT_RAIDTARGET1
},
};
type CombatLogEventHandler = (event: string) => void;
type CombatLogEventHandlerRegistry = LuaObj<LuaObj<CombatLogEventHandler>>;
export class CombatLogEvent {
private module: AceModule & AceEvent;
private tracer: Tracer;
private registry: CombatLogEventHandlerRegistry = {};
private pendingRegistry: CombatLogEventHandlerRegistry = {};
private fireDepth = 0;
private arg: LuaArray<any> = {};
timestamp = 0;
subEvent: CombatLogSubEvent = "SWING_DAMAGE";
hideCaster = false;
sourceGUID = "";
sourceName = "";
sourceFlags = 0;
sourceRaidFlags = 0;
destGUID = "";
destName = "";
destFlags = 0;
destRaidFlags = 0;
header: PayloadHeader = { type: "SWING" };
payload: Payload = { type: "DAMAGE" };
constructor(ovale: OvaleClass, debug: DebugTools) {
this.module = ovale.createModule(
"CombatLogEvent",
this.onEnable,
this.onDisable,
aceEvent
);
this.tracer = debug.create(this.module.GetName());
}
private onEnable = () => {
this.module.RegisterEvent(
"COMBAT_LOG_EVENT_UNFILTERED",
this.onCombatLogEventUnfiltered
);
};
private onDisable = () => {
this.module.UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED");
};
private onCombatLogEventUnfiltered = (event: string) => {
const arg = this.arg;
[
arg[1],
arg[2],
arg[3],
arg[4],
arg[5],
arg[6],
arg[7],
arg[8],
arg[9],
arg[10],
arg[11],
arg[12],
arg[13],
arg[14],
arg[15],
arg[16],
arg[17],
arg[18],
arg[19],
arg[20],
arg[21],
arg[22],
arg[23],
arg[24],
] = CombatLogGetCurrentEventInfo();
const subEvent = arg[2];
if (!this.hasEventHandler(subEvent)) {
return;
}
this.timestamp = (arg[1] as number) || 0;
this.subEvent = subEvent as CombatLogSubEvent;
this.hideCaster = ((arg[3] as boolean) && true) || false;
this.sourceGUID = (arg[4] as string) || "";
this.sourceName = (arg[5] as string) || "";
this.sourceFlags = (arg[6] as number) || 0;
this.sourceRaidFlags = arg[7] as number;
this.destGUID = (arg[8] as string) || "";
this.destName = (arg[9] as string) || "";
this.destFlags = (arg[10] as number) || 0;
this.destRaidFlags = (arg[11] as number) || 0;
if (subEvent == "ENCHANT_APPLIED") {
const header = this.header as EnchantAppliedPayloadHeader;
header.type = "ENCHANT_APPLIED";
header.spellName = (arg[12] as string) || "";
header.itemId = (arg[13] as number) || 0;
header.itemName = (arg[14] as string) || "";
} else if (subEvent == "ENCHANT_REMOVED") {
const header = this.header as EnchantRemovedPayloadHeader;
header.type = "ENCHANT_APPLIED";
header.spellName = (arg[12] as string) || "";
header.itemId = (arg[13] as number) || 0;
header.itemName = (arg[14] as string) || "";
} else if (subEvent == "PARTY_KILL") {
this.header.type = "PARTY_KILL";
} else if (subEvent == "UNIT_DIED") {
const header = this.header as UnitDiedPayloadHeader;
header.type = "UNIT_DIED";
header.recapId = (arg[12] as number) || 1;
header.unconsciousOnDeath = ((arg[13] as boolean) && true) || false;
} else if (subEvent == "UNIT_DESTROYED") {
const header = this.header as UnitDestroyedPayloadHeader;
header.type = "UNIT_DESTROYED";
header.recapId = (arg[12] as number) || 1;
header.unconsciousOnDeath = ((arg[13] as boolean) && true) || false;
} else if (subEvent == "UNIT_DISSIPATES") {
const header = this.header as UnitDissipatesPayloadHeader;
header.type = "UNIT_DISSIPATES";
header.recapId = (arg[12] as number) || 1;
header.unconsciousOnDeath = ((arg[13] as boolean) && true) || false;
} else {
let index = 12;
if (truthy(find(subEvent, "^SWING_"))) {
this.header.type = "SWING";
index = 12;
} else if (truthy(find(subEvent, "^RANGE_"))) {
const header = this.header as RangePayloadHeader;
header.type = "RANGE";
header.spellId = (arg[12] as number) || 0;
header.spellName = (arg[13] as string) || "";
header.school = (arg[14] as number) || 0;
index = 15;
} else if (truthy(find(subEvent, "^SPELL_PERIODIC_"))) {
const header = this.header as SpellPeriodicPayloadHeader;
header.type = "SPELL_PERIODIC";
header.spellId = (arg[12] as number) || 0;
header.spellName = (arg[13] as string) || "";
header.school = (arg[14] as number) || 0;
index = 15;
} else if (truthy(find(subEvent, "^SPELL_BUILDING"))) {
const header = this.header as SpellBuildingPayloadHeader;
header.type = "SPELL_BUILDING";
header.spellId = (arg[12] as number) || 0;
header.spellName = (arg[13] as string) || "";
header.school = (arg[14] as number) || 0;
index = 15;
} else if (
truthy(find(subEvent, "^SPELL_")) ||
truthy(find(subEvent, "^DAMAGE_"))
) {
const header = this.header as SpellPayloadHeader;
header.type = "SPELL";
header.spellId = (arg[12] as number) || 0;
header.spellName = (arg[13] as string) || "";
header.school = (arg[14] as number) || 0;
index = 15;
} else if (truthy(find(subEvent, "^ENVIRONMENTAL"))) {
const header = this.header as EnvironmentalPayloadHeader;
header.type = "ENVIRONMENTAL";
header.environmentalType =
(arg[12] as EnvironmentalType) || "Fire";
index = 13;
}
if (
truthy(find(subEvent, "_DAMAGE$")) ||
truthy(find(subEvent, "_SPLIT$")) ||
truthy(find(subEvent, "_SHIELD$"))
) {
const payload = this.payload as DamagePayload;
payload.type = "DAMAGE";
payload.amount = (arg[index] as number) || 0;
payload.overkill = (arg[index + 1] as number) || 0;
payload.school = (arg[index + 2] as number) || 0;
payload.resisted = (arg[index + 3] as number) || 0;
payload.blocked = (arg[index + 4] as number) || 0;
payload.absorbed = (arg[index + 5] as number) || 0;
payload.critical =
((arg[index + 6] as boolean) && true) || false;
payload.glancing =
((arg[index + 7] as boolean) && true) || false;
payload.crushing =
((arg[index + 8] as boolean) && true) || false;
payload.isOffHand =
((arg[index + 9] as boolean) && true) || false;
} else if (truthy(find(subEvent, "_MISSED$"))) {
const payload = this.payload as MissedPayload;
payload.type = "MISSED";
payload.missType = (arg[index] as MissType) || "MISS";
payload.isOffHand =
((arg[index + 1] as boolean) && true) || false;
payload.amountMissed = (arg[index + 2] as number) || 0;
payload.critical =
((arg[index + 3] as boolean) && true) || false;
} else if (truthy(find(subEvent, "_HEAL$"))) {
const payload = this.payload as HealPayload;
payload.type = "HEAL";
payload.amount = (arg[index] as number) || 0;
payload.overhealing = (arg[index + 2] as number) || 0;
payload.absorbed = (arg[index + 3] as number) || 0;
payload.critical =
((arg[index + 4] as boolean) && true) || false;
} else if (truthy(find(subEvent, "_HEAL_ABSORBED$"))) {
const payload = this.payload as HealAbsorbedPayload;
payload.type = "HEAL_ABSORBED";
payload.guid = (arg[index] as string) || "";
payload.name = (arg[index + 1] as string) || "";
payload.flags = (arg[index + 2] as number) || 0;
payload.raidFlags = (arg[index + 3] as number) || 0;
payload.spellId = (arg[index + 4] as number) || 0;
payload.spellName = (arg[index + 5] as string) || "";
payload.school = (arg[index + 6] as number) || 0;
payload.amount = (arg[index + 7] as number) || 0;
} else if (truthy(find(subEvent, "_ENERGIZE$"))) {
const payload = this.payload as EnergizePayload;
payload.type = "ENERGIZE";
payload.amount = (arg[index] as number) || 0;
payload.overEnergize = (arg[index + 1] as number) || 0;
payload.powerType =
(arg[index + 2] as number) || Enum.PowerType.None;
payload.alternatePowerType =
(arg[index + 3] as number) || Enum.PowerType.Alternate;
} else if (truthy(find(subEvent, "_DRAIN$"))) {
const payload = this.payload as DrainPayload;
payload.type = "DRAIN";
payload.amount = (arg[index] as number) || 0;
payload.powerType =
(arg[index + 1] as number) || Enum.PowerType.None;
payload.extraAmount = (arg[index + 2] as number) || 0;
} else if (truthy(find(subEvent, "_LEECH$"))) {
const payload = this.payload as LeechPayload;
payload.type = "LEECH";
payload.amount = (arg[index] as number) || 0;
payload.powerType =
(arg[index + 1] as number) || Enum.PowerType.None;
payload.extraAmount = (arg[index + 2] as number) || 0;
} else if (truthy(find(subEvent, "_INTERRUPT$"))) {
const payload = this.payload as InterruptPayload;
payload.type = "INTERRUPT";
payload.spellId = (arg[index] as number) || 0;
payload.spellName = (arg[index + 1] as string) || "";
payload.school = (arg[index + 2] as number) || 0;
} else if (truthy(find(subEvent, "_DISPEL$"))) {
const payload = this.payload as DispelPayload;
payload.type = "DISPEL";
payload.spellId = (arg[index] as number) || 0;
payload.spellName = (arg[index + 1] as string) || "";
payload.school = (arg[index + 2] as number) || 0;
payload.auraType = (arg[index + 3] as AuraType) || "DEBUFF";
} else if (truthy(find(subEvent, "_DISPEL_FAILED$"))) {
const payload = this.payload as DispelFailedPayload;
payload.type = "DISPEL_FAILED";
payload.spellId = (arg[index] as number) || 0;
payload.spellName = (arg[index + 1] as string) || "";
payload.school = (arg[index + 2] as number) || 0;
} else if (truthy(find(subEvent, "_STOLEN$"))) {
const payload = this.payload as StolenPayload;
payload.type = "STOLEN";
payload.spellId = (arg[index] as number) || 0;
payload.spellName = (arg[index + 1] as string) || "";
payload.school = (arg[index + 2] as number) || 0;
payload.auraType = (arg[index + 3] as AuraType) || "DEBUFF";
} else if (truthy(find(subEvent, "_EXTRA_ATTACKS$"))) {
const payload = this.payload as ExtraAttacksPayload;
payload.type = "EXTRA_ATTACKS";
payload.amount = (arg[index] as number) || 0;
} else if (truthy(find(subEvent, "_AURA_APPLIED$"))) {
const payload = this.payload as AuraAppliedPayload;
payload.type = "AURA_APPLIED";
payload.auraType = (arg[index] as AuraType) || "DEBUFF";
payload.amount = (arg[index + 1] as number) || 0;
} else if (truthy(find(subEvent, "_AURA_REMOVED$"))) {
const payload = this.payload as AuraRemovedPayload;
payload.type = "AURA_REMOVED";
payload.auraType = (arg[index] as AuraType) || "DEBUFF";
payload.amount = (arg[index + 1] as number) || 0;
} else if (truthy(find(subEvent, "_AURA_APPLIED_DOSE$"))) {
const payload = this.payload as AuraAppliedDosePayload;
payload.type = "AURA_APPLIED_DOSE";
payload.auraType = (arg[index] as AuraType) || "DEBUFF";
payload.amount = (arg[index + 1] as number) || 0;
} else if (truthy(find(subEvent, "_AURA_REMOVED_DOSE$"))) {
const payload = this.payload as AuraRemovedDosePayload;
payload.type = "AURA_REMOVED_DOSE";
payload.auraType = (arg[index] as AuraType) || "DEBUFF";
payload.amount = (arg[index + 1] as number) || 0;
} else if (truthy(find(subEvent, "_AURA_REFRESH$"))) {
const payload = this.payload as AuraRefreshPayload;
payload.type = "AURA_REFRESH";
payload.auraType = (arg[index] as AuraType) || "DEBUFF";
payload.amount = (arg[index + 1] as number) || 0;
} else if (truthy(find(subEvent, "_AURA_BROKEN$"))) {
const payload = this.payload as AuraBrokenPayload;
payload.type = "AURA_BROKEN";
payload.auraType = (arg[index] as AuraType) || "DEBUFF";
} else if (truthy(find(subEvent, "_AURA_BROKEN_SPELL$"))) {
const payload = this.payload as AuraBrokenSpellPayload;
payload.type = "AURA_BROKEN_SPELL";
payload.spellId = (arg[index] as number) || 0;
payload.spellName = (arg[index + 1] as string) || "";
payload.school = (arg[index + 2] as number) || 0;
payload.auraType = (arg[index + 3] as AuraType) || "DEBUFF";
} else if (truthy(find(subEvent, "_CAST_START$"))) {
this.payload.type = "CAST_START";
} else if (truthy(find(subEvent, "_CAST_SUCCESS$"))) {
this.payload.type = "CAST_SUCCESS";
} else if (truthy(find(subEvent, "_CAST_FAILED$"))) {
const payload = this.payload as CastFailedPayload;
payload.type = "CAST_FAILED";
payload.failedType = (arg[index] as string) || "CAST_FAILED";
} else if (truthy(find(subEvent, "_INSTAKILL$"))) {
this.payload.type = "INSTAKILL";
} else if (truthy(find(subEvent, "_DURABILITY_DAMAGE$"))) {
this.payload.type = "DURABILITY_DAMAGE";
} else if (truthy(find(subEvent, "_DURABILITY_DAMAGE_ALL$"))) {
this.payload.type = "DURABILITY_DAMAGE_ALL";
} else if (truthy(find(subEvent, "_CREATE$"))) {
this.payload.type = "CREATE";
} else if (truthy(find(subEvent, "_SUMMON$"))) {
this.payload.type = "SUMMON";
} else if (truthy(find(subEvent, "_DISSIPATES$"))) {
this.payload.type = "DISSIPATES";
}
}
this.tracer.debug(this.subEvent, this.getCurrentEventInfo());
this.fire(this.subEvent);
};
hasEventHandler = (event: string) => {
const handlers = this.registry[event];
return (handlers && next(handlers) && true) || false;
};
fire = (event: string) => {
if (this.registry[event]) {
this.fireDepth += 1;
for (const [, handler] of pairs(this.registry[event])) {
handler(event);
}
this.fireDepth -= 1;
if (this.fireDepth == 0) {
// Add all pending registrations to the main registry.
for (const [event, handlers] of pairs(this.pendingRegistry)) {
for (const [token, handler] of pairs(handlers)) {
this.insertEventHandler(
this.registry,
event,
token,
handler
);
}
}
}
}
};
private insertEventHandler = (
registry: CombatLogEventHandlerRegistry,
event: string,
token: any,
handler: CombatLogEventHandler
) => {
const handlers = registry[event] || {};
// Pretend to cast to string to satisfy Typescript.
const key = token as unknown as string;
handlers[key] = handler;
registry[event] = handlers;
};
private removeEventHandler = (
registry: CombatLogEventHandlerRegistry,
event: string,
token: any
) => {
const handlers = registry[event];
if (handlers) {
// Pretend to cast to string to satisfy Typescript.
const key = token as unknown as string;
delete handlers[key];
if (!next(handlers)) {
delete registry[event];
}
}
};
registerEvent = (
event: string,
token: any,
handler: CombatLogEventHandler
) => {
if (this.fireDepth > 0) {
this.insertEventHandler(
this.pendingRegistry,
event,
token,
handler
);
} else {
this.insertEventHandler(this.registry, event, token, handler);
}
};
unregisterEvent = (event: string, token: any) => {
this.removeEventHandler(this.pendingRegistry, event, token);
this.removeEventHandler(this.registry, event, token);
};
unregisterAllEvents = (token: any) => {
for (const [event] of pairs(this.registry)) {
this.unregisterEvent(event, token);
}
};
getCurrentEventInfo() {
return unpack(this.arg);
}
} | the_stack |
import { isIn } from '@nestled/util';
import * as color from 'chalk';
import { execSync } from 'child_process';
import { CommanderStatic } from 'commander';
import * as getGitBranch from 'current-git-branch';
import * as emoji from 'node-emoji';
import { CONFIG_FILE_NAME } from '../constants';
import { hasCached, saveCache } from '../helpers';
import { IMrepoConfigFile } from '../interfaces';
import { loadLernaFile, logger } from '../utils';
enum AvailableCommands {
CLEAN = 'clean',
BUILD = 'build',
TEST = 'test',
LINK = 'link',
UNLINK = 'unlink',
RELEASE = 'release',
}
const RELEASE_SEMVER = ['patch', 'minor', 'major', 'prepatch', 'preminor', 'premajor', 'prerelease', 'select'];
const RELEASE_SEMVER_STR = RELEASE_SEMVER.join(', ');
export class MainCommands {
static load(program: CommanderStatic['program'], configFile: IMrepoConfigFile) {
const packagesNames = configFile.workspace.packages.map((p) => p.name);
const packagesNamesStr = packagesNames.join(', ');
const { scope, name: workspaceName } = configFile.workspace;
/**
* Clean packages
*/
program
.command(AvailableCommands.CLEAN)
.alias('c')
.arguments('[package]')
.description('Clean package(s)', {
package: `Package name, if specified. One of: ${packagesNamesStr}`,
})
.action((packageName: string) => runClean(packageName));
/**
* Build packages
*/
program
.command(AvailableCommands.BUILD)
.alias('b')
.arguments('[package]')
.option('--no-cache', 'Force build without cache comparison', false)
.description('Build package(s)', {
package: `Package name, if specified. One of: ${packagesNamesStr}`,
})
.action(async (packageName: string, options: any) => runBuild(packageName, options.cache));
/**
* Test packages
*/
program
.command(AvailableCommands.TEST)
.alias('t')
.arguments('[package]')
.description('Run tests for package(s)', {
package: `Package name, if specified. One of: ${packagesNamesStr}`,
})
.option('-f, --folder <value>', 'Tests folder', workspaceName)
.option('-s, --suite <value>', 'Test suite', '')
.option('-c, --config <value>', 'Jest config file', 'jest.config.js')
.option('--coverage', 'Run with coverage', false)
.option('--addCollectCoverageFrom <value>', 'Add collect coverage rules to defaults', '')
.option('--verbose', 'Run verbose', false)
.description('Test package(s)', {
package: `Package name, if specified. One of: ${packagesNamesStr}`,
})
.action((packageName: string, options: any) => runTest(packageName, options));
/**
* Link packages
*/
program
.command(AvailableCommands.LINK)
.alias('l')
.arguments('[package]')
.option('--build', 'Build before linking', false)
.description('Link package(s)', {
package: `Package name, if specified. One of: ${packagesNamesStr}`,
})
.action((packageName: string, options: any) => runLink(packageName, options));
/**
* Unlink packages
*/
program
.command(AvailableCommands.UNLINK)
.alias('u')
.arguments('[package]')
.description('Unlink package(s)', {
package: `Package name, if specified. One of: ${packagesNamesStr}`,
})
.action((packageName: string) => runUnlink(packageName));
/**
* Release packages
*/
program
.command(AvailableCommands.RELEASE)
.alias('r')
.arguments('<semver> value')
.option('--no-git-push', 'Skip git commit and push', false)
.option('--no-changelog', 'Skip changelog generation', false)
.option('--preid <value>', 'Prerelease identifier', 'alpha')
.option('--dist-tag <value>', 'Dist tag if Lerna version is "independent"', 'latest')
.option('--force-publish', 'Force packages release', false)
.description('Release package(s)', {
semver: `Package version semver type. One of: ${RELEASE_SEMVER_STR}`,
})
.action((semver: string, options: any) => runRelease(semver, options));
/**
* Run `clean` command
* @param packageName string
*/
function runClean(packageName?: string) {
const placesToRemove = ['lib', 'tsconfig.tsbuildinfo', 'node_modules', 'package-lock.json'];
const exec = (pName: string) => {
const p = `./${workspaceName}/${pName}/`;
logger.info(AvailableCommands.CLEAN, `Cleaning ${color.italic.bold(pName)}`, emoji.get(':boom:'));
execSync(`npx rimraf ${placesToRemove.map((n) => p + n).join(' ')}`, { stdio: 'inherit' });
};
if (!packageName) {
packagesNames.forEach((pName: string) => {
exec(pName);
});
} else {
validatePackageExist(packageName, packagesNames);
exec(packageName);
}
logger.info(AvailableCommands.CLEAN, `Cleaning ${color.green('done')}`, emoji.get(':ok_hand:'));
}
/**
* Run `build` command
* @param packageName string
*/
async function runBuild(packageName: string, useCache = true) {
const exec = async (pName: string) => {
const hasCache = await hasCached(workspaceName, pName);
if (!useCache || !hasCache) {
logger.info(AvailableCommands.BUILD, `Building ${color.italic.bold(pName)}`, emoji.get(':package:'));
execSync(`npx lerna run build --scope @${scope}/${pName}`, { stdio: 'inherit' });
await saveCache(workspaceName, pName);
} else {
logger.info(
AvailableCommands.BUILD,
`Package ${color.italic.bold(pName)} has been built already`,
emoji.get(':ok_hand:'),
);
}
};
if (!packageName) {
for (let i = 0; i < packagesNames.length; i++) {
const pName = packagesNames[i];
await exec(pName);
}
} else {
validatePackageExist(packageName, packagesNames);
exec(packageName);
}
logger.info(AvailableCommands.BUILD, `Building ${color.green('done')}`, emoji.get(':ok_hand:'));
}
/**
* Run `test` command
* @param packageName string
* @param options object
*/
function runTest(packageName?: string, options?: any) {
const config = `-c=${options.config}`;
const coverage = options.coverage ? '--coverage' : '';
const verbose = options.verbose ? '--verbose' : '';
const suite = options.suite ? options.suite : '';
let where = '';
let collectCoverageFrom = '';
if (!packageName) {
logger.info(AvailableCommands.TEST, 'Running tests', emoji.get(':zap:'));
where = `${options.folder}/*`;
} else {
validatePackageExist(packageName, packagesNames);
logger.info(AvailableCommands.TEST, `Running tests for ${color.italic.bold(packageName)}`, emoji.get(':zap:'));
where = `${options.folder}/${packageName}/${suite}`;
if (coverage) {
const addToRules = options.addCollectCoverageFrom ? options.addCollectCoverageFrom : '';
collectCoverageFrom = `--collectCoverageFrom='["${options.folder}/${packageName}/**/*.ts","!${
options.folder
}/${packageName}/**/*.d.ts","!${options.folder}/${packageName}/**/index.ts","!${
options.folder
}/${packageName}/**/*.interface.ts","!**/node_modules/**","!**/__stubs__/**","!**/__fixture__/**","!integration/*"${
addToRules ? ',"' + addToRules.split(',').join('","') + '"' : ''
}]'`;
}
}
const cmd = `npx jest --runInBand --detectOpenHandles ${config} ${where} ${coverage} ${collectCoverageFrom} ${verbose}`;
execSync(cmd, { stdio: 'inherit' });
logger.info(AvailableCommands.TEST, `Running tests ${color.green('done')}`, emoji.get(':ok_hand:'));
}
/**
* Run `link` command
* @param packageName string
* @param options object
* @param configFile: IMrepoConfigFile
*/
function runLink(packageName: string, options: any) {
const exec = (pName: string) => {
logger.info(AvailableCommands.LINK, `Linking ${color.italic.bold(pName)}`, emoji.get(':loudspeaker:'));
execSync(`cd ./${workspaceName}/${pName} && npm link`, { stdio: 'inherit' });
};
if (!packageName) {
if (options.build) {
runBuild(undefined, false);
}
packagesNames.forEach((pName: string) => {
exec(pName);
});
} else {
validatePackageExist(packageName, packagesNames);
if (options.build) {
runBuild(packageName, false);
}
exec(packageName);
}
logger.info(AvailableCommands.LINK, `Linking ${color.green('done')}`, emoji.get(':ok_hand:'));
}
/**
* Run `unlink` command
* @param packageName string
*/
function runUnlink(packageName?: string) {
const exec = (pName: string) => {
logger.info(AvailableCommands.UNLINK, `Unlinking ${color.italic.bold(pName)}`, emoji.get(':loudspeaker:'));
execSync(`cd ./${workspaceName}/${pName} && npm unlink`, { stdio: 'inherit' });
};
if (!packageName) {
packagesNames.forEach((pName: string) => {
exec(pName);
});
} else {
exec(packageName);
}
logger.info(AvailableCommands.UNLINK, `Unlinking ${color.green('done')}`, emoji.get(':ok_hand:'));
}
/**
* Run `release` command
* @param semver string
*/
function runRelease(semver: string, options?: any) {
logger.info(AvailableCommands.RELEASE, 'Creating new release version(s)', emoji.get(':rocket:'));
const lernaFile = loadLernaFile();
const isIndependent = lernaFile.version === 'independent';
const isCustomVersion = semver === 'select';
const semverStr = isCustomVersion ? '' : semver;
validateReleaseSemver(semver);
if (options.gitPush) {
validateReleaseGitBranch();
}
const preid = semver.startsWith('pre') ? `--preid ${options.preid}` : '';
const withChangelog = options.changelog && !isCustomVersion ? '--conventional-commits' : '';
const forcePublish = options.forcePublish ? '--force-publish' : '';
const lernaVersionCmd = `npx lerna version ${semverStr} --no-git-tag-version ${withChangelog} ${preid} ${forcePublish}`;
execSync(lernaVersionCmd, { stdio: 'inherit' });
if (isIndependent) {
execSync(`npx json -I -f ${process.cwd()}/lerna.json -e "this.distTag='${options.distTag}'"`);
execSync(`git add . && git commit -m "chore: release with --dist-tag=${options.distTag}"`);
} else {
const updatedLernaFile = loadLernaFile();
execSync(`git add . && git commit -m "chore: release v${updatedLernaFile.version}"`);
}
logger.info(
AvailableCommands.RELEASE,
`Creating new release version(s) ${color.green('done')}`,
emoji.get(':ok_hand:'),
);
}
/**
* Validate package exists in config
* @param packageName string
* @param packagesNames string[]
*/
function validatePackageExist(packageName: string, packagesNames: string[]) {
if (!isIn(packageName, packagesNames)) {
const msg = `${emoji.get(':flushed:')} Sorry, package ${color.bold(name)} hasn't been specified in ${color.bold(
`${CONFIG_FILE_NAME} -> workspace -> packages`,
)}`;
logger.error('oops', msg);
throw new Error(msg);
}
}
/**
* Validate release semver
* @param semver
*/
function validateReleaseSemver(semver: string) {
if (!isIn(semver, RELEASE_SEMVER)) {
const msg = `${emoji.get(':flushed:')} Sorry, release version semver type must be one of ${color.bold(
RELEASE_SEMVER_STR,
)}`;
logger.error('oops', msg);
throw new Error(msg);
}
}
function validateReleaseGitBranch() {
const branch = getGitBranch({
altPath: process.cwd(),
});
if (!branch || !branch.startsWith('release')) {
const msg = `${emoji.get(':flushed:')} Sorry, release branch name should start with ${color.bold('release')}`;
logger.error('oops', msg);
throw new Error(msg);
}
}
}
} | the_stack |
type FlagTarget = Element | Document | string;
interface Event {
/**
Tells the browser that the default action should not be taken. The event will still continue to propagate up the tree. See Event.preventDefault()
@see https://imba.io/events/event-modifiers#core-prevent
*/
αprevent(): void;
/**
Stops the event from propagating up the tree. Event listeners for the same event on nodes further up the tree will not be triggered. See Event.stopPropagation()
*/
αstop(): void;
/**
Prevents default action & stops event from bubbling.
*/
αtrap(): void;
/**
* Indicates that the listeners should be invoked at most once. The listener will automatically be removed when invoked.
*/
αonce(): void;
/**
* Indicating that events of this type should be dispatched to the registered listener before being dispatched to tags deeper in the DOM tree.
*/
αcapture(): void;
/**
* Indicates that the listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. This is useful for optimal performance while scrolling etc.
*
* @summary indicates that the listener will never call preventDefault()
*/
αpassive(): void;
/**
* By default, Imba will re-render all scheduled tags after any *handled* event. So, Imba won't re-render your application if you click an element that has no attached handlers, but if you've added a `@click` listener somewhere in the chain of elements, `imba.commit` will automatically be called after the event has been handled.
This is usually what you want, but it is useful to be able to override this, especially when dealing with `@scroll` and other events that might fire rapidly.
#### Syntax
```imba
# Will only trigger when intersection ratio increases
<div @click.silent=handler>
# Will only trigger when element is more than 50% visible
<div @intersect(0.5).in=handler>
```
* @summary Don't trigger imba.commit from this event handler
*/
αsilent(): void;
/** The wait modifier delays the execution of subsequent modifiers and callback. It defaults to wait for 250ms, which can be overridden by passing a number or time as the first/only argument.
*
* @summary pause handler for `n` duration (default 250ms)
* @detail (time = 500ms)
*/
αwait(time?: Time): void;
/**
* The `throttle` modifier ensures the handler is called at most every `n` milliseconds (defaults to 500ms). This can be useful for events that fire very rapidly like `@scroll`, `@pointermove` etc.
*
* See `@event.cooldown` and `@event.debounce`.
* @detail (time = 500ms)
* @summary ensures that handler triggers at most every `n` seconds
*/
αthrottle(time?: Time): void;
/**
* The `cooldown` modifier ensures the handler is called at most every `n` milliseconds (defaults to 500ms). This can be useful for events that fire very rapidly like `@scroll`, `@pointermove` etc.
*
* See `@event.throttle` and `@event.debounce`.
*
* @detail (time = 500ms)
* @summary disable handler for a duration after trigger
*/
αcooldown(time?: Time): void;
/**
* The `debounce` modifier ensures that a minimum amount of time has elapsed after the user stops interacting and before calling the handler. This is especially useful, for example, when querying an API and not wanting to perform a request on every keystroke.
*
* See `@event.cooldown` and `@event.throttle`.
* @detail (time = 500ms)
* @summary dont trigger until no events has been handled for `n` time
*/
αdebounce(time?: Time): void;
/**
Stops handling unless event is trusted
@see https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
*/
αtrusted(): boolean;
/**
* The `self` event modifier is a handy way of reacting to events only when they are clicked on the actual element you are interacting with and not, for example, a child element. This can be useful for things like modal wrappers when you only want to react when clicking directly.
* @summary Only trigger handler if event.target is the element itself
*/
αself(): boolean;
/**
* Only trigger handler if event.target matches selector
* @detail (selector)
* */
αsel(selector: string): boolean;
/**
* Only trigger handler if event.target.closest(selector) returns a match
* @detail (selector)
* */
αclosest(selector: string): boolean;
/**
* Only trigger condition is truthy
* @detail (condition)
* */
αif(condition: unknown): boolean;
/**
* Trigger a custom event via this handler
* @param name The name of the event to trigger
* @param detail Data associated with the event
* @detail (name,detail = {})
* */
αemit(name: string, detail?: any): void;
/**
* Trigger a custom event via this handler
* @param detail Data associated with the event
* @deprecated
* */
αemitΞname(detail?: any): void;
/**
* Add an html class to target for at least 250ms
* If the callback returns a promise, the class
* will not be removed until said promise has resolved
* @param name the class to add
* @param target the element on which to add the class. Defaults to the element itself
* @detail (name,target?)
* */
αflag(name: string, target?: FlagTarget): void;
/**
* Add an html class to target for at least 250ms
* If the callback returns a promise, the class
* will not be removed until said promise has resolved
* @param target the element on which to add the class. Defaults to the element itself
* @deprecated
**/
αflagΞname(target?: FlagTarget): void;
/**
* Logs to console
* @detail (...data)
*/
αlog(...data: any[]): void;
}
interface MouseEvent {
/**
* Handle if ctrlKey is pressed
*
*/
αctrl(): boolean;
/**
* Handle if altKey is pressed
*
*/
αalt(): boolean;
/**
* Handle if shiftKey is pressed
*
*/
αshift(): boolean;
/**
* Handle if metaKey is pressed
*
*/
αmeta(): boolean;
/**
* Apple uses the ⌘ key while others use the Ctrl key for many keyboard shortcuts
* and features like (⌘ or Ctrl)+click for opening a link in a new tab.
* This modifier unifies the logic and is essentially an alias for `.meta` on mac,
* and `.ctrl` for all other platforms.
*
* @summary Handle if metaKey (on mac) or ctrlKey (other platforms) is pressed
*
*/
αmod(): boolean;
/**
* Handle if middle button is pressed
*
*/
αmiddle(): boolean;
/**
* Handle if left/primary button is pressed
*
*/
αleft(): boolean;
/**
* Handle if right button is pressed
*
*/
αright(): boolean;
}
interface KeyboardEvent {
/**
* Handle if enter key is pressed
*
*/
αenter(): boolean;
/**
* Handle if left key is pressed
*
*/
αleft(): boolean;
/**
* Handle if right key is pressed
*
*/
αright(): boolean;
/**
* Handle if up key is pressed
*
*/
αup(): boolean;
/**
* Handle if down key is pressed
*
*/
αdown(): boolean;
/**
* Handle if tab key is pressed
*
*/
αtab(): boolean;
/**
* Handle if esc key is pressed
*
*/
αesc(): boolean;
/**
* Handle if space key is pressed
*
*/
αspace(): boolean;
/**
* Handle if del key is pressed
*
*/
αdel(): boolean;
/**
* Handle if keyCode == code
* @detail (code)
*/
αkey(code:number): boolean;
}
interface PointerEvent {
/**
* @summary Handle if the event was generated by a mouse device.
*/
αmouse(): boolean;
/**
* @summary Handle if the event was generated by a pen or stylus device.
*/
αpen(): boolean;
/**
* @summary Handle if the event was generated by a touch, such as a finger.
*/
αtouch(): boolean;
/**
* Only when pressure is at least amount (defaults to 0.5)
* @detail (threshold=0.5)
*/
αpressure(amount?:number): boolean;
}
interface DragEvent {
}
type ModifierElementTarget = Element | string;
declare namespace imba {
/**
* To make it easier and more fun to work with touches, Imba includes a custom `@touch` event that combines `@pointerdown` -> `@pointermove` -> `@pointerup` in one convenient handler, with modifiers for commonly needed functionality.
* @custom
*/
declare class Touch {
/** The final X coordinate of the pointer (after modifiers) */
x: number;
/** The final Y coordinate of the pointer (after modifiers) */
y: number;
target: Element;
/** The X coordinate of the pointer in local (DOM content) coordinates. */
get clientX(): number;
/** The Y coordinate of the mouse pointer in local (DOM content) coordinates. */
get clientY(): number;
/** True if touch is still active */
get activeΦ(): boolean;
/** True if touch has ended */
get endedΦ(): boolean;
/** Returns true if the `control` key was down when the mouse event was fired. */
get ctrlKey(): boolean;
/** Returns true if the `alt` key was down when the mouse event was fired. */
get altKey(): boolean;
/** Returns true if the `shift` key was down when the mouse event was fired. */
get shiftKey(): boolean;
/** Returns true if the `shift` key was down when the mouse event was fired. */
get metaKey(): boolean;
/** Indicates the device type that caused the event (mouse, pen, touch, etc.) */
get pointerType(): string;
/**
The identifier is unique, being different from the identifiers of all other active pointer events. Since the value may be randomly generated, it is not guaranteed to convey any particular meaning.
@summary A unique identifier for the pointer causing the event.
* */
get pointerId(): number;
/**
* This guard will break the chain unless the touch has moved more than threshold. Once this threshold has been reached, all subsequent updates of touch will pass through. The element will also activate the `@move` pseudostate during touch - after threshold is reached.
* #### Syntax
```imba
<div @touch.moved(threshold=4px, dir='any')>
```
* @summary Only when touch has moved more than threshold
* @detail (threshold = 4px, dir = 'any')
*/
αmoved(threshold?: Length, dir?: string): boolean;
/**
* Only when touch has moved left or right more than threshold
* @detail (threshold = 4px)
* @deprecated
*/
αmovedΞx(threshold?: Length): boolean;
/**
* Only when touch has moved up or down more than threshold
* @detail (threshold = 4px)
* @deprecated
*/
αmovedΞy(threshold?: Length): boolean;
/**
* Only when touch has moved up more than threshold
* @detail (threshold = 4px)
** @deprecated
*/
αmovedΞup(threshold?: Length): boolean;
/**
* Only when touch has moved down more than threshold
* @detail (threshold = 4px)
* @deprecated
*/
αmovedΞdown(threshold?: Length): boolean;
/**
* Only when touch has moved left more than threshold
* @detail (threshold = 4px)
* @deprecated
*/
αmovedΞleft(threshold?: Length): boolean;
/**
* Only when touch has moved right more than threshold
* @detail (threshold = 4px)
* @deprecated
*/
αmovedΞright(threshold?: Length): boolean;
/**
* This guard will break the chain unless the touch has been held for a duration.
* If the pointer moves more than 5px before the modifier activates, the handler will
* essentially be cancelled.
* #### Syntax
```imba
<div @touch.hold(duration=250ms)>
```
* @summary Only start handling after pressing and holding still
* @detail (duration = 250ms)
*/
αhold(threshold?: Length, dir?: string): boolean;
/**
* A convenient touch modifier that takes care of updating the x,y values of some data during touch. When touch starts sync will remember the initial x,y values and only add/subtract based on movement of the touch.
*
* #### Syntax
```imba
<div @touch.sync(target, xprop='x', yprop='y')>
```
* @summary Sync the x,y properties of touch to another object
* @detail (data, xProp?, yProp?)
*/
αsync(data: object, xName?: string | null, yName?: string | null): boolean;
/**
* Sets the x and y properties of object to the x and y properties of touch.
*
* @see https://imba.io/events/touch-events#modifiers-apply
* @detail (data, xProp?, yProp?)
*/
αapply(data: object, xName?: string | null, yName?: string | null): boolean;
/**
* A very common need for touches is to convert the coordinates of the touch to some other frame of reference. When dragging you might want to make x,y relative to the container. For a custom slider you might want to convert the coordinates from pixels to relative offset of the slider track. There are loads of other scenarios where you'd want to convert the coordinates to some arbitrary scale and offset. This can easily be achieved with fitting modifiers.
* #### Syntax
```imba
<div @touch.fit> # make x,y relative to the element
<div @touch.fit(start,end,snap?)>
<div @touch.fit(target)> # make x,y relative to a target element
<div @touch.fit(target,start,end,snap?)>
<div @touch.fit(target,[xstart,ystart],[xend,yend],snap?)>
```
* @summary Convert the coordinates of the touch to some other frame of reference.
* @detail (target?,snap?)
*/
αfit(): void;
αfit(start: Length, end: Length, snap?: number): void;
αfit(target: ModifierElementTarget): void;
αfit(target: ModifierElementTarget, snap?: number): void;
αfit(target: ModifierElementTarget, snap?: number): void;
αfit(target: ModifierElementTarget, start: Length, end: Length, snap?: number): void;
/**
* Just like @touch.fit but without clamping x,y to the bounds of the
* target.
* @detail (target?, ax?, ay?)
*/
αreframe(): void;
αreframe(start: Length, end: Length, snap?: number): void;
αreframe(context: Element | string, snap?: number): void;
αreframe(context: Element | string, start: Length, end: Length, snap?: number): void;
/**
* Allow pinning the touch to a certain point in an element, so that
* all future x,y values are relative to this pinned point.
* @detail (target?, ax?, ay?)
*/
αpin(): void;
αpin(target: ModifierElementTarget): void;
αpin(anchorX: number, anchorY?: number): void;
αpin(target: ModifierElementTarget, anchorX?: number, anchorY?: number): void;
/**
* Round the x,y coordinates with an optional accuracy
* @detail (to = 1)
*/
αround(nearest?: number): void;
/**
* Add an html class to target for at least 250ms
* If the callback returns a promise, the class
* will not be removed until said promise has resolved
* @param name the class to add
* @param target the element on which to add the class. Defaults to the element itself
* @detail (name,target?)
* */
αflag(name: string, target?: FlagTarget): void;
/**
* Add an html class to target for at least 250ms
* If the callback returns a promise, the class
* will not be removed until said promise has resolved
* @param target the element on which to add the class. Defaults to the element itself
* @deprecated
**/
αflagΞname(target?: FlagTarget): void;
/**
* Only trigger handler if event.target matches selector
* @detail (selector)
* */
αsel(selector: string): boolean;
/**
Tells the browser that the default action should not be taken. The event will still continue to propagate up the tree. See Event.preventDefault()
@see https://imba.io/events/event-modifiers#core-prevent
*/
αprevent(): void;
/**
Stops the event from propagating up the tree. Event listeners for the same event on nodes further up the tree will not be triggered. See Event.stopPropagation()
*/
αstop(): void;
/**
Prevents default action & stops event from bubbling.
*/
αtrap(): void;
/**
* The `self` event modifier is a handy way of reacting to events only when they are clicked on the actual element you are interacting with and not, for example, a child element. This can be useful for things like modal wrappers when you only want to react when clicking directly.
* @summary Only trigger handler if event.target is the element itself
*/
αself(): boolean;
/**
* @summary Don't trigger imba.commit from this event handler
*/
αsilent(): void;
/**
* @summary Suppress pointer events on all other elements
*/
αlock(): void;
}
type IntersectRoot = Element | Document;
type IntersectOptions = {
rootMargin?: string;
root?: IntersectRoot;
thresholds?: number[];
}
/**
[IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) is a [well-supported](https://caniuse.com/#feat=intersectionobserver) API in modern browsers. It provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. Imba adds a simplified abstraction on top of this via the custom `@intersect` event.
#### Syntax
```imba
# Will only trigger when intersection ratio increases
<div @intersect.in=handler>
# Will only trigger when element is more than 50% visible
<div @intersect(0.5).in=handler>
```
#### Parameters
The `@intersect` events accepts several arguments. You can pass in an object with the same [root](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/root), [rootMargin](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin), and [threshold](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/threshold) properties supported by [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver).
```imba
<div @intersect=handler> # default options
<div @intersect(root: frame, rootMargin: '20px')=handler>
<div @intersect(threshold: [0,0.5,1])=handler>
```
For convenience, imba will convert certain arguments into options. A single number between 0 and 1 will map to the [threshold](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/threshold) option:
```imba
# n 0-1 adds single threshold at n visibility
<div @intersect(0)=handler> # {threshold: 0}
<div @intersect(0.5)=handler> # {threshold: 0.5}
<div @intersect(1)=handler> # {threshold: 1.0}
```
Any number above 1 will add n thresholds, spread evenly:
```imba
<div @intersect(2)=handler> # {threshold: [0,1]}
<div @intersect(3)=handler> # {threshold: [0,0.5,1]}
<div @intersect(5)=handler> # {threshold: [0,0.25,0.5,0.75,1]}
# ... and so forth
```
An element will map to the [root](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/root) option:
```imba
<div @intersect(frame)=handler> # {root: frame}
<div @intersect(frame,3)=handler> # {root: frame, threshold: [0,0.5,1]}
```
A string will map to the [rootMargin](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin) option:
```imba
<div @intersect("20px 10px")=handler> # {rootMargin: "20px 10px"}
```
* @custom
*/
declare class IntersectEvent extends Event {
/**
The `out` modifier stops the handler unless intersectionRatio has *increased*.
#### Syntax
```imba
# Will only trigger when intersection ratio increases
<div @intersect.in=handler>
# Will only trigger when element is more than 50% visible
<div @intersect(0.5).in=handler>
```
@summary Stop handling unless intersectionRatio has increased.
*/
αin(): boolean;
/**
*
The `out` modifier stops the handler unless intersectionRatio has *decreased*.
#### Syntax
```imba
# Will only trigger when element starts intersecting
<div @intersect.out=handler>
# Will trigger whenever any part of the div is hidden
<div @intersect(1).out=handler>
```
@summary Stop handling unless intersectionRatio has decreased.
*/
αout(): boolean;
/**
The css modifier sets a css variable --ratio on the event target with the current ratio.
@summary Set css variable `--ratio` to the intersectionRatio.
*/
αcss(): void;
/**
* Will add a class to the DOM element when intersecting
* @param name The class-name to add
*/
αflag(name: string): void;
/**
* Configuring
* @param root reference to the parent
* @param thresholds 0-1 for a single threshold, 2+ for n slices
*/
αoptions(root?: IntersectRoot, thresholds?: number): void;
αoptions(thresholds?: number): void;
αoptions(rootMargin: string, thresholds?: number): void;
αoptions(rootMargin: string, thresholds?: number): void;
αoptions(options: IntersectOptions): void;
/**
* The raw IntersectionObserverEntry
*
*/
entry: IntersectionObserverEntry;
/**
* Ratio of the intersectionRect to the boundingClientRect
*
*/
ratio: number;
/**
* Difference in ratio since previous event
*
*/
delta: number;
}
declare class HotkeyEvent extends Event {
/**
*
* @param pattern string following pattern from mousetrap
* @see https://craig.is/killing/mice
*/
αoptions(pattern:string): void;
/**
* Also trigger when input,textarea or a contenteditable is focused
* @deprecated Use `force` instead
*/
αcapture(): void;
/**
* Trigger even if outside of the originating hotkey group
*/
αglobal(): void;
/**
* Allow subsequent hotkey handlers for the same combo
* and don't automatically prevent default behaviour of originating
* keyboard event
*/
αpassive(): void;
/**
* Also trigger when input,textarea or a contenteditable is focused
*/
αforce(): void;
/**
* Allow the handler to trigger multiple times while user
* keeps pressing the key combination.
*/
αrepeat(): void;
/**
* The KeyboardEvent responsible for this HotkeyEvent
*
*/
readonly originalEvent: KeyboardEvent;
/**
* The combo for the event
*
*/
readonly combo: string;
}
/**
* The [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) interface reports changes to the dimensions of an Element's content or border box. It has [good browser support](https://caniuse.com/#feat=resizeobserver) and is very useful in a wide variety of usecases. ResizeObserver avoids infinite callback loops and cyclic dependencies that are often created when resizing via a callback function. It does this by only processing elements deeper in the DOM in subsequent frames.
* @custom
*/
declare class ResizeEvent extends UIEvent {
/** Width of the resized element */
readonly width: number;
/** Height of the resized element */
readonly height: number;
/** contentRect from the ResizeObserverEntry */
readonly rect: DOMRectReadOnly;
/** the raw ResizeObserverEntry */
readonly entry: ResizeObserverEntry;
}
declare class SelectionEvent extends Event {
detail: {
start: number;
end: number;
}
}
}
interface GlobalEventHandlersEventMap {
"touch": imba.Touch;
"intersect": imba.IntersectEvent;
"selection": imba.SelectionEvent;
"hotkey": imba.HotkeyEvent;
"resize": imba.ResizeEvent;
"__unknown": CustomEvent;
}
interface HTMLElementEventMap {
"resize": imba.ResizeEvent;
}
interface ImbaEvents {
/**
* The loading of a resource has been aborted.
*
*/
abort: Event;
animationcancel: AnimationEvent;
/**
* A CSS animation has completed.
*
*/
animationend: AnimationEvent;
/**
* A CSS animation is repeated.
*
*/
animationiteration: AnimationEvent;
/**
* A CSS animation has started.
*
*/
animationstart: AnimationEvent;
auxclick: MouseEvent;
/**
* An element has lost focus (does not bubble).
*
*/
blur: FocusEvent;
cancel: Event;
/**
* The user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
*
*/
canplay: Event;
/**
* The user agent can play the media up to its end without having to stop for further buffering of content.
*
*/
canplaythrough: Event;
/**
* The change event is fired for `<input>`, `<select>`, and `<textarea>` elements when a change to the element's value is committed by the user.
*
*/
change: Event;
/**
* A pointing device button has been pressed and released on an element.
*
*/
click: MouseEvent;
close: Event;
contextmenu: MouseEvent;
cuechange: Event;
dblclick: MouseEvent;
drag: DragEvent;
dragend: DragEvent;
dragenter: DragEvent;
dragleave: DragEvent;
dragover: DragEvent;
dragstart: DragEvent;
/**
* @summaryz Fires when an element or text selection is dropped on a valid drop target.
*/
drop: DragEvent;
durationchange: Event;
emptied: Event;
ended: Event;
error: ErrorEvent;
focus: FocusEvent;
focusin: FocusEvent;
focusout: FocusEvent;
/**
* @custom
* @summary Fired when the supplied keycombo is pressed anywhere in the document.
* @detail (combo)
*/
hotkey: imba.HotkeyEvent;
input: Event;
invalid: Event;
/**
* @custom
* @summary Fired when the element appears in the viewport (or another element).
*/
intersect: imba.IntersectEvent;
keydown: KeyboardEvent;
keypress: KeyboardEvent;
keyup: KeyboardEvent;
load: Event;
loadeddata: Event;
loadedmetadata: Event;
loadstart: Event;
mousedown: MouseEvent;
mouseenter: MouseEvent;
mouseleave: MouseEvent;
mousemove: MouseEvent;
mouseout: MouseEvent;
mouseover: MouseEvent;
mouseup: MouseEvent;
pause: Event;
play: Event;
playing: Event;
/**
* @summary A browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactivated).
*/
pointercancel: PointerEvent;
/**
* @summary Fired when a pointer becomes active buttons state.
*/
pointerdown: PointerEvent;
/**
* @summary Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown).
*/
pointerenter: PointerEvent;
/**
* @summary Fired when a pointer is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer.
*/
pointerleave: PointerEvent;
/**
* @summary Fired when a pointer changes coordinates. This event is also used if the change in pointer state can not be reported by other events.
*/
pointermove: PointerEvent;
/**
* @summary Fired for several reasons including: pointer is moved out of the hit test boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer.
*/
pointerout: PointerEvent;
/**
* @summary Fired when a pointer is moved into an element's hit test boundaries.
*/
pointerover: PointerEvent;
/**
* @summary Fired when a pointer is no longer active buttons state.
*/
pointerup: PointerEvent;
/**
* @summary Fired when an element receives pointer capture.
*/
gotpointercapture: PointerEvent;
/**
* @summary Fired after pointer capture is released for a pointer.
*/
lostpointercapture: PointerEvent;
progress: ProgressEvent;
ratechange: Event;
reset: Event;
/**
* @custom
* @summary Fired when element is resized.
*/
resize: imba.ResizeEvent;
scroll: Event;
securitypolicyviolation: SecurityPolicyViolationEvent;
seeked: Event;
seeking: Event;
select: Event;
selectionchange: Event;
selectstart: Event;
stalled: Event;
submit: Event;
suspend: Event;
timeupdate: Event;
toggle: Event;
/**
* @custom
* @summary Normalized handler for pointerdown->move->up with powerful custom modifiers.
*/
touch: imba.Touch;
touchcancel: TouchEvent;
touchend: TouchEvent;
touchmove: TouchEvent;
touchstart: TouchEvent;
transitioncancel: TransitionEvent;
transitionend: TransitionEvent;
transitionrun: TransitionEvent;
transitionstart: TransitionEvent;
volumechange: Event;
waiting: Event;
wheel: WheelEvent;
[event: string]: CustomEvent;
} | the_stack |
import { IBundle, IStorages } from "@staticdeploy/core";
import { expect } from "chai";
import { omit } from "lodash";
function removeAssetsContent(bundle: IBundle): IBundle {
return {
...bundle,
assets: bundle.assets.map((asset) => omit(asset, "content")),
};
}
export default (storages: IStorages) => {
describe("BundlesStorage", () => {
it("create a bundle and verify that one bundle with its id exists", async () => {
await storages.bundles.createOne({
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
});
const bundleExists = await storages.bundles.oneExistsWithId("id");
expect(bundleExists).to.equal(true);
});
it("check if one bundle with a non-existing id exists and get false", async () => {
const bundleExists = await storages.bundles.oneExistsWithId("id");
expect(bundleExists).to.equal(false);
});
it("create a bundle and find it by id", async () => {
const bundle = {
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
};
await storages.bundles.createOne(bundle);
const foundBundle = await storages.bundles.findOne("id");
expect(foundBundle).to.deep.equal(removeAssetsContent(bundle));
});
it("try to find a bundle by a non-existing id and get null", async () => {
const notFoundBundle = await storages.bundles.findOne("id");
expect(notFoundBundle).to.equal(null);
});
it("create many bundles with the same name and tag, and find the latest by name and tag", async () => {
const base = {
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
};
const bundles = [
{ ...base, id: "id0", createdAt: new Date("1970-01-01") },
// id1 is the latest
{ ...base, id: "id1", createdAt: new Date("1970-01-03") },
{ ...base, id: "id2", createdAt: new Date("1970-01-02") },
];
for (const bundle of bundles) {
await storages.bundles.createOne(bundle);
}
const foundBundle = await storages.bundles.findLatestByNameAndTag(
"name",
"tag"
);
expect(foundBundle).to.have.property("id", "id1");
});
it("try to find a bundle by a non-existing name:tag combination and get null", async () => {
const notFoundBundle = await storages.bundles.findLatestByNameAndTag(
"name",
"tag"
);
expect(notFoundBundle).to.equal(null);
});
it("create a bundle and retrieve one of its assets by path", async () => {
await storages.bundles.createOne({
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [
{
path: "/file",
content: Buffer.from("content"),
mimeType: "text/plain",
headers: {},
},
],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
});
const content = await storages.bundles.getBundleAssetContent(
"id",
"/file"
);
expect(content).to.deep.equal(Buffer.from("content"));
});
describe("retrieve a non-existing bundle asset and get null", () => {
it("case: non-existing bundle", async () => {
const notFountContent = await storages.bundles.getBundleAssetContent(
"id",
"/file"
);
expect(notFountContent).to.equal(null);
});
it("case: existing bundle, non-existing asset", async () => {
await storages.bundles.createOne({
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
});
const notFountContent = await storages.bundles.getBundleAssetContent(
"id",
"/file"
);
expect(notFountContent).to.equal(null);
});
});
it("create a bundle and get it back with stripped properties when finding many", async () => {
const bundle = {
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
};
await storages.bundles.createOne(bundle);
const foundBundles = await storages.bundles.findMany();
expect(foundBundles).to.deep.equal([
omit(bundle, [
"assets",
"description",
"fallbackAssetPath",
"fallbackStatusCode",
"hash",
]),
]);
});
it("create a bundle and get it back when finding many by name and tag", async () => {
const bundle = {
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
};
await storages.bundles.createOne(bundle);
const foundBundles = await storages.bundles.findManyByNameAndTag(
"name",
"tag"
);
expect(foundBundles).to.deep.equal([removeAssetsContent(bundle)]);
});
it("create some bundles and get back their names when finding many names", async () => {
const base = {
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
};
const bundles = [
{ ...base, id: "id0", name: "name0" },
{ ...base, id: "id1", name: "name1" },
{ ...base, id: "id2", name: "name2" },
];
for (const bundle of bundles) {
await storages.bundles.createOne(bundle);
}
const foundNames = await storages.bundles.findManyNames();
expect(foundNames.sort()).to.deep.equal(
["name0", "name1", "name2"].sort()
);
});
it("create some bundles and get back their tags when finding many tags by name", async () => {
const base = {
name: "name",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
};
const bundles = [
{ ...base, id: "id0", tag: "tag0" },
{ ...base, id: "id1", tag: "tag1" },
{ ...base, id: "id2", tag: "tag2" },
];
for (const bundle of bundles) {
await storages.bundles.createOne(bundle);
}
const foundTags = await storages.bundles.findManyTagsByName("name");
expect(foundTags.sort()).to.deep.equal(
["tag0", "tag1", "tag2"].sort()
);
});
it("create a bundle and, finding it by id, get it back as expected (without assets contents)", async () => {
const bundle: IBundle = {
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [
{
path: "/file/0",
content: Buffer.from("/file/0"),
mimeType: "text/plain",
headers: {},
},
{
path: "/file/1",
content: Buffer.from("/file/1"),
mimeType: "text/plain",
headers: { key: "value" },
},
],
fallbackAssetPath: "/file/0",
fallbackStatusCode: 200,
createdAt: new Date(),
};
await storages.bundles.createOne(bundle as any);
const foundBundle = await storages.bundles.findOne("id");
// We leave storages the possibility to either not-set
// asset.content, or set it to undefined (the two things are
// functionally the same). Chai's deep equal considers not-set and
// undefined to be different, and since removeAssetsContent un-sets
// asset.content, this test would fail for implementations that set
// it to undefined. JSON stringification allows us to check for
// equality not caring for the not-set/undefined difference. We
// should employ this strategy for the other tests as well, but
// since this test is the only one that runs into this problem for
// now, we do it just here
expect(JSON.stringify(foundBundle)).to.equal(
JSON.stringify(removeAssetsContent(bundle))
);
});
it("create a bundle and retrieve its assets contents as expected", async () => {
const bundle = {
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [
{
path: "/file/0",
content: Buffer.from("/file/0"),
mimeType: "text/plain",
headers: {},
},
{
path: "/file/1",
content: Buffer.from("/file/1"),
mimeType: "text/plain",
headers: {},
},
],
fallbackAssetPath: "/file/0",
fallbackStatusCode: 200,
createdAt: new Date(),
};
await storages.bundles.createOne(bundle as any);
const file0Content = await storages.bundles.getBundleAssetContent(
"id",
"/file/0"
);
expect(file0Content).to.deep.equal(Buffer.from("/file/0"));
const file1Content = await storages.bundles.getBundleAssetContent(
"id",
"/file/1"
);
expect(file1Content).to.deep.equal(Buffer.from("/file/1"));
});
it("create a bundle, delete it by id-s, and verify it doesn't exist (anymore)", async () => {
await storages.bundles.createOne({
id: "id",
name: "name",
tag: "tag",
description: "description",
hash: "hash",
assets: [],
fallbackAssetPath: "/file",
fallbackStatusCode: 200,
createdAt: new Date(),
});
await storages.bundles.deleteMany(["id"]);
const bundleExists = await storages.bundles.oneExistsWithId("id");
expect(bundleExists).to.equal(false);
});
});
}; | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/environmentSettingsMappers";
import * as Parameters from "../models/parameters";
import { ManagedLabsClientContext } from "../managedLabsClientContext";
/** Class representing a EnvironmentSettings. */
export class EnvironmentSettings {
private readonly client: ManagedLabsClientContext;
/**
* Create a EnvironmentSettings.
* @param {ManagedLabsClientContext} client Reference to the service client.
*/
constructor(client: ManagedLabsClientContext) {
this.client = client;
}
/**
* List environment setting in a given lab.
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param [options] The optional parameters
* @returns Promise<Models.EnvironmentSettingsListResponse>
*/
list(resourceGroupName: string, labAccountName: string, labName: string, options?: Models.EnvironmentSettingsListOptionalParams): Promise<Models.EnvironmentSettingsListResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param callback The callback
*/
list(resourceGroupName: string, labAccountName: string, labName: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param options The optional parameters
* @param callback The callback
*/
list(resourceGroupName: string, labAccountName: string, labName: string, options: Models.EnvironmentSettingsListOptionalParams, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>): void;
list(resourceGroupName: string, labAccountName: string, labName: string, options?: Models.EnvironmentSettingsListOptionalParams | msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>): Promise<Models.EnvironmentSettingsListResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
labName,
options
},
listOperationSpec,
callback) as Promise<Models.EnvironmentSettingsListResponse>;
}
/**
* Get environment setting
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<Models.EnvironmentSettingsGetResponse>
*/
get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: Models.EnvironmentSettingsGetOptionalParams): Promise<Models.EnvironmentSettingsGetResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param callback The callback
*/
get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: msRest.ServiceCallback<Models.EnvironmentSetting>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: Models.EnvironmentSettingsGetOptionalParams, callback: msRest.ServiceCallback<Models.EnvironmentSetting>): void;
get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: Models.EnvironmentSettingsGetOptionalParams | msRest.ServiceCallback<Models.EnvironmentSetting>, callback?: msRest.ServiceCallback<Models.EnvironmentSetting>): Promise<Models.EnvironmentSettingsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
options
},
getOperationSpec,
callback) as Promise<Models.EnvironmentSettingsGetResponse>;
}
/**
* Create or replace an existing Environment Setting. This operation can take a while to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param environmentSetting Represents settings of an environment, from which environment
* instances would be created
* @param [options] The optional parameters
* @returns Promise<Models.EnvironmentSettingsCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: Models.EnvironmentSetting, options?: msRest.RequestOptionsBase): Promise<Models.EnvironmentSettingsCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(resourceGroupName,labAccountName,labName,environmentSettingName,environmentSetting,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.EnvironmentSettingsCreateOrUpdateResponse>;
}
/**
* Delete environment setting. This operation can take a while to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,labAccountName,labName,environmentSettingName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Modify properties of environment setting.
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param environmentSetting Represents settings of an environment, from which environment
* instances would be created
* @param [options] The optional parameters
* @returns Promise<Models.EnvironmentSettingsUpdateResponse>
*/
update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: Models.EnvironmentSettingFragment, options?: msRest.RequestOptionsBase): Promise<Models.EnvironmentSettingsUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param environmentSetting Represents settings of an environment, from which environment
* instances would be created
* @param callback The callback
*/
update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: Models.EnvironmentSettingFragment, callback: msRest.ServiceCallback<Models.EnvironmentSetting>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param environmentSetting Represents settings of an environment, from which environment
* instances would be created
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: Models.EnvironmentSettingFragment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EnvironmentSetting>): void;
update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: Models.EnvironmentSettingFragment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EnvironmentSetting>, callback?: msRest.ServiceCallback<Models.EnvironmentSetting>): Promise<Models.EnvironmentSettingsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
environmentSetting,
options
},
updateOperationSpec,
callback) as Promise<Models.EnvironmentSettingsUpdateResponse>;
}
/**
* Claims a random environment for a user in an environment settings
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
claimAny(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param callback The callback
*/
claimAny(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param options The optional parameters
* @param callback The callback
*/
claimAny(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
claimAny(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
options
},
claimAnyOperationSpec,
callback);
}
/**
* Provisions/deprovisions required resources for an environment setting based on current state of
* the lab/environment setting.
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param publishPayload Payload for Publish operation on EnvironmentSetting.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
publish(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: Models.PublishPayload, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param publishPayload Payload for Publish operation on EnvironmentSetting.
* @param callback The callback
*/
publish(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: Models.PublishPayload, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param publishPayload Payload for Publish operation on EnvironmentSetting.
* @param options The optional parameters
* @param callback The callback
*/
publish(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: Models.PublishPayload, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
publish(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: Models.PublishPayload, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
publishPayload,
options
},
publishOperationSpec,
callback);
}
/**
* Starts a template by starting all resources inside the template. This operation can take a while
* to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginStart(resourceGroupName,labAccountName,labName,environmentSettingName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Starts a template by starting all resources inside the template. This operation can take a while
* to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginStop(resourceGroupName,labAccountName,labName,environmentSettingName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Create or replace an existing Environment Setting. This operation can take a while to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param environmentSetting Represents settings of an environment, from which environment
* instances would be created
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: Models.EnvironmentSetting, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
environmentSetting,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Delete environment setting. This operation can take a while to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Starts a template by starting all resources inside the template. This operation can take a while
* to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
options
},
beginStartOperationSpec,
options);
}
/**
* Starts a template by starting all resources inside the template. This operation can take a while
* to complete
* @param resourceGroupName The name of the resource group.
* @param labAccountName The name of the lab Account.
* @param labName The name of the lab.
* @param environmentSettingName The name of the environment Setting.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
labAccountName,
labName,
environmentSettingName,
options
},
beginStopOperationSpec,
options);
}
/**
* List environment setting in a given lab.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.EnvironmentSettingsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.EnvironmentSettingsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironmentSetting>): Promise<Models.EnvironmentSettingsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.EnvironmentSettingsListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName
],
queryParameters: [
Parameters.expand,
Parameters.filter,
Parameters.top,
Parameters.orderby,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ResponseWithContinuationEnvironmentSetting
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.expand,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.EnvironmentSetting
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "environmentSetting",
mapper: {
...Mappers.EnvironmentSettingFragment,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.EnvironmentSetting
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const claimAnyOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/claimAny",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const publishOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/publish",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "publishPayload",
mapper: {
...Mappers.PublishPayload,
required: true
}
},
responses: {
200: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "environmentSetting",
mapper: {
...Mappers.EnvironmentSetting,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.EnvironmentSetting
},
201: {
bodyMapper: Mappers.EnvironmentSetting
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginStartOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/start",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginStopOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/stop",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labAccountName,
Parameters.labName,
Parameters.environmentSettingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ResponseWithContinuationEnvironmentSetting
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import {Mutable, Class, Equals, Values, Domain, Range, AnyTiming, LinearRange, ContinuousScale} from "@swim/util";
import {Affinity, MemberFastenerClass, Property, Animator} from "@swim/component";
import {BTree} from "@swim/collections";
import type {R2Box} from "@swim/math";
import {AnyFont, Font, AnyColor, Color} from "@swim/style";
import {ThemeAnimator} from "@swim/theme";
import {ViewContextType, ViewFlags, AnyView, ViewCreator, View, ViewSet} from "@swim/view";
import {GraphicsView, CanvasContext, CanvasRenderer} from "@swim/graphics";
import type {DataPointCategory} from "../data/DataPoint";
import {AnyDataPointView, DataPointView} from "../data/DataPointView";
import {ContinuousScaleAnimator} from "../scaled/ContinuousScaleAnimator";
import type {PlotViewInit, PlotViewDataPointExt, PlotView} from "./PlotView";
import type {SeriesPlotViewObserver} from "./SeriesPlotViewObserver";
/** @public */
export type SeriesPlotHitMode = "domain" | "plot" | "data" | "none";
/** @public */
export type AnySeriesPlotView<X = unknown, Y = unknown> = SeriesPlotView<X, Y> | SeriesPlotViewInit<X, Y>;
/** @public */
export interface SeriesPlotViewInit<X = unknown, Y = unknown> extends PlotViewInit<X, Y> {
hitMode?: SeriesPlotHitMode;
}
/** @public */
export abstract class SeriesPlotView<X = unknown, Y = unknown> extends GraphicsView implements PlotView<X, Y> {
constructor() {
super();
this.xDataDomain = null;
this.yDataDomain = null;
this.xDataRange = null;
this.yDataRange = null;
this.gradientStops = 0;
this.dataPointViews = new BTree();
}
override readonly observerType?: Class<SeriesPlotViewObserver<X, Y>>;
@ThemeAnimator({type: Font, value: null, inherits: true})
readonly font!: ThemeAnimator<this, Font | null, AnyFont | null>;
@ThemeAnimator({type: Color, value: null, inherits: true})
readonly textColor!: ThemeAnimator<this, Color | null, AnyColor | null>;
@Property({type: String, value: "domain"})
readonly hitMode!: Property<this, SeriesPlotHitMode>;
@Animator<SeriesPlotView<X, Y>, ContinuousScale<X, number> | null>({
extends: ContinuousScaleAnimator,
type: ContinuousScale,
inherits: true,
value: null,
updateFlags: View.NeedsLayout,
willSetValue(newXScale: ContinuousScale<X, number> | null, oldXScale: ContinuousScale<X, number> | null): void {
this.owner.callObservers("viewWillSetXScale", newXScale, oldXScale, this.owner);
},
didSetValue(newXScale: ContinuousScale<X, number> | null, oldXScale: ContinuousScale<X, number> | null): void {
this.owner.updateXDataRange();
this.owner.callObservers("viewDidSetXScale", newXScale, oldXScale, this.owner);
},
})
readonly xScale!: ContinuousScaleAnimator<this, X, number>;
@Animator<SeriesPlotView<X, Y>, ContinuousScale<Y, number> | null>({
extends: ContinuousScaleAnimator,
type: ContinuousScale,
inherits: true,
value: null,
updateFlags: View.NeedsLayout,
willSetValue(newYScale: ContinuousScale<Y, number> | null, oldYScale: ContinuousScale<Y, number> | null): void {
this.owner.callObservers("viewWillSetYScale", newYScale, oldYScale, this.owner);
},
didSetValue(newYScale: ContinuousScale<Y, number> | null, oldYScale: ContinuousScale<Y, number> | null): void {
this.owner.updateYDataRange();
this.owner.callObservers("viewDidSetYScale", newYScale, oldYScale, this.owner);
},
})
readonly yScale!: ContinuousScaleAnimator<this, Y, number>;
xDomain(): Domain<X> | null;
xDomain(xDomain: Domain<X> | string | null, timing?: AnyTiming | boolean): this;
xDomain(xMin: X, xMax: X, timing: AnyTiming | boolean): this;
xDomain(xMin?: Domain<X> | X | string | null, xMax?: X | AnyTiming | boolean,
timing?: AnyTiming | boolean): Domain<X> | null | this {
if (arguments.length === 0) {
const xScale = this.xScale.value;
return xScale !== null ? xScale.domain : null;
} else {
this.xScale.setDomain(xMin as any, xMax as any, timing);
return this;
}
}
yDomain(): Domain<Y> | null;
yDomain(yDomain: Domain<Y> | string | null, timing?: AnyTiming | boolean): this;
yDomain(yMin: Y, yMax: Y, timing: AnyTiming | boolean): this;
yDomain(yMin?: Domain<Y> | Y | string | null, yMax?: Y | AnyTiming | boolean,
timing?: AnyTiming | boolean): Domain<Y> | null | this {
if (arguments.length === 0) {
const yScale = this.yScale.value;
return yScale !== null ? yScale.domain : null;
} else {
this.yScale.setDomain(yMin as any, yMax as any, timing);
return this;
}
}
xRange(): Range<number> | null {
const xScale = this.xScale.value;
return xScale !== null ? xScale.range : null;
}
yRange(): Range<number> | null {
const yScale = this.yScale.value;
return yScale !== null ? yScale.range : null;
}
@Property<SeriesPlotView<X, Y>, readonly [number, number]>({
initValue(): readonly [number, number] {
return [0, 0];
},
willSetValue(newXRangePadding: readonly [number, number], oldXRangePadding: readonly [number, number]): void {
this.owner.callObservers("viewWillSetXRangePadding", newXRangePadding, oldXRangePadding, this.owner);
},
didSetValue(newXRangePadding: readonly [number, number], oldXRangePadding: readonly [number, number]): void {
this.owner.callObservers("viewDidSetXRangePadding", newXRangePadding, oldXRangePadding, this.owner);
},
})
readonly xRangePadding!: Property<this, readonly [number, number]>
@Property<SeriesPlotView<X, Y>, readonly [number, number]>({
initValue(): readonly [number, number] {
return [0, 0];
},
willSetValue(newYRangePadding: readonly [number, number], oldYRangePadding: readonly [number, number]): void {
this.owner.callObservers("viewWillSetYRangePadding", newYRangePadding, oldYRangePadding, this.owner);
},
didSetValue(newYRangePadding: readonly [number, number], oldYRangePadding: readonly [number, number]): void {
this.owner.callObservers("viewDidSetYRangePadding", newYRangePadding, oldYRangePadding, this.owner);
},
})
readonly yRangePadding!: Property<this, readonly [number, number]>
readonly xDataDomain: Domain<X> | null;
protected setXDataDomain(newXDataDomain: Domain<X> | null): void {
const oldXDataDomain = this.xDataDomain;
if (!Equals(newXDataDomain, oldXDataDomain)) {
this.willSetXDataDomain(newXDataDomain, oldXDataDomain);
(this as Mutable<this>).xDataDomain = newXDataDomain;
this.onSetXDataDomain(newXDataDomain, oldXDataDomain);
this.didSetXDataDomain(newXDataDomain, oldXDataDomain);
}
}
protected willSetXDataDomain(newXDataDomain: Domain<X> | null, oldXDataDomain: Domain<X> | null): void {
this.callObservers("viewWillSetXDataDomain", newXDataDomain, oldXDataDomain, this);
}
protected onSetXDataDomain(newXDataDomain: Domain<X> | null, oldXDataDomain: Domain<X> | null): void {
this.updateXDataRange();
this.requireUpdate(View.NeedsLayout);
}
protected didSetXDataDomain(newXDataDomain: Domain<X> | null, oldXDataDomain: Domain<X> | null): void {
this.callObservers("viewDidSetXDataDomain", newXDataDomain, oldXDataDomain, this);
}
protected updateXDataDomain(dataPointView: DataPointView<X, Y>): void {
const dataPointViews = this.dataPointViews;
const xMin = dataPointViews.firstKey();
const xMax = dataPointViews.lastKey();
let xDataDomain: Domain<X> | null;
if (xMin !== void 0 && xMax !== void 0) {
xDataDomain = Domain<X>(xMin, xMax);
} else {
const x = dataPointView.x.getValue();
xDataDomain = Domain<X>(x, x);
}
this.setXDataDomain(xDataDomain);
}
readonly yDataDomain: Domain<Y> | null;
protected setYDataDomain(newYDataDomain: Domain<Y> | null): void {
const oldYDataDomain = this.yDataDomain;
if (!Equals(newYDataDomain, oldYDataDomain)) {
this.willSetYDataDomain(newYDataDomain, oldYDataDomain);
(this as Mutable<this>).yDataDomain = newYDataDomain;
this.onSetYDataDomain(newYDataDomain, oldYDataDomain);
this.didSetYDataDomain(newYDataDomain, oldYDataDomain);
}
}
protected willSetYDataDomain(newYDataDomain: Domain<Y> | null, oldYDataDomain: Domain<Y> | null): void {
this.callObservers("viewWillSetYDataDomain", newYDataDomain, oldYDataDomain, this);
}
protected onSetYDataDomain(newYDataDomain: Domain<Y> | null, oldYDataDomain: Domain<Y> | null): void {
this.updateYDataRange();
this.requireUpdate(View.NeedsLayout);
}
protected didSetYDataDomain(newYDataDomain: Domain<Y> | null, oldYDataDomain: Domain<Y> | null): void {
this.callObservers("viewDidSetYDataDomain", newYDataDomain, oldYDataDomain, this);
}
protected updateYDataDomain(dataPointView: DataPointView<X, Y>): void {
const y = dataPointView.y.value;
const y2 = dataPointView.y2.value;
let yDataDomain = this.yDataDomain;
if (yDataDomain === null) {
yDataDomain = Domain(y, y);
} else {
if (Values.compare(y, yDataDomain[0]) < 0) {
yDataDomain = Domain(y, yDataDomain[1]);
} else if (Values.compare(yDataDomain[1], y) < 0) {
yDataDomain = Domain(yDataDomain[0], y);
}
if (y2 !== void 0) {
if (Values.compare(y2, yDataDomain[0]) < 0) {
yDataDomain = Domain(y2, yDataDomain[1]);
} else if (Values.compare(yDataDomain[1], y2) < 0) {
yDataDomain = Domain(yDataDomain[0], y2);
}
}
}
this.setYDataDomain(yDataDomain);
}
readonly xDataRange: Range<number> | null;
protected setXDataRange(xDataRange: Range<number> | null): void {
(this as Mutable<this>).xDataRange = xDataRange;
}
protected updateXDataRange(): void {
const xDataDomain = this.xDataDomain;
if (xDataDomain !== null) {
const xScale = this.xScale.value;
if (xScale !== null) {
this.setXDataRange(LinearRange(xScale(xDataDomain[0]), xScale(xDataDomain[1])));
} else {
this.setXDataRange(null);
}
}
}
readonly yDataRange: Range<number> | null;
protected setYDataRange(yDataRange: Range<number> | null): void {
(this as Mutable<this>).yDataRange = yDataRange;
}
protected updateYDataRange(): void {
const yDataDomain = this.yDataDomain;
if (yDataDomain !== null) {
const yScale = this.yScale.value;
if (yScale !== null) {
this.setYDataRange(LinearRange(yScale(yDataDomain[0]), yScale(yDataDomain[1])));
} else {
this.setYDataRange(null);
}
}
}
/** @internal */
readonly gradientStops: number;
@ViewSet<SeriesPlotView<X, Y>, DataPointView<X, Y>, PlotViewDataPointExt<X, Y>>({
implements: true,
type: DataPointView,
binds: true,
observes: true,
willAttachView(dataPointView: DataPointView<X, Y>, targetView: View | null): void {
this.owner.callObservers("viewWillAttachDataPoint", dataPointView, targetView, this.owner);
},
didAttachView(dataPointView: DataPointView<X, Y>): void {
if (this.owner.dataPointViews.get(dataPointView.x.state!) === void 0) {
this.owner.dataPointViews.set(dataPointView.x.state!, dataPointView);
}
this.owner.updateXDataDomain(dataPointView);
this.owner.updateYDataDomain(dataPointView);
const labelView = dataPointView.label.view;
if (labelView !== null) {
this.attachDataPointLabelView(labelView);
}
},
willDetachView(dataPointView: DataPointView<X, Y>): void {
if (this.owner.dataPointViews.get(dataPointView.x.state!) === dataPointView) {
this.owner.dataPointViews.delete(dataPointView.x.state!);
}
const labelView = dataPointView.label.view;
if (labelView !== null) {
this.detachDataPointLabelView(labelView);
}
this.owner.updateXDataDomain(dataPointView);
// yDataDomain will be recomputed next layout pass
},
didDetachView(dataPointView: DataPointView<X, Y>): void {
this.owner.callObservers("viewDidDetachDataPoint", dataPointView, this.owner);
},
viewDidSetDataPointX(newX: X | undefined, oldX: X | undefined, dataPointView: DataPointView<X, Y>): void {
this.owner.updateXDataDomain(dataPointView);
this.owner.requireUpdate(View.NeedsLayout);
},
viewDidSetDataPointY(newY: Y | undefined, oldY: Y | undefined, dataPointView: DataPointView<X, Y>): void {
this.owner.updateYDataDomain(dataPointView);
this.owner.requireUpdate(View.NeedsLayout);
},
viewDidSetDataPointY2(newY2: Y | undefined, oldY2: Y | undefined, dataPointView: DataPointView<X, Y>): void {
this.owner.updateYDataDomain(dataPointView);
this.owner.requireUpdate(View.NeedsLayout);
},
viewWillAttachDataPointLabel(labelView: GraphicsView): void {
this.attachDataPointLabelView(labelView);
},
viewDidDetachDataPointLabel(labelView: GraphicsView): void {
this.detachDataPointLabelView(labelView);
},
attachDataPointLabelView(labelView: GraphicsView): void {
this.owner.requireUpdate(View.NeedsLayout);
},
detachDataPointLabelView(labelView: GraphicsView): void {
// hook
},
})
readonly dataPoints!: ViewSet<this, DataPointView<X, Y>>;
static readonly dataPoints: MemberFastenerClass<SeriesPlotView, "dataPoints">;
/** @internal */
readonly dataPointViews: BTree<X, DataPointView<X, Y>>;
getDataPoint(x: X): DataPointView<X, Y> | null {
const dataPoint = this.dataPointViews.get(x);
return dataPoint !== void 0 ? dataPoint : null;
}
insertDataPoint(dataPointView: AnyDataPointView<X, Y>): DataPointView<X, Y> {
return this.insertChild(DataPointView.fromAny(dataPointView), null);
}
insertDataPoints(...dataPointViews: AnyDataPointView<X, Y>[]): void {
for (let i = 0, n = dataPointViews.length; i < n; i += 1) {
this.insertDataPoint(dataPointViews[i]!);
}
}
removeDataPoint(x: X): DataPointView<X, Y> | null {
const dataPointView = this.getDataPoint(x);
if (dataPointView !== null) {
this.removeChild(dataPointView);
}
return dataPointView;
}
override setChild<V extends View>(key: string, newChild: V): View | null;
override setChild<F extends ViewCreator<F>>(key: string, factory: F): View | null;
override setChild(key: string, newChild: AnyView | null): View | null;
override setChild(key: string, newChild: AnyView | null): View | null {
if (newChild !== null) {
newChild = View.fromAny(newChild);
}
if (newChild instanceof DataPointView) {
const target = this.dataPointViews.nextValue(newChild.x.state) ?? null;
const oldView = this.getChild(key);
super.insertChild(newChild, target, key);
return oldView;
} else {
return super.setChild(key, newChild) as View | null;
}
}
override appendChild<V extends View>(child: V, key?: string): V;
override appendChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>;
override appendChild(child: AnyView, key?: string): View;
override appendChild(child: AnyView, key?: string): View {
child = View.fromAny(child);
if (child instanceof DataPointView) {
const target = this.dataPointViews.nextValue(child.x.state) ?? null;
return super.insertChild(child, target, key);
} else {
return super.appendChild(child, key);
}
}
override prependChild<V extends View>(child: V, key?: string): V;
override prependChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>;
override prependChild(child: AnyView, key?: string): View;
override prependChild(child: AnyView, key?: string): View {
child = View.fromAny(child);
if (child instanceof DataPointView) {
const target = this.dataPointViews.nextValue(child.x.state) ?? null;
return super.insertChild(child, target, key);
} else {
return super.prependChild(child, key);
}
}
override insertChild<V extends View>(child: V, target: View | null, key?: string): V;
override insertChild<F extends ViewCreator<F>>(factory: F, target: View | null, key?: string): InstanceType<F>;
override insertChild(child: AnyView, target: View | null, key?: string): View;
override insertChild(child: AnyView, target: View | null, key?: string): View {
child = View.fromAny(child);
if (child instanceof DataPointView && target === null) {
target = this.dataPointViews.nextValue(child.x.state) ?? null;
}
return super.insertChild(child, target, key);
}
protected override onLayout(viewContext: ViewContextType<this>): void {
super.onLayout(viewContext);
this.xScale.recohere(viewContext.updateTime);
this.yScale.recohere(viewContext.updateTime);
this.resizeScales(this.viewFrame);
}
/**
* Updates own scale ranges to project onto view frame.
*/
protected resizeScales(frame: R2Box): void {
const xScale = !this.xScale.inherited ? this.xScale.value : null;
if (xScale !== null && xScale.range[1] !== frame.width) {
this.xScale.setRange(0, frame.width);
}
const yScale = !this.yScale.inherited ? this.yScale.value : null;
if (yScale !== null && yScale.range[1] !== frame.height) {
this.yScale.setRange(0, frame.height);
}
}
protected override displayChildren(displayFlags: ViewFlags, viewContext: ViewContextType<this>,
displayChild: (this: this, child: View, displayFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
let xScale: ContinuousScale<X, number> | null;
let yScale: ContinuousScale<Y, number> | null;
if ((displayFlags & View.NeedsLayout) !== 0 &&
(xScale = this.xScale.value, xScale !== null) &&
(yScale = this.yScale.value, yScale !== null)) {
this.layoutChildViews(xScale, yScale, displayFlags, viewContext, displayChild);
} else {
super.displayChildren(displayFlags, viewContext, displayChild);
}
}
protected layoutChildViews(xScale: ContinuousScale<X, number>,
yScale: ContinuousScale<Y, number>,
displayFlags: ViewFlags, viewContext: ViewContextType<this>,
displayChild: (this: this, child: View, displayFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
// Recompute extrema when laying out child views.
const frame = this.viewFrame;
let xDataDomainMin: X | undefined;
let xDataDomainMax: X | undefined;
let yDataDomainMin: Y | undefined;
let yDataDomainMax: Y | undefined;
let gradientStops = 0;
let point0 = null as DataPointView<X, Y> | null;
let point1 = null as DataPointView<X, Y> | null;
let y0: Y | undefined;
let y1: Y | undefined;
type self = this;
function layoutChildView(this: self, child: View, displayFlags: ViewFlags,
viewContext: ViewContextType<self>): void {
const point2 = child as DataPointView<X, Y>;
const x2 = point2.x.getValue();
const y2 = point2.y.getValue();
const dy2 = point2.y2.value;
const sx2 = xScale(x2);
const sy2 = yScale(y2);
point2.setXCoord(frame.xMin + sx2);
point2.setYCoord(frame.yMin + sy2);
const sdy2 = dy2 !== void 0 ? yScale(dy2) : void 0;
if (sdy2 !== void 0) {
point2.setY2Coord(frame.yMin + sdy2);
} else if (point2.y2Coord !== void 0) {
point2.setY2Coord(void 0);
}
if (point2.isGradientStop()) {
gradientStops += 1;
}
if (point1 !== null) {
let category: DataPointCategory;
if (point0 !== null) {
// categorize mid point
if (Values.compare(y0!, y1!) < 0 && Values.compare(y2, y1!) < 0) {
category = "maxima";
} else if (Values.compare(y1!, y0!) < 0 && Values.compare(y1!, y2) < 0) {
category = "minima";
} else if (Values.compare(y0!, y1!) < 0 && Values.compare(y1!, y2) < 0) {
category = "increasing";
} else if (Values.compare(y1!, y0!) < 0 && Values.compare(y2, y1!) < 0) {
category = "decreasing";
} else {
category = "flat";
}
} else {
// categorize start point
if (Values.compare(y1!, y2) < 0) {
category = "increasing";
} else if (Values.compare(y2, y1!) < 0) {
category = "decreasing";
} else {
category = "flat";
}
}
point1.category.setValue(category, Affinity.Intrinsic);
// update extrema
if (Values.compare(y2, yDataDomainMin) < 0) {
yDataDomainMin = y2;
} else if (Values.compare(yDataDomainMax, y2) < 0) {
yDataDomainMax = y2;
}
if (dy2 !== void 0) {
if (Values.compare(dy2, yDataDomainMin) < 0) {
yDataDomainMin = dy2;
} else if (Values.compare(yDataDomainMax, dy2) < 0) {
yDataDomainMax = dy2;
}
}
} else {
xDataDomainMin = x2;
xDataDomainMax = x2;
yDataDomainMin = y2;
yDataDomainMax = y2;
}
point0 = point1;
point1 = point2;
y0 = y1;
y1 = y2;
xDataDomainMax = x2;
displayChild.call(this, child, displayFlags, viewContext);
}
super.displayChildren(displayFlags, viewContext, layoutChildView);
if (point1 !== null) {
let category: DataPointCategory;
if (point0 !== null) {
// categorize end point
if (Values.compare(y0!, y1!) < 0) {
category = "increasing";
} else if (Values.compare(y1!, y0!) < 0) {
category = "decreasing";
} else {
category = "flat";
}
} else {
// categorize sole point
category = "flat";
}
point1.category.setValue(category, Affinity.Intrinsic);
}
this.setXDataDomain(point0 !== null ? Domain<X>(xDataDomainMin!, xDataDomainMax!) : null);
this.setYDataDomain(point0 !== null ? Domain<Y>(yDataDomainMin!, yDataDomainMax!) : null);
(this as Mutable<this>).gradientStops = gradientStops;
}
protected override didRender(viewContext: ViewContextType<this>): void {
const renderer = viewContext.renderer;
if (renderer instanceof CanvasRenderer && !this.hidden && !this.culled) {
this.renderPlot(renderer.context, this.viewFrame);
}
super.didRender(viewContext);
}
protected abstract renderPlot(context: CanvasContext, frame: R2Box): void;
protected override hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
const hitMode = this.hitMode.value;
if (hitMode !== "none") {
const renderer = viewContext.renderer;
if (renderer instanceof CanvasRenderer) {
let hit: GraphicsView | null;
if (hitMode === "domain") {
const viewFrame = this.viewFrame;
hit = this.hitTestDomain(x - viewFrame.x, y - viewFrame.y, renderer);
} else {
hit = this.hitTestPlot(x, y, renderer);
}
return hit;
}
}
return null;
}
protected override hitTestChildren(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
return null;
}
protected hitTestDomain(x: number, y: number, renderer: CanvasRenderer): GraphicsView | null {
const xScale = this.xScale.value;
if (xScale !== null) {
const d = xScale.inverse(x);
const v0 = this.dataPointViews.previousValue(d);
const v1 = this.dataPointViews.nextValue(d);
const x0 = v0 !== void 0 ? v0.x.value : void 0;
const x1 = v1 !== void 0 ? v1.x.value : void 0;
const dx0 = x0 !== void 0 ? +d - +x0 : NaN;
const dx1 = x1 !== void 0 ? +x1 - +d : NaN;
if (dx0 <= dx1) {
return v0!;
} else if (dx0 > dx1) {
return v1!;
} else if (v0 !== void 0) {
return v0;
} else if (v1 !== void 0) {
return v1;
}
}
return null;
}
protected abstract hitTestPlot(x: number, y: number, renderer: CanvasRenderer): GraphicsView | null;
override init(init: SeriesPlotViewInit<X, Y>): void {
super.init(init);
if (init.xScale !== void 0) {
this.xScale(init.xScale);
}
if (init.yScale !== void 0) {
this.yScale(init.yScale);
}
const data = init.data;
if (data !== void 0) {
this.insertDataPoints(...data);
}
if (init.font !== void 0) {
this.font(init.font);
}
if (init.textColor !== void 0) {
this.textColor(init.textColor);
}
if (init.hitMode !== void 0) {
this.hitMode(init.hitMode);
}
}
} | the_stack |
import * as d3 from "d3";
import {WordLine} from "../vis/WordLine";
import {AttentionVis} from "../vis/AttentionVis";
import {BarList} from "../vis/BarList";
import {StateVis} from "../vis/StateVis";
import {CloseWordList} from "../vis/CloseWordList";
import {WordProjector} from "../vis/WordProjector";
import {SimpleEventHandler} from "../etc/SimpleEventHandler";
import {D3Sel} from "../etc/LocalTypes";
import * as _ from "lodash";
import {StateProjector} from "../vis/StateProjector";
import {StatePictograms} from "../vis/StatePictograms";
import {BeamTreeVis} from "../vis/BeamTree";
import {InfoPanel} from "../vis/InfoPanel";
type VisColumn<DW=WordLine> = {
// encoder_extra: VComponent<any>[],
sideIndicator: D3Sel,
// encoder_states: NeighborStates,
encoder_words: WordLine,
attention: AttentionVis,
decoder_words: DW,
beam: DW,
// context: NeighborStates,
// decoder_states: NeighborStates,
// decoder_extra: VComponent<any>[],
selection: D3Sel
}
function initPanel<T=WordLine>(select): VisColumn<T> {
return {
sideIndicator:null,
selection: select,
// encoder_extra: [],
// encoder_states: null,
encoder_words: null,
attention: null,
decoder_words: null,
beam: null,
// context: null,
// decoder_states: null,
// decoder_extra: []
}
};
export class PanelManager {
private _current = {
topN: <number> 0,
hideStates: <boolean> false,
box_width: <number> 40,
wordProjector: <WordProjector> null,
closeWordsList: <CloseWordList> null,
hasMediumPanel: <boolean> false,
infoPanel: <InfoPanel>null,
};
panels = {
projectorSelect: this._createProjectorOptions(),
projectorPanel: d3.select('#projectorPanel'),
loadProjectButton: d3.select('#loadProject'),
loadProjectSpinner: d3.select('#lPspinner'),
enterComparison: {
dialog: d3.select('#comparisonDialog'),
btn: d3.select('#comparison_btn'),
enc: d3.select('#compare_enc'),
encBtn: d3.select('#cmp_translate'),
dec: d3.select('#compare_dec'),
decBtn: d3.select('#cmp_partial'),
},
swapBtn: d3.select('#make_pivot_btn'),
wordMode:{
wordBtn: d3.select('#word_vector_fix_btn'),
attnBtn: d3.select('#attn_fix_btn'),
attnApplyBtn: d3.select('#apply_attn')
},
statePictoPanel: d3.select('#statePictos')
};
private _vis = {
zero: <VisColumn<BarList>> initPanel(d3.select('.col0')),
left: initPanel(d3.select('.col1')),
middle: initPanel(d3.select('.col3')),
right: initPanel(d3.select('.col5')),
middle_extra: <VisColumn<BarList>> initPanel(d3.select('.col2')),
right_extra: initPanel(d3.select('.col4')),
projectors: this._createProjectorPanel(),
statePicto: <StatePictograms> null, // initialized in init.. requires projectors
beamView: this._createBeamViewPanel()
};
get vis() {
return this._vis;
}
constructor(private eventHandler: SimpleEventHandler) {
this.init();
}
init() {
this.buildFullStack(this._vis.left);
this._vis.statePicto = this._createStatePictoPanel();
// Zero
this.buildDecorators(this._vis.zero);
}
_createStatePictoPanel() {
return new StatePictograms(d3.select('#statePictos'),
this._vis.projectors, this.eventHandler)
}
_createBeamViewPanel() {
const parent = d3.select('#beam-view').append('svg').attrs({
width: 1000,
height: 150
});
return new BeamTreeVis(parent, this.eventHandler, {
width: 1000,
height: 150
})
}
_createProjectorPanel() {
const parent = d3.select('#projectorPanel').append('svg').attrs({
width: 500,
height: 30
});
const sp = new StateProjector(parent, this.eventHandler, {});
sp.setHideElement(this.panels.projectorPanel);
return sp;
}
public getMediumPanel() {
if (!this._current.hasMediumPanel) {
this.buildFullStack(this._vis.middle);
// this.buildDecorators(this._vis.middle_extra);
this._current.hasMediumPanel = true;
}
return {main: this._vis.middle, extra: this._vis.middle_extra};
}
public removeMediumPanel() {
if (this._current.hasMediumPanel) {
//todo: check if this works...
this._vis.middle_extra.selection.selectAll("*").remove();
this._vis.middle_extra = initPanel(this._vis.middle_extra.selection);
this._vis.middle.selection.selectAll("*").remove();
this._vis.middle = initPanel(this._vis.middle.selection);
this._current.hasMediumPanel = false;
}
}
private buildDecorators(visColumn: VisColumn<BarList>) {
// visColumn.encoder_extra.push(PanelManager._setupPanel({
// col: visColumn.selection,
// className: "encoder_states_setup",
// addSVG: false,
// title: 'Enc states: ',
// divStyles: {height: '100px', width: '100px', 'padding-top': '5px'}
// }));
// visColumn.encoder_states = PanelManager._setupPanel({
// col: visColumn.selection,
// className: "encoder_states_setup",
// addSVG: false,
// title: 'Enc states: ',
// divStyles: {height: '21px', width: '100px', 'padding-top': '0px'}
// })
visColumn.encoder_words = PanelManager._setupPanel({
col: visColumn.selection,
className: "encoder_words_setup",
addSVG: false,
title: 'Enc words: ',
divStyles: {height: '21px', width: '100px', 'padding-top': '5px'}
})
visColumn.attention = PanelManager._setupPanel({
col: visColumn.selection,
className: "attn_setup",
addSVG: false,
title: 'Attention: ',
divStyles: {height: '50px', width: '100px'}
})
// noinspection JSUnresolvedVariable
visColumn.decoder_words = this._createScoreVis({
col: visColumn.selection,
className: "decoder_words_setup",
divStyles: {
height: '21px',
width: '100px',
'padding-bottom': '5px'
},
options: {
bar_height: 20,
data_access: d => [d.scores[this._current.topN]],
data_access_all: d => d.scores
}
})
visColumn.beam = PanelManager._setupPanel({
col: visColumn.selection,
className: "beam_states_setup",
addSVG: false,
title: 'topK: ',
divStyles: {height: '120px', width: '100px', 'padding-top': '0px'}
})
// visColumn.encoder_states = PanelManager._setupPanel({
// col: visColumn.selection,
// className: "decoder_states_setup",
// addSVG: false,
// title: 'Dec states: ',
// divStyles: {height: '21px', width: '100px', 'padding-top': '0px'}
// })
// visColumn.context = PanelManager._setupPanel({
// col: visColumn.selection,
// className: "context_setup",
// addSVG: false,
// title: 'Context states: ',
// divStyles: {height: '21px', width: '100px', 'padding-top': '5px'}
// })
// visColumn.decoder_extra.push(PanelManager._setupPanel({
// col: visColumn.selection,
// className: "decoder_states_setup",
// addSVG: false,
// title: 'Dec states: ',
// divStyles: {
// height: '100px',
// width: '100px',
// 'padding-bottom': '5px'
// }
// }))
//
// visColumn.decoder_extra.push(this._createScoreVis({
// col: visColumn.selection,
// className: "decoder_words_setup",
// divStyles: {width: '100px', 'padding-top': '5px'},
// options: {
// bar_height: 23,
// data_access: d => d.scores.filter((_, i) => i !== this._current.topN),
// data_access_all: null
// }
// }))
}
private buildFullStack(visColumn: VisColumn) {
// visColumn.encoder_extra.push(this._createStatesVis({
// col: visColumn.selection,
// className: 'states_encoder',
// divStyles: {'padding-top': '5px'},
// options: {
// data_access: d => d.encoder.map(e => _.isArray(e.state) ? e.state : []),// TODO: fix hack !!!
// hidden: this._current.hideStates,
// height: 100,
// cell_width: this._current.box_width
// }
// }));
// visColumn.encoder_states = this._createNeighborStates({
// col: visColumn.selection,
// className: 'encoder_state_neighbors',
// options: {
// box_width: this._current.box_width
// }
// });
visColumn.encoder_words = this._createWordLine({
col: visColumn.selection,
className: 'encoder_words',
divStyles: {'padding-top': '5px'},
options: {
box_type: this._current.hideStates ? WordLine.BoxType.flow : WordLine.BoxType.fixed,
box_width: this._current.box_width
}
});
visColumn.attention = this._createAttention({
col: visColumn.selection,
className: 'attn_vis',
options: {}
});
visColumn.decoder_words = this._createWordLine({
col: visColumn.selection,
className: 'decoder_words',
divStyles: {'padding-bottom': '5px'},
options: {
box_width: this._current.box_width,
box_type: this._current.hideStates ? WordLine.BoxType.flow : WordLine.BoxType.fixed,
css_class_main: 'outWord',
// data_access: d => d.decoder.length ? [d.decoder[this._current.topN]] : []
}
});
visColumn.beam = this._createWordLine({
col: visColumn.selection,
className: 'beam_words',
divStyles: {'padding-bottom': '5px'},
options: {
box_width: this._current.box_width,
box_type: this._current.hideStates ? WordLine.BoxType.flow : WordLine.BoxType.fixed,
css_class_main: 'topKWord',
// data_access: d => d.decoder.length ? [d.decoder[this._current.topN]] : []
}
});
visColumn.sideIndicator = visColumn.selection.append('div').classed('sideIndicator',true)
.text('side');
// visColumn.decoder_states = this._createNeighborStates({
// col: visColumn.selection,
// className: 'decoder_state_neighbors',
// divStyles: {'padding-bottom': '5px'},
// options: {
// box_width: this._current.box_width
// }
// });
// visColumn.context = this._createNeighborStates({
// col: visColumn.selection,
// className: 'context_state_neighbors',
//
// options: {
// box_width: this._current.box_width
// }
// });
const partial_diff = (x) => {
const y = x.map(e => Array.isArray(e.cstar) ? e.cstar : [])
// diff:
// for (let i = 0; i < y.length - 1; i++) {
// y[i] = y[i + 1].map((yd, yi) => Math.abs(yd - y[i][yi]))
// }
// y[y.length - 1] = y[0].map(() => 0)
return y;
}
// visColumn.decoder_extra.push(this._createStatesVis({
// col: visColumn.selection,
// className: 'states_decoder',
// divStyles: {'padding-bottom': '5px'},
// options: {
// data_access: d =>
// (d.decoder.length > this._current.topN) ?
// partial_diff(d.decoder[this._current.topN])
// // d.decoder[this._current.topN]
// // .map(e => _.isArray(e.cstar) ? e.cstar : [])
// : [[]], // TODO: fix hack !!!
// hidden: this._current.hideStates,
// height: 100,
// cell_width: this._current.box_width
// }
// }));
//
// visColumn.decoder_extra.push(this._createWordLine({
// col: visColumn.selection,
// className: 'decoder_topK',
// divStyles: {'padding-top': '5px'},
// options: {
// css_class_main: 'topKWord',
// data_access: d => d.decoder.filter((_, i) => i !== this._current.topN)
// }
// }))
}
static _setupPanel({col, className, divStyles, addSVG = true, title = <string> null}) {
const div = col
.append('div').attr('class', 'setup ' + className).styles(divStyles)
// .style('background', 'lightgray');
if (title) {
div.html(title);
}
if (addSVG) return div.append('svg').attrs({width: 100, height: 30})
.styles({
display: 'inline-block'
});
else return div;
}
_createScoreVis({col, className, options, divStyles}) {
const svg = PanelManager._setupPanel({
col,
className,
divStyles,
addSVG: true
});
return new BarList(svg, this.eventHandler, options)
}
static _standardSVGPanel({col, className, divStyles}) {
return col
.append('div').attr('class', className).styles(divStyles)
.append('svg').attrs({width: 500, height: 30});
}
_createStatesVis({col, className, options, divStyles}) {
const svg = PanelManager._standardSVGPanel({col, className, divStyles});
return new StateVis(svg, this.eventHandler, options);
}
_createAttention({col, className, options, divStyles = null}) {
const svg = PanelManager._standardSVGPanel({col, className, divStyles});
return new AttentionVis(svg, this.eventHandler, options)
}
_createWordLine({col, className, options, divStyles}) {
const svg = PanelManager._standardSVGPanel({col, className, divStyles});
return new WordLine(svg, this.eventHandler, options)
}
_createWordProjector({col, className, options, divStyles}) {
const svg = PanelManager._standardSVGPanel({col, className, divStyles});
return new WordProjector(svg, this.eventHandler, options)
}
_createCloseWordList({col, className, options, divStyles}) {
const svg = PanelManager._standardSVGPanel({col, className, divStyles});
return new CloseWordList(svg, this.eventHandler, options)
}
getWordProjector() {
if (this._current.wordProjector === null) {
this.closeAllRight();
this._current.wordProjector = this._createWordProjector({
col: this._vis.right.selection,
className: "word_projector",
divStyles: {},
options: {}
})
}
return this._current.wordProjector;
}
getInfoPanel() {
if (this._current.infoPanel === null) {
this.closeAllRight();
this._current.infoPanel = new InfoPanel(this._vis.right.selection);
}
return this._current.infoPanel
}
closeAllRight() {
// if (this._current.wordProjector) {
this._vis.right.selection.selectAll('*').remove();
this._vis.right = initPanel(this._vis.right.selection);
this._current.wordProjector = null;
this._current.infoPanel = null;
// }
}
getWordList() {
if (this._current.closeWordsList === null) {
this._current.closeWordsList = this._createCloseWordList({
col: this._vis.right.selection,
className: "close_word_list",
divStyles: {'padding-top': '10px'},
options: {}
})
}
return this._current.closeWordsList;
}
_createProjectorOptions() {
return d3.select('#projectorSelect')
// .on('change', ()=>{
// const v = d3.select('#projectorSelect').property('value')
// console.log(v,"--- ");
// })
}
updateProjectionSelectField(options: string[], defaultOption = null) {
const op = this.panels.projectorSelect
.selectAll('option').data(options);
op.exit().remove();
op.enter().append('option')
.merge(op)
// .attr('selected', d => (d === defaultOption) ? true : null)
.attr('value', d => d)
.text(d => d)
if (defaultOption) this.panels.projectorSelect.property('value', defaultOption)
}
setVisibilityNeighborPanels(visibility: boolean) {
this.panels.projectorPanel.style('display', visibility?null:'none');
this.panels.statePictoPanel.style('display', visibility?null:'none');
}
} | the_stack |
import {
request,
IRequestOptions,
appendCustomParams
} from "@esri/arcgis-rest-request";
import { IItem, IGroup } from "@esri/arcgis-rest-types";
import { getPortalUrl } from "../util/get-portal-url";
import { scrubControlChars } from '../util/scrub-control-chars';
import {
IItemDataOptions,
IItemRelationshipOptions,
IUserItemOptions,
determineOwner,
FetchReadMethodName
} from "./helpers";
/**
* ```
* import { getItem } from "@esri/arcgis-rest-portal";
* //
* getItem("ae7")
* .then(response);
* // or
* getItem("ae7", { authentication })
* .then(response)
* ```
* Get an item by id. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/item.htm) for more information.
*
* @param id - Item Id
* @param requestOptions - Options for the request
* @returns A Promise that will resolve with the data from the response.
*/
export function getItem(
id: string,
requestOptions?: IRequestOptions
): Promise<IItem> {
const url = getItemBaseUrl(id, requestOptions);
// default to a GET request
const options: IRequestOptions = {
...{ httpMethod: "GET" },
...requestOptions
};
return request(url, options);
}
/**
* Get the fully qualified base URL to the REST end point for an item.
* @param id Item Id
* @param portalUrlOrRequestOptions a portal URL or request options
* @returns URL to the item's REST end point, defaults to `https://www.arcgis.com/sharing/rest/content/items/{id}`
*/
export const getItemBaseUrl = (
id: string,
portalUrlOrRequestOptions?: string | IRequestOptions
) => {
const portalUrl =
typeof portalUrlOrRequestOptions === "string"
? portalUrlOrRequestOptions
: getPortalUrl(portalUrlOrRequestOptions);
return `${portalUrl}/content/items/${id}`;
};
/**
* ```
* import { getItemData } from "@esri/arcgis-rest-portal";
* //
* getItemData("ae7")
* .then(response)
* // or
* getItemData("ae7", { authentication })
* .then(response)
* ```
* Get the /data for an item. If no data exists, returns `undefined`. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/item-data.htm) for more information.
* @param id - Item Id
* @param requestOptions - Options for the request
* @returns A Promise that will resolve with the json data for the item.
*/
export function getItemData(
id: string,
requestOptions?: IItemDataOptions
): Promise<any> {
const url = `${getItemBaseUrl(id, requestOptions)}/data`;
// default to a GET request
const options: IItemDataOptions = {
...{ httpMethod: "GET", params: {} },
...requestOptions
};
if (options.file) {
options.params.f = null;
}
return request(url, options).catch(err => {
/* if the item doesn't include data, the response will be empty
and the internal call to response.json() will fail */
const emptyResponseErr = RegExp(
/The string did not match the expected pattern|(Unexpected end of (JSON input|data at line 1 column 1))/i
);
/* istanbul ignore else */
if (emptyResponseErr.test(err.message)) {
return;
} else throw err;
});
}
export interface IGetRelatedItemsResponse {
total: number;
relatedItems: IItem[];
}
/**
* ```
* import { getRelatedItems } from "@esri/arcgis-rest-portal";
* //
* getRelatedItems({
* id: "ae7",
* relationshipType: "Service2Layer" // or several ["Service2Layer", "Map2Area"]
* })
* .then(response)
* ```
* Get the related items. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/related-items.htm) for more information.
*
* @param requestOptions - Options for the request
* @returns A Promise to get some item resources.
*/
export function getRelatedItems(
requestOptions: IItemRelationshipOptions
): Promise<IGetRelatedItemsResponse> {
const url = `${getItemBaseUrl(
requestOptions.id,
requestOptions
)}/relatedItems`;
const options: IItemRelationshipOptions = {
httpMethod: "GET",
params: {
direction: requestOptions.direction
},
...requestOptions
};
if (typeof requestOptions.relationshipType === "string") {
options.params.relationshipType = requestOptions.relationshipType;
} else {
options.params.relationshipTypes = requestOptions.relationshipType;
}
delete options.direction;
delete options.relationshipType;
return request(url, options);
}
/**
* Get the resources associated with an item
*
* @param requestOptions - Options for the request
* @returns A Promise to get some item resources.
*/
export function getItemResources(
id: string,
requestOptions?: IRequestOptions
): Promise<any> {
const url = `${getItemBaseUrl(id, requestOptions)}/resources`;
// Mix in num:1000 with any user supplied params
// Key thing - we don't want to mutate the passed in requestOptions
// as that may be used in other (subsequent) calls in the course
// of a long promise chains
const options: IRequestOptions = {
...requestOptions
};
options.params = { num: 1000, ...options.params };
return request(url, options);
}
export interface IGetItemGroupsResponse {
admin?: IGroup[];
member?: IGroup[];
other?: IGroup[];
}
export interface IGetItemResourceOptions extends IRequestOptions {
/**
* Name of the info file, optionally including the folder path
*/
fileName: string;
/**
* How the fetch response should be read, see:
* https://developer.mozilla.org/en-US/docs/Web/API/Body#Methods
*/
readAs?: FetchReadMethodName;
}
/**
* ```js
* import { getItemResource } from "@esri/arcgis-rest-portal";
*
* // Parses contents as blob by default
* getItemResource("3ef", { fileName: "resource.jpg", ...})
* .then(resourceContents => {});
*
* // Can override parse method
* getItemResource("3ef", { fileName: "resource.json", readAs: 'json', ...})
* .then(resourceContents => {});
*
* // Get the response object instead
* getItemResource("3ef",{ rawResponse: true, fileName: "resource.json" })
* .then(response => {})
* ```
* Fetches an item resource and optionally parses it to the correct format.
*
* Note: provides JSON parse error protection by sanitizing out any unescaped control
* characters before parsing that would otherwise cause an error to be thrown
*
* @param {string} itemId
* @param {IGetItemResourceOptions} requestOptions
*/
export function getItemResource(
itemId: string,
requestOptions: IGetItemResourceOptions
) {
const readAs = requestOptions.readAs || 'blob';
return getItemFile(itemId, `/resources/${requestOptions.fileName}`, readAs, requestOptions);
}
/**
* ```js
* import { getItemGroups } from "@esri/arcgis-rest-portal";
* //
* getItemGroups("30e5fe3149c34df1ba922e6f5bbf808f")
* .then(response)
* ```
* Lists the groups of which the item is a part, only showing the groups that the calling user can access. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/groups.htm) for more information.
*
* @param id - The Id of the item to query group association for.
* @param requestOptions - Options for the request
* @returns A Promise to get some item groups.
*/
export function getItemGroups(
id: string,
requestOptions?: IRequestOptions
): Promise<IGetItemGroupsResponse> {
const url = `${getItemBaseUrl(id, requestOptions)}/groups`;
return request(url, requestOptions);
}
export interface IItemStatusOptions extends IUserItemOptions {
/**
* The type of asynchronous job for which the status has to be checked. Default is none, which check the item's status.
*/
jobType?: "publish" | "generateFeatures" | "export" | "createService";
/**
* The job ID returned during publish, generateFeatures, export, and createService calls.
*/
jobId?: string;
/**
* The response format. The default and the only response format for this resource is HTML.
*/
format?: "html";
}
export interface IGetItemStatusResponse {
status: "partial" | "processing" | "failed" | "completed";
statusMessage: string;
itemId: string;
}
/**
* ```js
* import { getItemStatus } from "@esri/arcgis-rest-portal";
* //
* getItemStatus({
* id: "30e5fe3149c34df1ba922e6f5bbf808f",
* authentication
* })
* .then(response)
* ```
* Inquire about status when publishing an item, adding an item in async mode, or adding with a multipart upload. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/status.htm) for more information.
*
* @param id - The Id of the item to get status for.
* @param requestOptions - Options for the request
* @returns A Promise to get the item status.
*/
export function getItemStatus(
requestOptions: IItemStatusOptions
): Promise<IGetItemStatusResponse> {
return determineOwner(requestOptions).then(owner => {
const url = `${getPortalUrl(requestOptions)}/content/users/${owner}/items/${
requestOptions.id
}/status`;
const options = appendCustomParams<IItemStatusOptions>(
requestOptions,
["jobId", "jobType"],
{ params: { ...requestOptions.params } }
);
return request(url, options);
});
}
export interface IGetItemPartsResponse {
parts: number[];
}
/**
* ```js
* import { getItemParts } from "@esri/arcgis-rest-portal";
* //
* getItemParts({
* id: "30e5fe3149c34df1ba922e6f5bbf808f",
* authentication
* })
* .then(response)
* ```
* Lists the part numbers of the file parts that have already been uploaded in a multipart file upload. This method can be used to verify the parts that have been received as well as those parts that were not received by the server. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/parts.htm) for more information.
*
* @param id - The Id of the item to get part list.
* @param requestOptions - Options for the request
* @returns A Promise to get the item part list.
*/
export function getItemParts(
requestOptions: IUserItemOptions
): Promise<IGetItemPartsResponse> {
return determineOwner(requestOptions).then(owner => {
const url = `${getPortalUrl(requestOptions)}/content/users/${owner}/items/${
requestOptions.id
}/parts`;
return request(url, requestOptions);
});
}
export interface IGetItemInfoOptions extends IRequestOptions {
/**
* Name of the info file, optionally including the folder path
*/
fileName?: string;
/**
* How the fetch response should be read, see:
* https://developer.mozilla.org/en-US/docs/Web/API/Body#Methods
*/
readAs?: FetchReadMethodName;
}
/**
* ```
* import { getItemInfo } from "@esri/arcgis-rest-portal";
* // get the "Info Card" for the item
* getItemInfo("ae7")
* .then(itemInfoXml) // XML document as a string
* // or get the contents of a specific file
* getItemInfo("ae7", { fileName: "form.json", readAs: "json", authentication })
* .then(formJson) // JSON document as JSON
* ```
* Get an info file for an item. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/item-info-file.htm) for more information.
* @param id - Item Id
* @param requestOptions - Options for the request, including the file name which defaults to `iteminfo.xml`.
* If the file is not a text file (XML, HTML, etc) you will need to specify the `readAs` parameter
* @returns A Promise that will resolve with the contents of the info file for the item.
*/
export function getItemInfo(
id: string,
requestOptions?: IGetItemInfoOptions
): Promise<any> {
const { fileName = "iteminfo.xml", readAs = "text" } = requestOptions || {};
const options: IRequestOptions = {
httpMethod: "GET",
...requestOptions
};
return getItemFile(id, `/info/${fileName}`, readAs, options);
}
/**
* ```
* import { getItemMetadata } from "@esri/arcgis-rest-portal";
* // get the metadata for the item
* getItemMetadata("ae7")
* .then(itemMetadataXml) // XML document as a string
* // or with additional request options
* getItemMetadata("ae7", { authentication })
* .then(itemMetadataXml) // XML document as a string
* ```
* Get the standard formal metadata XML file for an item (`/info/metadata/metadata.xml`)
* @param id - Item Id
* @param requestOptions - Options for the request
* @returns A Promise that will resolve with the contents of the metadata file for the item as a string.
*/
export function getItemMetadata(
id: string,
requestOptions?: IRequestOptions
): Promise<any> {
const options = {
...requestOptions,
fileName: "metadata/metadata.xml"
} as IGetItemInfoOptions;
return getItemInfo(id, options);
}
// overrides request()'s default behavior for reading the response
// which is based on `params.f` and defaults to JSON
// Also adds JSON parse error protection by sanitizing out any unescaped control characters before parsing
function getItemFile(
id: string,
// NOTE: fileName should include any folder/subfolders
fileName: string,
readMethod: FetchReadMethodName,
requestOptions?: IRequestOptions
): Promise<any> {
const url = `${getItemBaseUrl(id, requestOptions)}${fileName}`;
// preserve escape hatch to let the consumer read the response
// and ensure the f param is not appended to the query string
const options: IRequestOptions = {
params: {},
...requestOptions
};
const justReturnResponse = options.rawResponse;
options.rawResponse = true;
options.params.f = null;
return request(url, options).then(response => {
if (justReturnResponse) {
return response;
}
return readMethod !== 'json'
? response[readMethod]()
: response.text().then((text: string) => JSON.parse(scrubControlChars(text)));
});
} | the_stack |
import React, { useEffect } from "react";
import { connect, useConnect } from "frontity";
import { isArchive, isError } from "@frontity/source";
import {
generateMemoizedWrapper,
InternalWrapper,
} from "../use-infinite-scroll/utils";
import { getLinksFromPages } from "./utils";
import {
Packages,
WrapperGenerator,
WrapperProps,
} from "../use-infinite-scroll/types";
import {
UsePostTypeInfiniteScrollOptions,
UsePostTypeInfiniteScrollOutput,
} from "./types";
/**
* Generate a Wrapper component.
*
* @param options - The link for the page that the Wrapper belongs to
* and the intersection observer options for fetching and routing.
*
* @returns A React component that should be used to wrap the post.
*/
export const wrapperGenerator: WrapperGenerator = ({
link,
fetchInViewOptions,
routeInViewOptions,
}) => {
/**
* The wrapper component returned by this hook.
*
* @param props - The component props.
* @returns A react element.
*/
const PostTypeWrapper: React.FC<WrapperProps> = ({ children, className }) => {
const { state } = useConnect<Packages>();
const { infiniteScroll } = state.router.state;
// Values from browser state.
const links: string[] = infiniteScroll?.links || [link];
const limit: number = infiniteScroll?.limit;
const pages: string[] = infiniteScroll?.pages || [];
const itemLinks = getLinksFromPages({
pages,
firstLink: links[0],
sourceGet: state.source.get,
});
const props = {
link,
nextLink: itemLinks[itemLinks.indexOf(link) + 1],
className,
children,
fetchInViewOptions,
routeInViewOptions,
hasReachedLimit: !!limit && links.length >= limit,
};
return <InternalWrapper {...props} />;
};
return connect(PostTypeWrapper, { injectProps: false });
};
/**
* The memoized <Wrapper> component.
*/
const MemoizedWrapper = generateMemoizedWrapper(wrapperGenerator);
/**
* A hook used to add infinite scroll to any Frontity post type.
*
* @param options - Options for the hook, like the number of posts it should
* load autoamtically or if it's active or not. Defined in {@link
* UsePostTypeInfiniteScroll}.
*
* @returns - An array of posts and other useful booleans. Defined in {@link
* UsePostTypeInfiniteScroll}.
*/
const usePostTypeInfiniteScroll = (
options: UsePostTypeInfiniteScrollOptions = {}
): UsePostTypeInfiniteScrollOutput => {
const defaultOptions = { active: true };
options = { ...defaultOptions, ...options };
const { state, actions } = useConnect<Packages>();
const { infiniteScroll } = state.router.state;
// Values for browser state.
const archive: string = (() => {
// If `archive` is set in options, use it.
if (options.archive) {
return options.archive;
}
// If `archive` is already in the state, use it.
if (infiniteScroll?.archive) {
return infiniteScroll.archive;
}
// If `state.router.previous` is an archive, use it.
const previous = state.router.previous
? state.source.get(state.router.previous)
: null;
if (previous && isArchive(previous)) {
return previous.link;
}
// If `fallback` is set in options, use it.
if (options.fallback) {
return options.fallback;
}
// If subdirectory (and postsPage) exist, return them.
if (state.source.subdirectory) {
const subdirectory = state.source.subdirectory
.replace(/^\/?/, "/")
.replace(/\/?$/, "/");
if (state.source.postsPage)
return (
subdirectory.replace(/\/?$/, "") +
state.source.postsPage.replace(/^\/?/, "/").replace(/\/?$/, "/")
);
return subdirectory;
}
// If postsPage exists, return it.
if (state.source.postsPage)
return state.source.postsPage.replace(/^\/?/, "/").replace(/\/?$/, "/");
// Return home as default.
return "/";
})();
// List of links for the different archive pages.
const pages: string[] = infiniteScroll?.pages
? [...infiniteScroll.pages]
: [archive];
// List of links for the posts contained in the archive pages.
const links: string[] = infiniteScroll?.links
? [...infiniteScroll.links]
: [state.router.link];
const limit = infiniteScroll?.limit || options.limit;
// Boolean to trigger the initialization effect.
const isInitialized = !!infiniteScroll;
// Initialize/update browser state.
useEffect(() => {
if (!options.active) return;
actions.router.updateState({
...state.router.state,
infiniteScroll: {
...state.router.state.infiniteScroll,
archive,
pages,
links,
limit,
},
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [options.active, isInitialized]);
// Data objects of the last archive page fetched and the next one.
const lastPage = state.source.get(pages[pages.length - 1]);
const nextPage =
isArchive(lastPage) && lastPage.next
? state.source.get(lastPage.next)
: null;
// The first link that appears at the top of the infinite scroll.
const firstLink = links[0];
// Data object of the last entity rendered by the infinite scroll hook.
const last = state.source.get(links[links.length - 1]);
// Get the list of all item links from the archive pages and obtain the data
// object of the next entity from there.
const itemLinks = getLinksFromPages({
pages,
firstLink,
sourceGet: state.source.get,
});
const lastIndex = itemLinks.indexOf(last.link);
const nextLink = itemLinks[lastIndex + 1];
const next = nextLink ? state.source.get(nextLink) : null;
// Compute the infinite scroll booleans returned by this hook.
const isLastItem = itemLinks[itemLinks.length - 1] === state.router.link;
const hasReachedLimit = !!limit && links.length >= limit;
const thereIsNext =
lastIndex < itemLinks.length - 1 ||
(isArchive(lastPage) && !!lastPage.next);
const isFetching =
!!next?.isFetching || (pages.length > 1 && lastPage.isFetching);
const isLastError = isError(last) || isError(lastPage);
const isLimit = hasReachedLimit && thereIsNext && !isFetching;
// Request archive if not present.
useEffect(() => {
if (!options.active) return;
const data = archive ? state.source.get(archive) : null;
if (!data.isReady && !data.isFetching) {
actions.source.fetch(data.link);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [options.active]);
// Request next page on last item.
useEffect(() => {
if (!options.active || !nextPage || hasReachedLimit || !isLastItem) return;
pages.push(nextPage.link);
actions.router.updateState({
...state.router.state,
infiniteScroll: {
...state.router.state.infiniteScroll,
pages,
},
});
if (!nextPage.isReady && !nextPage.isFetching) {
actions.source.fetch(nextPage.link);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [options.active, state.router.link, itemLinks.length, hasReachedLimit]);
/**
* Function to fetch the next item disregarding the limit.
*/
const fetchNext = async () => {
// Don't fetch if hook is not active or there are no next page or there
// was not an error in the last fetch.
if (!options.active || (!thereIsNext && !isLastError)) return;
const links = infiniteScroll?.links
? [...infiniteScroll.links]
: [state.router.link];
// We need `nextItem` to be declared in local scope.
let nextItem = itemLinks[lastIndex + 1];
// Start the fetch of the next page and await until it has finished.
if (isLastError) {
// If there was an error, force a fetch of the last page.
if (isError(lastPage))
await actions.source.fetch(pages[pages.length - 1], { force: true });
} else if (!nextItem) {
// If there is no next page, do nothing.
if (!nextPage) return;
pages.push(nextPage.link);
actions.router.updateState({
...state.router.state,
infiniteScroll: {
...infiniteScroll,
links,
pages,
},
});
// If next page is not already ready or fetching, fetch and wait until it
// finishes.
if (!nextPage.isReady && !nextPage.isFetching) {
await actions.source.fetch(nextPage.link);
}
// Once it has finished, get the new list of items.
const itemLinks = getLinksFromPages({
pages,
firstLink,
sourceGet: state.source.get,
});
// Update the next item.
nextItem = itemLinks[lastIndex + 1];
}
// Start the fetch of the next item and wait until it has finished.
if (isLastError) {
if (isError(last))
// If there was an error, force a fetch of the last item.
await actions.source.fetch(links[links.length - 1], { force: true });
} else {
// If the nextItem is not in the links, do nothing.
if (links.includes(nextItem)) return;
links.push(nextItem);
actions.router.updateState({
...state.router.state,
infiniteScroll: {
...state.router.state.infiniteScroll,
links,
pages,
},
});
const next = state.source.get(nextItem);
// If next item is not already ready or fetching, fetch and wait until it
// finishes.
if (!next.isReady && !next.isFetching) {
await actions.source.fetch(nextItem);
}
}
};
// Map every link to its DIY object.
const posts = links.map((link) => ({
key: link,
link: link,
isLast:
(link === last.link && !!last.isReady && !isError(last)) ||
(link === links[links.length - 2] && !last.isReady) ||
(link === links[links.length - 2] && !!last.isReady && !!isError(last)),
Wrapper: MemoizedWrapper(link, {
fetchInViewOptions: options.fetchInViewOptions,
routeInViewOptions: options.routeInViewOptions,
}),
}));
return {
posts,
isLimit,
isFetching,
isError: isLastError,
fetchNext,
};
};
export default usePostTypeInfiniteScroll; | the_stack |
import 'reflect-metadata';
import { Collection, Before, After, MongoRepository, RepoEventArgs, RepoOperation, DatabaseClient } from '../src';
import * as mongoMock from 'mongo-mock';
mongoMock.max_delay = 0; // turn of fake async
import { expect } from 'chai';
import * as faker from 'faker';
import { ObjectId } from 'mongodb';
import * as clone from 'clone';
describe('MongoRepository', () => {
const dbs = [];
// Make sure you close all DBs
// Added this in case of error, CI tests are not hung open
after(async () => {
await Promise.all(dbs.map(db => db.close()));
});
function getDb(): Promise<DatabaseClient> {
return new Promise((resolve, reject) => {
const dbc = new DatabaseClient();
const MongoClient = mongoMock.MongoClient;
// unique db for each request
const uri = `mongodb://${faker.internet.domainName()}:12345/Foo`;
MongoClient.connect(uri, {}, (err, db) => {
if (err) reject(err);
else {
// dbc.connect(uri, db);
// Hack until mongo-mock support 3.x driver
dbc.db = Promise.resolve(db);
dbs.push(db);
resolve(dbc);
}
});
});
}
describe('CRUD', () => {
const COLLECTION_NAME = 'Foo';
interface User {
name: string;
title?: string;
}
@Collection({
name: COLLECTION_NAME
})
class UserRepository extends MongoRepository<User> {
events: {
pre: { [op in RepoOperation]: Array<{ args: [] }> };
post: { [op in RepoOperation]: Array<{ args: [] }> };
} = {
pre: Object.keys(RepoOperation).reduce((opMap, opName) => {
opMap[opName] = [];
return opMap;
}, {}) as any,
post: Object.keys(RepoOperation).reduce((opMap, opName) => {
opMap[opName] = [];
return opMap;
}, {}) as any
};
clearEvents(): void {
this.events = {
pre: Object.keys(RepoOperation).reduce((opMap, opName) => {
opMap[opName] = [];
return opMap;
}, {}) as any,
post: Object.keys(RepoOperation).reduce((opMap, opName) => {
opMap[opName] = [];
return opMap;
}, {}) as any
};
}
@Before(...Object.keys(RepoOperation))
@After(...Object.keys(RepoOperation))
captureEvent(...args: any[]): any {
const eventArgs: RepoEventArgs = args[args.length - 1];
if (!this.events[eventArgs.operationType][eventArgs.operation]) {
this.events[eventArgs.operationType][eventArgs.operation] = [];
}
this.events[eventArgs.operationType][eventArgs.operation].push({ args: clone(args) });
return args[0]; // return document
}
}
class UserRepositoryNoDecorator extends MongoRepository<User> {}
it('should create a collection', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new UserRepository(dbc);
await repo.collection; // wait for collection to be created
const collection = mockDb.collection(COLLECTION_NAME);
expect(collection.collectionName).to.equal(COLLECTION_NAME);
dbc.close();
});
it('should create a collection with supplied options instead of decorator', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const name = COLLECTION_NAME + '_noDecorator';
const repo = new UserRepositoryNoDecorator(dbc, { name });
await repo.collection; // wait for collection to be created
const collection = mockDb.collection(name);
expect(collection.collectionName).to.equal(name);
dbc.close();
});
it('should throw an error if no collection name is provided', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
expect(() => new UserRepositoryNoDecorator(dbc)).to.throw(/No name was provided for this collection/);
dbc.close();
});
it('should reuse an existing collection', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const collection = mockDb.collection(COLLECTION_NAME);
const user = { name: faker.name.firstName() };
const record = await collection.insertOne(user);
const repo = new UserRepository(dbc);
const foundRecord = await repo.findOne({ name: user.name });
expect(foundRecord.name).to.deep.equal(record.ops[0].name);
dbc.close();
});
it('should create/save/delete a record', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new UserRepository(dbc);
const userObj = {
name: faker.name.firstName(),
title: faker.name.jobTitle()
};
// Create
const user = await repo.create(userObj);
const collection = mockDb.collection(COLLECTION_NAME);
const foundUser = await collection.findOne({ name: userObj.name });
expect(foundUser.name).to.equal(userObj.name);
expect(foundUser).to.haveOwnProperty('_id');
// Save
userObj.title = user.title = faker.name.jobTitle();
const newUser = await repo.save(user);
expect(newUser.title).to.equal(userObj.title);
// Find one by id and update
// reuse foundUser from above
userObj.name = faker.name.firstName();
const updatedUserName = await repo.findOneByIdAndUpdate(foundUser._id, {
updates: {
$set: {
name: userObj.name
}
}
});
expect(updatedUserName.name).to.equal(userObj.name);
// Find one and update
userObj.title = faker.name.jobTitle();
const updatedUserTitle = await repo.findOneAndUpdate({
conditions: {
name: userObj.name
},
updates: {
$set: {
title: userObj.title
}
}
});
expect(updatedUserTitle.title).to.equal(userObj.title);
// Delete One by Id
const deleteOneById = await repo.deleteOneById(foundUser._id);
expect(deleteOneById.result.n).to.equal(1);
// Delete One
await repo.create(userObj); // put user back in
const deleteOne = await repo.deleteOne({ name: userObj.name });
expect(deleteOne.result.n).to.equal(1);
dbc.close();
});
it('should delete many records', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new UserRepository(dbc);
const title = faker.name.jobTitle();
// insert a bunch of documents
for (let x = 0; x < 10; x++) {
await repo.create({ name: faker.name.firstName(), title });
}
const delRes = await repo.deleteMany({ title });
expect(delRes.result.n).to.equal(10);
dbc.close();
});
describe('findOneAndUpdate', () => {
it('should short circuit with no document found by id', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new UserRepository(dbc);
await repo.create({ name: faker.name.firstName(), title: faker.name.jobTitle() });
repo.clearEvents();
const noUser = await repo.findOneByIdAndUpdate(new ObjectId().toHexString(), {
updates: { $set: { title: 'Unicorn Tamer' } }
});
expect(noUser).to.be.null;
expect(repo.events.post.update).to.be.empty;
expect(repo.events.post.updateOne).to.be.empty;
expect(repo.events.pre.update).to.be.lengthOf(1);
expect(repo.events.pre.updateOne).to.be.lengthOf(1);
dbc.close();
});
it('should short circuit with no document found', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new UserRepository(dbc);
await repo.create({ name: faker.name.firstName(), title: faker.name.jobTitle() });
repo.clearEvents();
const noUser = await repo.findOneAndUpdate({
conditions: { name: 'Nonexistent User' },
updates: { $set: { title: 'Unicorn Tamer' } }
});
expect(noUser).to.be.null;
expect(repo.events.post.update).to.be.empty;
expect(repo.events.post.updateOne).to.be.empty;
expect(repo.events.pre.update).to.be.lengthOf(1);
expect(repo.events.pre.updateOne).to.be.lengthOf(1);
dbc.close();
});
});
});
describe('Finding', () => {
const COLLECTION_NAME = 'People';
interface Person {
firstName: string;
lastName: string;
title: string;
}
@Collection({
name: COLLECTION_NAME
})
class PeopleRepository extends MongoRepository<Person> {}
async function populateDb(db: any): Promise<any[]> {
const collection = db.collection(COLLECTION_NAME);
const people: any[] = [];
for (let x = 0; x < 10; x++) {
const res = await collection.insertOne({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
title: 'fake'
});
people.push(...res.ops);
}
return people;
}
it('should find a record by id', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const people = await populateDb(mockDb);
const repo = new PeopleRepository(dbc);
const foundPerson = await repo.findById(people[0]._id);
const collection = await repo.collection;
expect(foundPerson.firstName).to.equal(people[0].firstName);
dbc.close();
});
it('should find a record by name', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const people = await populateDb(mockDb);
const repo = new PeopleRepository(dbc);
const foundPerson = await repo.findOne({ firstName: people[0].firstName });
expect(foundPerson.firstName).to.equal(people[0].firstName);
dbc.close();
});
it('should find multiple records', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const people = await populateDb(mockDb);
const repo = new PeopleRepository(dbc);
const foundPeople = await repo.find({ conditions: { title: 'fake' } });
expect(foundPeople.length).to.equal(people.length);
dbc.close();
});
it('should find multiple records by id', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const people = await populateDb(mockDb);
const repo = new PeopleRepository(dbc);
const foundPeople = await repo.findManyById(people.map(p => p._id.toString()));
expect(foundPeople.length).to.equal(people.length);
dbc.close();
});
});
describe('Before/After', () => {
const COLLECTION_NAME = 'Dogs';
interface Dog {
firstName: string;
type: string;
good?: boolean;
}
@Collection({
name: COLLECTION_NAME
})
class DogRepository extends MongoRepository<Dog> {
@Before('create')
async goodBoy(doc: Dog): Promise<Dog> {
doc.good = true;
return doc;
}
@Before('save')
async onlyGoodBoys(doc: Dog): Promise<Dog> {
if ('good' in doc && !doc.good) {
throw new Error('All dogs are good!');
}
return doc;
}
@After('find')
async shout(doc: Dog): Promise<Dog> {
doc.firstName = doc.firstName.toUpperCase();
return doc;
}
@After('save', 'update')
async convert(newDoc: Dog, args: RepoEventArgs): Promise<Dog> {
if (
args.originalDocument &&
args.originalDocument.firstName === 'FIDO' &&
args.originalDocument.firstName !== newDoc.firstName
) {
throw new Error(`don't change fido's name!`);
}
return newDoc;
}
@After('create', 'delete')
async protec(newDoc: Dog, args: RepoEventArgs): Promise<Dog> {
if (args.operation === RepoOperation.delete) {
throw new Error(`you wouldn't delete a dog would you?`);
}
return newDoc;
}
}
it('should set all new dogs to good', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new DogRepository(dbc);
const puppers = await repo.create({ firstName: faker.name.firstName(), type: 'mutt' });
const foundPup = await repo.findOne({ firstName: puppers.firstName });
expect(foundPup.firstName).to.equal(puppers.firstName.toUpperCase());
expect(foundPup.good).to.equal(true);
dbc.close();
});
it('should reject any bad dogs', async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new DogRepository(dbc);
const puppers = await repo.create({ firstName: faker.name.firstName(), type: 'mutt' });
try {
const badDog = await repo.save({ ...puppers, good: false });
throw new Error('We allowed a bad dog!');
} catch (err) {
expect(err.message).to.equal('All dogs are good!');
}
dbc.close();
});
it(`should reject save changing fido's name`, async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new DogRepository(dbc);
const puppers = await repo.create({ firstName: 'fido', type: 'mutt' });
try {
const badDog = await repo.save({ ...puppers, firstName: 'somethingelse' });
throw new Error('We allowed fido to change names!');
} catch (err) {
expect(err.message).to.equal(`don't change fido's name!`);
}
dbc.close();
});
it(`should allow save changing spot's name`, async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new DogRepository(dbc);
const puppers = await repo.create({ firstName: 'spot', type: 'mutt' });
try {
const badDog = await repo.save({ ...puppers, firstName: 'somethingelse' });
throw new Error('We allowed spot to change names to ' + badDog.firstName + '!');
} catch (err) {
expect(err.message).to.equal(`We allowed spot to change names to somethingelse!`);
}
dbc.close();
});
it(`should reject update changing fido's name`, async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new DogRepository(dbc);
const puppers = await repo.create({ firstName: 'fido', type: 'mutt' });
try {
const badDog = await repo.findOneAndUpdate({
conditions: { firstName: 'fido' },
updates: { firstName: 'somethingelse' }
});
throw new Error('We allowed fido to change names!');
} catch (err) {
expect(err.message).to.equal(`don't change fido's name!`);
}
dbc.close();
});
it(`should allow save changing spot's name`, async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new DogRepository(dbc);
const puppers = await repo.create({ firstName: 'spot', type: 'mutt' });
try {
const badDog = await repo.findOneAndUpdate({
conditions: { firstName: 'spot' },
updates: { firstName: 'somethingelse' }
});
throw new Error('We allowed spot to change names to ' + badDog.firstName + '!');
} catch (err) {
expect(err.message).to.equal(`We allowed spot to change names to somethingelse!`);
}
dbc.close();
});
it(`should prevent deleting a dog`, async () => {
const dbc = await getDb();
const mockDb = await dbc.db;
const repo = new DogRepository(dbc);
const puppers = await repo.create({ firstName: 'spot', type: 'mutt' });
try {
const badDog = await repo.deleteOne(puppers);
throw new Error('We deleted spot!');
} catch (err) {
expect(err.message).to.equal(`you wouldn't delete a dog would you?`);
}
dbc.close();
});
});
}); | the_stack |
import NoteToTransmit from "../lib/notes/interfaces/NoteToTransmit.js";
import { NoteId } from "../lib/notes/interfaces/NoteId.js";
import Stats from "../lib/notes/interfaces/GraphStats.js";
import { yyyymmdd } from "../lib/utils.js";
import * as config from "./config.js";
import compression from "compression";
import express from "express";
import * as Notes from "../lib/notes/index.js";
import bcrypt from "bcryptjs";
import APIResponse from "./interfaces/APIResponse.js";
import { APIError } from "./interfaces/APIError.js";
import cookieParser from "cookie-parser";
import AppStartOptions from "./interfaces/AppStartOptions.js";
import NoteListPage from "../lib/notes/interfaces/NoteListPage.js";
import FileSystemStorageProvider from "./lib/FileSystemStorageProvider.js";
import http from "http";
import https from "https";
import getUrlMetadata from "./lib/getUrlMetadata.js";
import twofactor from "node-2fa";
import fallback from "express-history-api-fallback";
import * as path from "path";
import session from "express-session";
import User from "./interfaces/User.js";
import { randomUUID } from "crypto";
import FileSessionStore from "./lib/FileSessionStore.js";
import * as logger from "./lib/logger.js";
import { NoteListSortMode } from "../lib/notes/interfaces/NoteListSortMode.js";
import { UserId } from "./interfaces/UserId.js";
import { GraphId } from "./interfaces/GraphId.js";
import BruteForcePreventer from "./BruteForcePreventer.js";
const startApp = async ({
users,
dataPath,
frontendPath,
sessionSecret,
sessionTTL,
maxUploadFileSize,
sessionCookieName,
}:AppStartOptions):Promise<Express.Application> => {
const graphsDirectoryPath = path.join(dataPath, config.GRAPHS_DIRECTORY_NAME);
const storageProvider = new FileSystemStorageProvider(graphsDirectoryPath);
logger.info("File system storage ready at " + graphsDirectoryPath);
logger.info("Session TTL: " + sessionTTL.toString() + " day(s)");
logger.info(
"Maximum upload file size: " + maxUploadFileSize.toString() + " byte(s)",
);
logger.info("Initializing notes module...");
await Notes.init(storageProvider, getUrlMetadata, randomUUID);
logger.info("Initializing routes...")
const app = express();
const bruteForcePreventer = new BruteForcePreventer();
const sessionMiddleware = session({
secret: sessionSecret,
saveUninitialized: false,
cookie: {
maxAge: sessionTTL * 24 * 60 * 60 * 1000, // days to ms
path: '/',
httpOnly: true,
secure: "auto",
},
resave: false,
name: sessionCookieName,
unset: "keep",
store: new (FileSessionStore(session))({
checkPeriod: 86400000, // prune expired entries every 24h,
maxNumberOfSessions: 1000,
filePath: path.join(dataPath, "sessions.json"),
}),
});
const getUserByApiKey = (apiKey:string):User | null => {
const user = users.find((user) => {
return user.apiKeys?.includes(apiKey);
});
return user ?? null;
};
const getGraphIdsForUser = (userId:UserId):GraphId[] => {
const user = users.find((user) => user.id === userId);
if (!user) {
throw new Error("Unknown user id");
}
return user.graphIds;
}
const verifyUser = (req, res, next) => {
if (req.session.userId) {
// make the user id available in the req object for easier access
req.userId = req.session.userId;
// if the user passed a graph id as param, they must have the rights to
// access it
if (req.params.graphId) {
const graphIds = getGraphIdsForUser(req.userId);
if (!graphIds.includes(req.params.graphId)){
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
return res.status(406).json(response);
}
}
next();
// if userId has not been set via session, check if api key is present
} else if (typeof req.headers["x-auth-token"] === "string") {
const apiKey = req.headers["x-auth-token"];
const user = getUserByApiKey(apiKey);
if (user) {
req.userId = user.id;
next();
} else {
logger.verbose("User provided invalid API key: " + apiKey);
const response:APIResponse = {
success: false,
error: APIError.INVALID_CREDENTIALS,
};
return res.status(401).json(response);
}
} else {
const response:APIResponse = {
success: false,
error: APIError.UNAUTHORIZED,
};
return res.status(401).json(response);
}
};
//CORS middleware
const allowCORS = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Methods',
'GET, PUT, POST, PATCH, DELETE, OPTIONS',
);
res.header(
'Access-Control-Allow-Headers',
'Origin, Content-Type, X-Auth-Token',
);
if (req.method === "OPTIONS") {
return res.status(200).end();
}
next();
};
app.use("/", express.static(frontendPath));
app.use(compression());
app.use(cookieParser());
app.use(allowCORS);
/* ***************
Endpoints
*****************/
/* ***************
Endpoints with authentication required
*****************/
app.get(
config.USER_ENDOPINT + "authenticated",
sessionMiddleware,
verifyUser,
async function(req, res) {
const response:APIResponse = {
success: true,
payload: {
graphIds: getGraphIdsForUser(req.userId),
},
};
res.json(response);
},
);
app.get(
config.GRAPH_ENDPOINT,
sessionMiddleware,
verifyUser,
async function(req, res) {
const graphId = req.params.graphId;
const withFiles = req.query.withFiles === "true";
const databaseStream = await Notes.getReadableGraphStream(
graphId,
withFiles,
);
// set the archive name
const dateSuffix = yyyymmdd(new Date());
const extension = withFiles ? "zip" : "json";
const filename = `neno-${graphId}-${dateSuffix}.db.${extension}`;
res.attachment(filename);
// this is the streaming magic
databaseStream.pipe(res);
},
);
app.put(
config.GRAPH_ENDPOINT,
sessionMiddleware,
verifyUser,
express.json(),
function(req, res) {
const graphId = req.params.graphId;
const response:APIResponse = {
success: false,
};
try {
const success = Notes.importDB(req.body, graphId);
if (!success) throw new Error("INTERNAL_SERVER_ERROR");
response.success = true;
} catch(e) {
response.success = false;
response.error = APIError.INTERNAL_SERVER_ERROR;
} finally {
res.status(response.success ? 200 : 500).json(response);
}
},
);
app.get(
config.GRAPH_ENDPOINT + "graph-visualization",
sessionMiddleware,
verifyUser,
async function(req, res) {
const graphId = req.params.graphId;
const graph = await Notes.getGraphVisualization(graphId);
const response:APIResponse = {
success: true,
payload: graph,
};
res.json(response);
},
);
app.get(
config.GRAPH_ENDPOINT + "stats",
sessionMiddleware,
verifyUser,
async function(req, res) {
const graphId = req.params.graphId;
const options = {
includeMetadata: req.query.includeMetadata === "true",
includeAnalysis: req.query.includeAnalysis === "true",
};
const stats:Stats = await Notes.getStats(graphId, options);
const response:APIResponse = {
success: true,
payload: stats,
};
res.json(response);
},
);
app.post(
config.GRAPH_ENDPOINT + "graph-visualization",
sessionMiddleware,
verifyUser,
express.json({ limit: "1mb" }), // posting a graph can be somewhat larger
async function(req, res) {
const graphId = req.params.graphId;
try {
await Notes.setGraphVisualization(req.body, graphId);
const response:APIResponse = {
success: true,
};
res.json(response);
} catch (e) {
const response:APIResponse = {
success: false,
error: APIError.INTERNAL_SERVER_ERROR,
};
res.json(response);
}
},
);
app.get(
config.GRAPH_ENDPOINT + "notes",
sessionMiddleware,
verifyUser,
async function(req, res) {
const graphId = req.params.graphId;
const searchString = req.query.searchString as (string | undefined) || "";
const caseSensitive = req.query.caseSensitive === "true";
const page = typeof req.query.page === "string"
? parseInt(req.query.page)
: 1;
const sortMode = req.query.sortMode as NoteListSortMode;
const limit = typeof req.query.limit === "string"
? parseInt(req.query.limit)
: 0;
const notesListPage:NoteListPage = await Notes.getNotesList(
graphId,
{
searchString,
caseSensitive,
page,
sortMode,
limit,
},
);
const response:APIResponse = {
success: true,
payload: notesListPage,
};
res.json(response);
},
);
app.get(
config.GRAPH_ENDPOINT + "note/:noteId",
sessionMiddleware,
verifyUser,
async function(req, res) {
const graphId = req.params.graphId;
const noteId:NoteId = parseInt(req.params.noteId);
try {
const note:NoteToTransmit = await Notes.get(noteId, graphId);
const response:APIResponse = {
success: true,
payload: note,
};
res.json(response);
} catch (e) {
const response:APIResponse = {
success: false,
error: e,
};
res.json(response);
}
},
);
app.put(
config.GRAPH_ENDPOINT + "note",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const graphId = req.params.graphId;
const reqBody = req.body;
try {
const noteToTransmit:NoteToTransmit = await Notes.put(
reqBody.note,
graphId,
reqBody.options,
);
const response:APIResponse = {
success: true,
payload: noteToTransmit,
};
res.json(response);
} catch (e) {
const response:APIResponse = {
success: false,
error: e.message,
};
res.json(response);
}
},
);
app.put(
config.GRAPH_ENDPOINT + "import-links-as-notes",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const graphId = req.params.graphId;
const reqBody = req.body;
const links:string[] = reqBody.links;
const result = await Notes.importLinksAsNotes(graphId, links);
const response:APIResponse = {
payload: result,
success: true,
};
res.json(response);
},
);
app.delete(
config.GRAPH_ENDPOINT + "note/:noteId",
sessionMiddleware,
verifyUser,
async function(req, res) {
try {
const graphId = req.params.graphId;
await Notes.remove(parseInt(req.params.noteId), graphId);
const response:APIResponse = {
success: true,
};
res.json(response);
} catch (e) {
const response:APIResponse = {
success: false,
error: e.message,
};
res.json(response);
}
},
);
app.post(
config.GRAPH_ENDPOINT + "file",
sessionMiddleware,
verifyUser,
async function(req, res) {
const graphId = req.params.graphId;
const sizeString = req.headers["content-length"];
if (typeof sizeString !== "string") {
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
res.status(406).json(response);
return;
}
const size = parseInt(sizeString);
if (isNaN(size) || size < 1) {
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
res.status(406).json(response);
return;
}
if (size > maxUploadFileSize) {
const response:APIResponse = {
success: false,
error: APIError.RESOURCE_EXCEEDS_FILE_SIZE,
};
res.status(406).json(response);
return;
}
const mimeType = req.headers["content-type"];
if (!mimeType) {
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
res.status(406).json(response);
return;
}
try {
logger.verbose("Starting file upload. Type: " + mimeType);
//console.log(req)
const {fileId, size: transmittedBytes} = await Notes.addFile(
graphId,
req,
mimeType,
);
logger.verbose(
`Expected size: ${size} Transmitted: ${transmittedBytes}`,
);
if (size !== transmittedBytes) {
/* this looks like the request was not completed. we'll remove the
file */
logger.verbose("Removing file due to incomplete upload");
await Notes.deleteFile(graphId, fileId);
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
res.status(406).json(response);
return;
}
const response:APIResponse = {
success: true,
payload: {
fileId,
size,
},
};
res.json(response);
} catch (e) {
logger.verbose("Catched an error trying to upload a file:");
logger.verbose(e);
const response:APIResponse = {
success: false,
error: e.message,
};
res.status(406).json(response);
}
},
);
app.post(
config.GRAPH_ENDPOINT + "file-by-url",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const graphId = req.params.graphId;
const reqBody = req.body;
const url = reqBody.url;
if (!url) {
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
res.status(406).json(response);
return;
}
const handleResourceResponse = async (resourceResponse) => {
const mimeType = resourceResponse.headers['content-type'];
const size = parseInt(resourceResponse.headers['content-length']);
if (size > maxUploadFileSize) {
const response:APIResponse = {
success: false,
error: APIError.RESOURCE_EXCEEDS_FILE_SIZE,
};
res.status(406).json(response);
return;
}
if (!mimeType) {
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
res.status(406).json(response);
return;
}
try {
logger.verbose("Starting file download. Type: " + mimeType);
const {fileId, size: transmittedBytes} = await Notes.addFile(
graphId,
resourceResponse,
mimeType,
);
logger.verbose(
`Expected size: ${size} Transmitted: ${transmittedBytes}`,
);
if (size !== transmittedBytes) {
/* this looks like the download was not completed. we'll remove the
file */
await Notes.deleteFile(graphId, fileId);
const response:APIResponse = {
success: false,
error: APIError.INVALID_REQUEST,
};
res.status(406).json(response);
return;
}
const response:APIResponse = {
success: true,
payload: {
fileId,
size,
},
};
res.json(response);
} catch (e) {
const response:APIResponse = {
success: false,
error: e.message,
};
res.status(406).json(response);
}
}
if (url.startsWith("http://")) {
http
.get(url, handleResourceResponse)
// handle possible ECONNRESET errors
.on("error", (e) => {
const response:APIResponse = {
success: false,
error: e.message as APIError,
};
res.status(406).json(response);
});
} else if (url.startsWith("https://")) {
https
.get(url, handleResourceResponse)
// handle possible ECONNRESET errors
.on("error", (e) => {
const response:APIResponse = {
success: false,
error: e.message as APIError,
};
res.status(406).json(response);
});
} else {
const response:APIResponse = {
success: false,
error: APIError.UNSUPPORTED_URL_SCHEME,
};
res.status(406).json(response);
return;
}
},
);
app.get(
// the public name parameter is optionally given but is not used by the API.
// it's only there for the browser to save/display the file with a custom
// name with a url like
// /api/file/ae62787f-4344-4124-8026-3839543fde70.png/my-pic.png
config.GRAPH_ENDPOINT + "file/:fileId/:publicName*?",
sessionMiddleware,
verifyUser,
async function(req, res) {
try {
const graphId = req.params.graphId;
/** Calculate Size of file */
const size = await Notes.getFileSize(graphId, req.params.fileId);
const range = req.headers.range;
/** Check for Range header */
if (range) {
/** Extracting Start and End value from Range Header */
const [startString, endString] = range.replace(/bytes=/, "")
.split("-");
let start = parseInt(startString, 10);
let end = endString ? parseInt(endString, 10) : size - 1;
if (!isNaN(start) && isNaN(end)) {
// eslint-disable-next-line no-self-assign
start = start;
end = size - 1;
}
if (isNaN(start) && !isNaN(end)) {
start = size - end;
end = size - 1;
}
// Handle unavailable range request
if (start >= size || end >= size) {
// Return the 416 Range Not Satisfiable.
res.writeHead(416, {
"Content-Range": `bytes */${size}`
});
return res.end();
}
const { readable, mimeType }
= await Notes.getReadableFileStream(
graphId,
req.params.fileId,
{ start: start, end: end },
);
readable.on("error", () => {
const response:APIResponse = {
success: false,
error: APIError.FILE_NOT_FOUND,
};
res.json(response);
});
/** Sending Partial Content With HTTP Code 206 */
res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/${size}`,
"Accept-Ranges": "bytes",
"Content-Length": end - start + 1,
"Content-Type": mimeType,
});
readable.pipe(res);
} else { // no range request
const { readable, mimeType }
= await Notes.getReadableFileStream(graphId, req.params.fileId);
readable.on("error", () => {
const response:APIResponse = {
success: false,
error: APIError.FILE_NOT_FOUND,
};
res.json(response);
});
res.writeHead(200, {
"Content-Length": size,
"Content-Type": mimeType
});
readable.pipe(res);
}
} catch (e) {
const response:APIResponse = {
success: false,
error: e.message,
};
res.json(response);
}
},
);
app.get(
config.GRAPH_ENDPOINT + "files",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const graphId = req.params.graphId;
const files = await Notes.getFiles(graphId);
const response:APIResponse = {
payload: files,
success: true,
};
res.json(response);
},
);
app.get(
config.GRAPH_ENDPOINT + "url-metadata",
sessionMiddleware,
verifyUser,
async (req, res) => {
const url = req.query.url;
try {
const metadata = await Notes.getUrlMetadata(url as string);
const response:APIResponse = {
success: true,
payload: metadata,
};
res.json(response);
} catch (e) {
logger.verbose("Error while getting URL metadata");
logger.verbose(JSON.stringify(e));
const response:APIResponse = {
"success": false,
"error": e.message,
};
res.json(response);
}
},
);
app.put(
config.GRAPH_ENDPOINT + "pins",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const graphId = req.params.graphId;
const reqBody = req.body;
const noteId = reqBody.noteId;
const pinnedNotes = await Notes.pin(graphId, noteId);
const response:APIResponse = {
payload: pinnedNotes,
success: true,
};
res.json(response);
},
);
app.delete(
config.GRAPH_ENDPOINT + "pins",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const graphId = req.params.graphId;
const reqBody = req.body;
const noteId = reqBody.noteId;
const pinnedNotes = await Notes.unpin(graphId, noteId);
const response:APIResponse = {
payload: pinnedNotes,
success: true,
};
res.json(response);
},
);
app.get(
config.GRAPH_ENDPOINT + "pins",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const graphId = req.params.graphId;
const pinnedNotes = await Notes.getPins(graphId);
const response:APIResponse = {
payload: pinnedNotes,
success: true,
};
res.json(response);
},
);
app.post(
config.USER_ENDOPINT + "logout",
sessionMiddleware,
verifyUser,
express.json(),
async function(req, res) {
const response:APIResponse = {
success: true,
};
logger.verbose(`Logout: ${req.userId}`);
await new Promise((resolve, reject) => {
req.session.destroy(function(err) {
if (err) {
reject(err);
} else {
resolve(null);
}
})
})
return res
.status(200)
.clearCookie(
sessionCookieName,
)
.json(response);
},
);
/* ***************
Endpoints with NO authentication required
*****************/
app.get(config.API_PATH, function(req, res) {
const response:APIResponse = {
success: true,
payload: "Hello world!",
}
res.json(response);
});
const handleUnsuccessfulLoginAttempt = (req, res) => {
logger.verbose("Unsuccessful login attempt");
logger.verbose(`User: ${req.body.username}`);
logger.verbose(`Password: ${req.body.password}`);
logger.verbose(`MFA Token: ${req.body.mfaToken}`);
logger.verbose(`IP: ${req.socket.remoteAddress}`);
bruteForcePreventer.unsuccessfulLogin(req.socket.remoteAddress);
const response:APIResponse = {
success: false,
error: APIError.INVALID_CREDENTIALS,
};
return res.status(401).json(response);
}
app.post(
config.USER_ENDOPINT + 'login',
sessionMiddleware,
express.json(),
(req, res) => {
if (!bruteForcePreventer.isLoginAttemptLegit(req.socket.remoteAddress)) {
logger.verbose(
`Login request denied due to brute force prevention. IP: ${req.socket.remoteAddress}`
);
const response:APIResponse = {
success: false,
error: APIError.TOO_EARLY,
};
return res.status(425).json(response);
}
// read username and password from request body
const submittedUsername = req.body.username;
const submittedPassword = req.body.password;
const submittedMfaToken = req.body.mfaToken;
if (
(!submittedUsername)
|| (!submittedPassword)
|| (!submittedMfaToken)
) {
return handleUnsuccessfulLoginAttempt(req, res);
}
const user = users.find((user) => {
return user.login === submittedUsername;
});
if (!user) {
return handleUnsuccessfulLoginAttempt(req, res);
}
const mfaTokenIsValid
= twofactor.verifyToken(
user.mfaSecret,
submittedMfaToken,
)?.delta === 0;
if (!mfaTokenIsValid) {
return handleUnsuccessfulLoginAttempt(req, res);
}
const passwordIsValid
= bcrypt.compareSync(submittedPassword, user.passwordHash);
if (!passwordIsValid) {
return handleUnsuccessfulLoginAttempt(req, res);
}
// this modification of the session object initializes the session and
// makes express-session set the cookie
req.session.userId = user.login;
req.session.userAgent = req.headers["user-agent"];
req.session.userPlatform = req.headers["sec-ch-ua-platform"];
logger.verbose(
`Successful login: ${req.session.userId} IP: ${req.socket.remoteAddress}`,
);
bruteForcePreventer.successfulLogin(req.socket.remoteAddress);
const response:APIResponse = {
success: true,
payload: {
graphIds: user.graphIds,
},
};
return res.status(200).json(response);
},
);
app.use(
fallback(
'index.html',
{
root: path.resolve(frontendPath),
},
),
);
return app;
};
export default startApp; | the_stack |
import {Watcher, RawMap, RawValue, RawEAV} from "./watcher";
import {v4 as uuid} from "uuid";
export interface Attrs extends RawMap<RawValue|RawValue[]|RawEAV[]> {}
export class UIWatcher extends Watcher {
protected static _addAttrs(id:string, attrs?: Attrs, eavs:RawEAV[] = []) {
if(attrs) {
for(let attr in attrs) {
if(attrs[attr].constructor !== Array) {
eavs.push([id, attr, attrs[attr] as RawValue]);
} else {
let vals = attrs[attr] as RawValue[] | RawEAV[];
// We have a nested sub-object (i.e. a set of EAVs).
if(vals[0].constructor === Array) {
let childEAVs:RawEAV[] = vals as any;
let [childId] = childEAVs[0];
eavs.push([id, attr, childId]);
for(let childEAV of childEAVs) {
eavs.push(childEAV);
}
} else {
for(let val of vals as RawValue[]) {
eavs.push([id, attr, val]);
}
}
}
}
}
return eavs;
}
protected static $elem(tag:string, attrs?: Attrs) {
let id = uuid();
let eavs:RawEAV[] = [
[id, "tag", tag],
];
UIWatcher._addAttrs(id, attrs, eavs);
return eavs;
}
protected static _makeContainer(tag:string) {
function $container(children: RawEAV[][]):RawEAV[];
function $container(attrs: Attrs, children: RawEAV[][]):RawEAV[];
function $container(attrsOrChildren?: Attrs|RawEAV[][], maybeChildren?: RawEAV[][]):RawEAV[] {
let attrs:Attrs|undefined;
let children:RawEAV[][];
if(maybeChildren) {
attrs = attrsOrChildren as Attrs|undefined;
children = maybeChildren;
} else {
children = attrsOrChildren as RawEAV[][];
}
let eavs = UIWatcher.$elem(tag, attrs);
let [id] = eavs[0];
for(let child of children) {
let [childId] = child[0];
eavs.push([id, "children", childId]);
for(let childEAV of child) {
eavs.push(childEAV);
}
}
return eavs;
}
return $container;
}
public static helpers = {
$style: (attrs?: Attrs) => {
return UIWatcher._addAttrs(uuid(), attrs);
},
$elem: UIWatcher.$elem,
$text: (text:RawValue, attrs?: Attrs) => {
let eavs = UIWatcher.$elem("ui/text", attrs);
let [id] = eavs[0];
eavs.push([id, "text", text]);
return eavs;
},
$button: (attrs?: Attrs) => {
return UIWatcher.$elem("ui/button", attrs);
},
$row: UIWatcher._makeContainer("ui/row"),
$column: UIWatcher._makeContainer("ui/column"),
}
public helpers = UIWatcher.helpers;
setup() {
this.program.attach("html");
this.program
// Containers
.bind("Decorate row elements as html.", ({find, record}) => {
let elem = find("ui/row");
return [elem.add("tag", "html/element").add("tagname", "row")];
})
.bind("Decorate column elements as html.", ({find, record}) => {
let elem = find("ui/column");
return [elem.add("tag", "html/element").add("tagname", "column")];
})
.bind("Decorate spacer elements as html.", ({find, record}) => {
let elem = find("ui/spacer");
return [elem.add("tag", "html/element").add("tagname", "spacer")];
})
.bind("Decorate input elements as html.", ({find, record}) => {
let elem = find("ui/input");
return [elem.add("tag", "html/element").add("tagname", "input")];
})
.bind("Decorate text elements as html.", ({find, record}) => {
let elem = find("ui/text");
return [elem.add("tag", "html/element").add("tagname", "text")];
})
.bind("Decorate a elements as html.", ({find, record}) => {
let elem = find("ui/a");
return [elem.add("tag", "html/element").add("tagname", "a")];
})
.bind("Decorate style elements as html.", ({find, record}) => {
let elem = find("ui/style");
return [elem.add("tag", "html/element").add("tagname", "style")];
})
.bind("Decorate link elements as html.", ({find, record}) => {
let elem = find("ui/link");
return [elem.add("tag", "html/element").add("tagname", "link")];
})
.bind("Decorate div elements as html.", ({find, record}) => {
let elem = find("ui/div");
return [elem.add("tag", "html/element").add("tagname", "div")];
})
.bind("Decorate span elements as html.", ({find, record}) => {
let elem = find("ui/span");
return [elem.add("tag", "html/element").add("tagname", "span")];
})
.bind("Decorate img elements as html.", ({find, record}) => {
let elem = find("ui/img");
return [elem.add("tag", "html/element").add("tagname", "img")];
})
.bind("Decorate h1 elements as html.", ({find, record}) => {
let elem = find("ui/h1");
return [elem.add("tag", "html/element").add("tagname", "h1")];
})
.bind("Decorate h2 elements as html.", ({find, record}) => {
let elem = find("ui/h2");
return [elem.add("tag", "html/element").add("tagname", "h2")];
})
.bind("Decorate h3 elements as html.", ({find, record}) => {
let elem = find("ui/h3");
return [elem.add("tag", "html/element").add("tagname", "h3")];
})
.bind("Decorate ul elements as html.", ({find, record}) => {
let elem = find("ui/ul");
return [elem.add("tag", "html/element").add("tagname", "ul")];
})
.bind("Decorate ol elements as html.", ({find, record}) => {
let elem = find("ui/ol");
return [elem.add("tag", "html/element").add("tagname", "ol")];
})
.bind("Decorate li elements as html.", ({find, record}) => {
let elem = find("ui/li");
return [elem.add("tag", "html/element").add("tagname", "li")];
});
// Buttons
this.program
.bind("Decorate button elements as html.", ({find, record}) => {
let elem = find("ui/button");
return [elem.add("tag", "html/element").add("tagname", "div").add("class", "button")];
})
.bind("Decorate button elements with icons.", ({find, record}) => {
let elem = find("ui/button");
return [elem.add("class", "iconic").add("class", `ion-${elem.icon}`)];
});
//--------------------------------------------------------------------
// Field Table
//--------------------------------------------------------------------
this.program
.bind("Decorate field tables as html.", ({find, record}) => {
let elem = find("ui/field-table");
return [elem.add({tag: "html/element", tagname: "table", cellspacing: 0})];
})
.bind("Field tables have a value_row for each AV pair in their fields.", ({find, choose, record}) => {
let table = find("ui/field-table");
let {field} = table;
let {attribute, value} = field;
let [editable] = choose(() => { field.editable == "value"; return "true"; }, () => "false");
return [table.add("value_row", [
record({field, attribute, value})
.add("editable", editable)
])];
})
.bind("If a table is editable: all attach each specific editing mode.", ({find, choose}) => {
let table = find("ui/field-table", "ui/editable");
return [table.add("editable", [
// Modify existing
"value",
"attribute",
// Create new,
"row",
"field"
])];
})
.bind("A table's fields inherit the editing mode of their table if they don't specify their own.", ({find, choose}) => {
let table = find("ui/field-table");
let {field} = table;
let [editable] = choose(() => field.editable, () => table.editable);
return [field.add("editable", editable)];
})
.bind("Create a row for each unique field.", ({find, choose, record}) => {
let table = find("ui/field-table");
let {field} = table;
return [
table.add("children", [
record("ui/field-table/row", {table, field})
])
];
})
.commit("If a field is row editable, add value_rows for the field when no empty ones exist.", ({find, not, gather, choose, record}) => {
let table = find("ui/field-table");
let {field} = table;
field.editable == "row";
not(() => find("ui/field-table/cell", {table, field, column: "value", value: ""}))
let [count] = choose(() => {
let cell = find("ui/field-table/cell", {field});
return gather(cell).per(field).count() + 1;
}, () => 1);
return [
table.add("value_row", [
record("ui/field-table/value-row/new", {sort: `zz${count}`, field, attribute: field.attribute, value: ""})
.add("editable", "true")
])
];
})
.commit("If a field is row editable, clear any excess empty rows.", ({find, record}) => {
let table = find("ui/field-table");
let {field} = table;
field.editable == "row";
let cell = find("ui/field-table/cell", {table, field, column: "value", value: ""});
let other = find("ui/field-table/cell", {table, field, column: "value", value: ""});
other.sort > cell.sort;
return [other.value_row.remove()];
})
.commit("If a table is field editable, add a field when no empty ones exist.", ({find, not, gather, choose, record}) => {
let table = find("ui/field-table", {editable: "field"});
not(() => find("ui/field-table/attribute", {table, column: "attribute", value: ""}))
let [count] = choose(() => {
table == find("ui/field-table"); // @FIXME: Hackaround aggregate bug.
return gather(table.field).per(table).count() + 1;
}, () => 1);
return [
table.add("field", [
record("ui/field-table/field/new", {sort: `zz${count}`, attribute: "", value: ""})
.add("editable", table.editable)
.add("editable", ["attribute", "value"])
])
];
})
.commit("If a table is field editable, clear any excess empty fields.", ({find, lookup, not, choose, record}) => {
let table = find("ui/field-table", {editable: "field"});
let table_alias = find("ui/field-table", {editable: "field"});
table == table_alias;
// Two new fields exist
let field = find("ui/field-table/field/new");
let other_field = find("ui/field-table/field/new");
// In the same table
table.field == field;
table_alias.field == other_field;
// Both are empty
not(() => table.change.field == field);
not(() => table_alias.change.field == other_field);
// And the other is before this one.
other_field.sort < field.sort;
return [field.remove()];
})
.bind("Each field row has an attribute and a value set.", ({find, choose, record}) => {
let field_row = find("ui/field-table/row");
let {table, field} = field_row;
let [sort] = choose(() => field.sort, () => field.attribute, () => 1);
let [editable] = choose(() => { field.editable == "attribute"; return "true" }, () => "false");
return [
field_row.add({tag: "html/element", tagname: "tr", sort}).add("children", [
record("html/element", {sort: 1, tagname: "td", table, field}).add("children", [
record("ui/field-table/attribute", "ui/field-table/cell", {table, field, value_row: field, column: "attribute"})
.add("editable", editable)
]),
record("html/element", {sort: 2, tagname: "td", table, field}).add("children", [
record("ui/field-table/value-set", "ui/column", {table, field})
])
])
];
})
.bind("Create a value for each field value in the value set.", ({find, choose, record}) => {
let value_set = find("ui/field-table/value-set");
let {table, field} = value_set;
let {value_row} = table;
value_row.field == field;
let {value, editable} = value_row;
let [sort] = choose(() => value_row.sort, () => value);
return [
value_set.add("children", [
record("ui/field-table/value", "ui/field-table/cell", {sort, table, field, value_row, column: "value", editable}),
])
];
})
.bind("The initial value of a cell is pulled off it's value_row or field.", ({find, choose, not, lookup, record}) => {
let cell = find("ui/field-table/cell");
let {field, value_row, column} = cell;
let {attribute, value:initial} = lookup(value_row);
attribute == column;
return [cell.add("initial", initial)]
})
.bind("Draw field cells as text if they're not editable.", ({find}) => {
let cell = find("ui/field-table/cell", {editable: "false"});
let {field, column, initial} = cell;
return [cell.add({tag: "ui/text", text: initial})];
})
.bind("Draw field cells as inputs when they're editable.", ({find}) => {
let cell = find("ui/field-table/cell", {editable: "true"});
let {field, column, initial} = cell;
return [cell.add({tag: ["ui/input", "html/autosize-input"], placeholder: `${column}...`})];
})
.bind("When a cell changes value, update the tables changes list.", ({find, lookup, record}) => {
let cell = find("ui/field-table/cell");
let {table, field, column, value, value_row, initial} = cell;
field.editable == column;
value != initial;
return [table.add("change", [
record("ui/field-change", {field}).add("cell", [
record({column, initial, value})
])
])];
})
this.autocomplete();
}
//--------------------------------------------------------------------
// Autocomplete
//--------------------------------------------------------------------
autocomplete() {
this.program
.bind("Decorate autocompletes.", ({find, record}) => {
let autocomplete = find("ui/autocomplete");
return [
autocomplete.add({tag: "ui/column"}).add("children", [
record("ui/autocomplete/input", "ui/input", {sort: 1, autocomplete})
])
];
})
.bind("Copy input placeholder.", ({find}) => {
let input = find("ui/autocomplete/input");
return [input.add({placeholder: input.autocomplete.placeholder})];
})
.bind("Copy input initial.", ({find}) => {
let input = find("ui/autocomplete/input");
return [input.add({initial: input.autocomplete.initial})];
})
.bind("Copy trigger focus.", ({find}) => {
let autocomplete = find("ui/autocomplete", "html/trigger/focus");
let input = find("ui/autocomplete/input", {autocomplete});
return [input.add({tag: "html/trigger/focus"})];
})
.bind("Copy autosize input.", ({find}) => {
let autocomplete = find("ui/autocomplete", "html/autosize-input");
let input = find("ui/autocomplete/input", {autocomplete});
return [input.add({tag: "html/autosize-input"})];
})
.bind("An autocompletes value is it's input's.", ({find, choose}) => {
let input = find("ui/autocomplete/input");
let [value] = choose(() => input.value, () => "");
return [input.autocomplete.add("value", value)];
})
.commit("If an autocomplete's value disagrees with it's selected, clear the selected.", ({find}) => {
let autocomplete = find("ui/autocomplete");
let {selected, value} = autocomplete;
selected.text != value;
return [autocomplete.remove("selected")];
})
.bind("Completions that match the current input value are matches.", ({find, lib:{string}}) => {
let autocomplete = find("ui/autocomplete");
let {value, completion} = autocomplete;
let ix = string["index-of"](string.lowercase(completion.text), string.lowercase(value));
return [autocomplete.add("match", completion)];
})
.bind("Matches are sorted by length.", ({find, lib:{string}}) => {
let autocomplete = find("ui/autocomplete");
let {match} = autocomplete;
let sort = string["codepoint-length"](match.text);
return [match.add("sort", sort)];
})
.bind("Show the matches in a popout beneath the input.", ({find, lookup, record}) => {
let autocomplete = find("ui/autocomplete");
let {match} = autocomplete;
let {attribute, value} = lookup(match);
attribute != "tag";
return [
autocomplete.add("children", [
record("ui/autocomplete/matches", "ui/column", {sort: 2, autocomplete}).add("children", [
record("ui/autocomplete/match", "ui/text", {autocomplete, match, sort: match.sort}).add(attribute, value)
])
])
];
});
//--------------------------------------------------------------------
// Autocomplete Interaction
//--------------------------------------------------------------------
this.program
.commit("Clicking a match updates the selected and value of the autocomplete.", ({find, record}) => {
let ui_match = find("ui/autocomplete/match");
find("html/event/mouse-down", {element: ui_match});
let {autocomplete, match} = ui_match;
return [
record("ui/event/select", {autocomplete, selected: match}),
];
})
.commit("Focusing an autocomplete input opens the autocomplete.", ({find, record}) => {
let input = find("ui/autocomplete/input");
find("html/event/focus", {element: input});
return [record("ui/event/open", {autocomplete: input.autocomplete})];
})
.commit("Blurring an autocomplete input closes the autocomplete.", ({find, record}) => {
let input = find("ui/autocomplete/input");
find("html/event/blur", {element: input});
return [record("ui/event/close", {autocomplete: input.autocomplete})];
})
.commit("If the value matches perfectly on blur, select that match.", ({find, lib:{string}, record}) => {
let input = find("ui/autocomplete/input");
let {value} = find("html/event/blur", {element: input});
let {autocomplete} = input;
let {match} = autocomplete;
string.lowercase(match.text) == string.lowercase(value);
return [record("ui/event/select", {autocomplete, selected: match})];
})
.commit("Pressing escape in an open autocomplete closes it.", ({find, not, record}) => {
let autocomplete = find("ui/autocomplete", {open: "true"});
find("html/event/key-down", {key: "escape", element: autocomplete});
return [record("ui/event/close", {autocomplete})];
})
.commit("Pressing enter in an open autocomplete submits it.", ({find, record}) => {
let autocomplete = find("ui/autocomplete", {open: "true"});
find("html/event/key-down", {key: "enter", element: autocomplete});
return [
record("ui/event/submit", {autocomplete}),
record("ui/event/close", {autocomplete})
];
})
.commit("Pressing tab in an open autocomplete selects the top match.", ({find, gather, record}) => {
let autocomplete = find("ui/autocomplete", {open: "true"});
find("html/event/key-down", {key: "tab", element: autocomplete});
let {match} = autocomplete;
1 == gather(match.sort).per(autocomplete).sort();
return [
record("ui/event/select", {autocomplete, selected: match}),
record("ui/event/close", {autocomplete})
];
})
//--------------------------------------------------------------------
// Autocomplete Events
//--------------------------------------------------------------------
this.program
.commit("Clear the specified autocomplete.", ({find}) => {
let event = find("ui/event/clear");
let {autocomplete} = event;
let input = find("ui/autocomplete/input", {autocomplete});
return [
input.remove("value"),
event.remove()
];
})
.commit("When an autocomplete is opened, store it's previous value.", ({find, choose, record}) => {
let event = find("ui/event/open");
let {autocomplete} = event;
let input = find("ui/autocomplete/input", {autocomplete});
let [value] = choose(() => autocomplete.previous, () => autocomplete.value, () => "");
return [
autocomplete.remove("open").add({open: "true", previous: value}),
input.remove("tag", "html/trigger/blur"),
event.remove()
];
})
.commit("When an autocomplete is closed, erase it's previous value.", ({find, choose, record}) => {
let event = find("ui/event/close");
let {autocomplete} = event;
let input = find("ui/autocomplete/input", {autocomplete});
return [
autocomplete.remove("open").remove("previous"),
input.add("tag", "html/trigger/blur"),
autocomplete.remove("tag", "html/trigger/focus"),
event.remove()
];
})
.commit("When an autocomplete is closed, and it's value is changed, emit a change event.", ({find, choose, record}) => {
let event = find("ui/event/close");
let {autocomplete} = event;
autocomplete.value != autocomplete.previous;
return [
record("ui/event/change", {autocomplete, value: autocomplete.value})
];
})
.commit("Selecting a completion updates the autocomplete.", ({find, record}) => {
let event = find("ui/event/select");
let {autocomplete, selected} = event;
let input = find("ui/autocomplete/input", {autocomplete});
return [
input.remove("value").add("value", selected.text),
autocomplete.remove("selected").add("selected", selected),
event.remove()
];
})
.commit("When a selection is made and it's different from the previous value, emit a change event.", ({find, record}) => {
let event = find("ui/event/select");
let {autocomplete, selected} = event;
selected.text != autocomplete.previous;
return [
record("ui/event/change", {autocomplete, value: selected.text})
];
})
.commit("Clear the autocomplete change event.", ({find, record}) => {
let event = find("ui/event/change");
let {autocomplete} = event;
return [event.remove()];
})
}
}
Watcher.register("ui", UIWatcher); | the_stack |
import { HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Feed, FeedDocument, FeedModel } from './entities/feed.entity';
import { DetailedFeed } from './types/detailed-feed.type';
import { Types, FilterQuery } from 'mongoose';
import _ from 'lodash';
import { FailRecord, FailRecordModel } from './entities/fail-record.entity';
import { FeedStatus } from './types/FeedStatus.type';
import dayjs from 'dayjs';
import { FeedSchedulingService } from './feed-scheduling.service';
import { DiscordAPIService } from '../../services/apis/discord/discord-api.service';
import { ConfigService } from '@nestjs/config';
import { CloneFeedInputProperties } from './dto/CloneFeedInput.dto';
import {
FeedSubscriber,
FeedSubscriberModel,
} from './entities/feed-subscriber.entity';
import { FeedFetcherService } from '../../services/feed-fetcher/feed-fetcher.service';
import logger from '../../utils/logger';
import { DiscordAuthService } from '../discord-auth/discord-auth.service';
import { DiscordAPIError } from '../../common/errors/DiscordAPIError';
import {
BannedFeedException,
FeedLimitReachedException,
MissingChannelException,
MissingChannelPermissionsException,
UserMissingManageGuildException,
} from './exceptions';
import { SupportersService } from '../supporters/supporters.service';
import { BannedFeed, BannedFeedModel } from './entities/banned-feed.entity';
import { DiscordGuildChannel } from '../../common';
import { DiscordPermissionsService } from '../discord-auth/discord-permissions.service';
import {
SEND_CHANNEL_MESSAGE,
VIEW_CHANNEL,
} from '../discord-auth/constants/permissions';
import {
FeedFilteredFormat,
FeedFilteredFormatModel,
} from './entities/feed-filtered-format.entity';
interface UpdateFeedInput {
title?: string;
text?: string;
filters?: Record<string, string[]>;
checkTitles?: boolean;
checkDates?: boolean;
imgPreviews?: boolean;
imgLinksExistence?: boolean;
formatTables?: boolean;
splitMessage?: boolean;
channelId?: string;
webhook?: {
id?: string;
name?: string;
iconUrl?: string;
token?: string;
};
ncomparisons?: string[];
pcomparisons?: string[];
}
interface PopulatedFeed extends Feed {
failRecord?: FailRecord;
}
@Injectable()
export class FeedsService {
constructor(
@InjectModel(Feed.name) private readonly feedModel: FeedModel,
@InjectModel(FailRecord.name) private readonly failRecord: FailRecordModel,
@InjectModel(BannedFeed.name)
private readonly bannedFeedModel: BannedFeedModel,
@InjectModel(FeedSubscriber.name)
private readonly feedSubscriberModel: FeedSubscriberModel,
@InjectModel(FeedFilteredFormat.name)
private readonly feedFilteredFormatModel: FeedFilteredFormatModel,
private readonly feedSchedulingService: FeedSchedulingService,
private readonly feedFetcherSevice: FeedFetcherService,
private readonly discordApiService: DiscordAPIService,
private readonly configService: ConfigService,
private readonly discordAuthService: DiscordAuthService,
private readonly supportersService: SupportersService,
private readonly discordPermissionsService: DiscordPermissionsService,
) {}
async addFeed(
userAccessToken: string,
{
title,
url,
channelId,
isFeedV2,
}: {
title: string;
url: string;
channelId: string;
isFeedV2: boolean;
},
) {
let channel: DiscordGuildChannel;
try {
channel = await this.discordApiService.getChannel(channelId);
} catch (err) {
logger.info(`Error while getting channel ${channelId} of feed addition`, {
stack: err.stack,
});
if (err instanceof DiscordAPIError) {
if (err.statusCode === HttpStatus.NOT_FOUND) {
throw new MissingChannelException();
}
if (err.statusCode === HttpStatus.FORBIDDEN) {
throw new MissingChannelPermissionsException();
}
}
throw err;
}
const userManagesGuild = await this.discordAuthService.userManagesGuild(
userAccessToken,
channel.guild_id,
);
if (!userManagesGuild) {
logger.info(
`Blocked user from adding feed to guild ${channel.guild_id} ` +
`due to missing manage permissions`,
);
throw new UserMissingManageGuildException();
}
const remainingAvailableFeeds = await this.getRemainingFeedLimitCount(
channel.guild_id,
);
if (remainingAvailableFeeds <= 0) {
throw new FeedLimitReachedException();
}
await this.feedFetcherSevice.fetchFeed(url, {
fetchOptions: {
useServiceApi: isFeedV2,
useServiceApiCache: false,
},
});
const bannedRecord = await this.getBannedFeedDetails(url, channel.guild_id);
if (bannedRecord) {
throw new BannedFeedException();
}
if (
!(await this.discordPermissionsService.botHasPermissionInChannel(
channel,
[SEND_CHANNEL_MESSAGE, VIEW_CHANNEL],
))
) {
throw new MissingChannelPermissionsException();
}
const created = await this.feedModel.create({
title,
url,
channel: channelId,
guild: channel.guild_id,
});
const withDetails = await this.findFeeds(
{
_id: created._id,
},
{
limit: 1,
skip: 0,
},
);
return withDetails[0];
}
async removeFeed(feedId: string) {
const feedIdObjectId = new Types.ObjectId(feedId);
await Promise.all([
this.feedModel.deleteOne({
_id: feedIdObjectId,
}),
this.feedSubscriberModel.deleteMany({
feed: feedIdObjectId,
}),
this.feedFilteredFormatModel.deleteMany({
feed: feedIdObjectId,
}),
]);
}
async getFeed(feedId: string): Promise<DetailedFeed | null> {
const feeds = await this.findFeeds(
{
_id: new Types.ObjectId(feedId),
},
{
limit: 1,
skip: 0,
},
);
const matchedFeed = feeds[0];
if (!matchedFeed) {
return null;
}
return matchedFeed;
}
async getServerFeeds(
serverId: string,
options: {
search?: string;
limit: number;
offset: number;
},
): Promise<DetailedFeed[]> {
const feeds = await this.findFeeds(
{
guild: serverId,
},
{
search: options.search,
limit: options.limit,
skip: options.offset,
},
);
return feeds;
}
async countServerFeeds(
serverId: string,
options?: {
search?: string;
},
): Promise<number> {
const query: FilterQuery<Feed> = {
guild: serverId,
};
if (options?.search) {
query.$or = [
{
title: new RegExp(_.escapeRegExp(options.search), 'i'),
},
{
url: new RegExp(_.escapeRegExp(options.search), 'i'),
},
];
}
return this.feedModel.countDocuments(query);
}
async updateOne(
feedId: string | Types.ObjectId,
input: UpdateFeedInput,
): Promise<DetailedFeed> {
const existingFeed = await this.feedModel.findById(feedId).lean();
if (!existingFeed) {
throw new Error(`Feed ${feedId} not found while attempting to update`);
}
const strippedUpdateObject: UpdateFeedInput = _.omitBy(
input,
_.isUndefined,
);
const webhookUpdates = this.getUpdateWebhookObject(
existingFeed.webhook,
input,
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updateObject: Record<string, any> = {
$set: {
...webhookUpdates.$set,
},
$unset: {
...webhookUpdates.$unset,
},
};
if (strippedUpdateObject.text != null) {
updateObject.$set.text = strippedUpdateObject.text;
}
if (strippedUpdateObject.filters) {
updateObject.$set.filters = strippedUpdateObject.filters;
}
if (strippedUpdateObject.title) {
updateObject.$set.title = strippedUpdateObject.title;
}
if (strippedUpdateObject.checkTitles != null) {
updateObject.$set.checkTitles = strippedUpdateObject.checkTitles;
}
if (strippedUpdateObject.checkDates != null) {
updateObject.$set.checkDates = strippedUpdateObject.checkDates;
}
if (strippedUpdateObject.imgPreviews != null) {
updateObject.$set.imgPreviews = strippedUpdateObject.imgPreviews;
}
if (strippedUpdateObject.imgLinksExistence != null) {
updateObject.$set.imgLinksExistence =
strippedUpdateObject.imgLinksExistence;
}
if (strippedUpdateObject.formatTables != null) {
updateObject.$set.formatTables = strippedUpdateObject.formatTables;
}
if (strippedUpdateObject.splitMessage != null) {
updateObject.$set.split = {
enabled: strippedUpdateObject.splitMessage,
};
}
if (strippedUpdateObject.ncomparisons) {
updateObject.$set.ncomparisons = strippedUpdateObject.ncomparisons;
}
if (strippedUpdateObject.pcomparisons) {
updateObject.$set.pcomparisons = strippedUpdateObject.pcomparisons;
}
if (strippedUpdateObject.channelId) {
await this.checkFeedGuildChannelIsValid(
existingFeed.guild,
strippedUpdateObject.channelId,
);
updateObject.$set.channel = strippedUpdateObject.channelId;
}
await this.feedModel.updateOne(
{
_id: feedId,
},
updateObject,
);
const foundFeeds = await this.findFeeds(
{
_id: new Types.ObjectId(feedId),
},
{
limit: 1,
skip: 0,
},
);
return foundFeeds[0];
}
async refresh(feedId: string | Types.ObjectId): Promise<DetailedFeed> {
const feed = await this.feedModel.findById(feedId).lean();
if (!feed) {
throw new Error(`Feed ${feedId} does not exist`);
}
await this.feedFetcherSevice.fetchFeed(feed.url, {
fetchOptions: {
useServiceApi: feed.isFeedv2 || false,
useServiceApiCache: false,
},
});
await this.failRecord.deleteOne({ _id: feed.url });
const feeds = await this.findFeeds(
{
_id: new Types.ObjectId(feedId),
},
{
limit: 1,
skip: 0,
},
);
return feeds[0];
}
async findFeeds(
filter: FilterQuery<FeedDocument>,
options: {
search?: string;
limit: number;
skip: number;
},
): Promise<DetailedFeed[]> {
const match = {
...filter,
};
if (options.search) {
match.$or = [
{
title: new RegExp(_.escapeRegExp(options.search), 'i'),
},
{
url: new RegExp(_.escapeRegExp(options.search), 'i'),
},
];
}
const feeds: PopulatedFeed[] = await this.feedModel.aggregate([
{
$match: match,
},
{
$sort: {
addedAt: -1,
},
},
{
$skip: options.skip,
},
{
$limit: options.limit,
},
{
$lookup: {
from: 'fail_records',
localField: 'url',
foreignField: '_id',
as: 'failRecord',
},
},
{
$addFields: {
failRecord: {
$first: '$failRecord',
},
},
},
]);
const refreshRates =
await this.feedSchedulingService.getRefreshRatesOfFeeds(
feeds.map((feed) => ({
_id: feed._id.toHexString(),
guild: feed.guild,
url: feed.url,
})),
);
const withStatuses = feeds.map((feed, index) => {
let feedStatus: FeedStatus;
if (this.isValidFailRecord(feed.failRecord || null)) {
feedStatus = FeedStatus.FAILED;
} else if (feed.failRecord) {
feedStatus = FeedStatus.FAILING;
} else if (feed.disabled) {
feedStatus = FeedStatus.DISABLED;
} else {
feedStatus = FeedStatus.OK;
}
return {
...feed,
status: feedStatus,
failReason: feed.failRecord?.reason,
disabledReason: feed.disabled,
refreshRateSeconds: refreshRates[index],
};
});
withStatuses.forEach((feed) => {
delete feed.failRecord;
});
return withStatuses;
}
async allFeedsBelongToGuild(feedIds: string[], guildId: string) {
const foundCount = await this.feedModel.countDocuments({
_id: {
$in: feedIds.map((id) => new Types.ObjectId(id)),
},
guild: guildId,
});
return foundCount === feedIds.length;
}
async cloneFeed(
sourceFeed: Feed,
targetFeedIds: string[],
properties: CloneFeedInputProperties[],
) {
const propertyMap: Partial<
Record<CloneFeedInputProperties, (keyof Feed)[]>
> = {
COMPARISONS: ['ncomparisons', 'pcomparisons'],
FILTERS: ['filters', 'rfilters'],
MESSAGE: ['text', 'embeds'],
MISC_OPTIONS: [
'checkDates',
'checkTitles',
'imgPreviews',
'imgLinksExistence',
'formatTables',
'split',
],
WEBHOOK: ['webhook'],
REGEXOPS: ['regexOps'],
};
const toUpdate = {
$set: {} as Record<keyof Feed, unknown>,
};
for (const property of properties) {
const propertyKeys = propertyMap[property];
if (propertyKeys) {
for (const key of propertyKeys) {
toUpdate.$set[key] = sourceFeed[key];
}
}
}
if (properties.includes(CloneFeedInputProperties.SUBSCRIBERS)) {
await this.cloneSubscribers(sourceFeed._id.toHexString(), targetFeedIds);
}
await this.feedModel.updateMany(
{
_id: {
$in: targetFeedIds.map((id) => new Types.ObjectId(id)),
},
},
toUpdate,
);
const foundFeeds = await this.findFeeds(
{
_id: {
$in: targetFeedIds.map((id) => new Types.ObjectId(id)),
},
},
{
limit: targetFeedIds.length,
skip: 0,
},
);
return foundFeeds;
}
async getBannedFeedDetails(url: string, guildId: string) {
return this.bannedFeedModel.findOne({
url: url,
$or: [
{
guildIds: guildId,
},
{
guildIds: {
$size: 0,
},
},
],
});
}
private async checkFeedGuildChannelIsValid(
guildId: string,
channelId: string,
) {
let channel: DiscordGuildChannel;
try {
channel = await this.discordApiService.getChannel(channelId);
} catch (err) {
logger.info(
`Skipped updating feed channel because failed to get channel`,
{
stack: err.stack,
},
);
if (err instanceof DiscordAPIError) {
if (err.statusCode === HttpStatus.NOT_FOUND) {
throw new MissingChannelException();
}
if (err.statusCode === HttpStatus.FORBIDDEN) {
throw new MissingChannelPermissionsException();
}
}
throw err;
}
if (channel.guild_id !== guildId) {
throw new MissingChannelPermissionsException();
}
const hasPermissionInChannel =
await this.discordPermissionsService.botHasPermissionInChannel(channel, [
VIEW_CHANNEL,
SEND_CHANNEL_MESSAGE,
]);
if (!hasPermissionInChannel) {
throw new MissingChannelPermissionsException();
}
}
private getUpdateWebhookObject(
existingFeedWebhook: Feed['webhook'],
updateObject: UpdateFeedInput,
) {
if (updateObject.webhook?.id === '') {
return {
$set: {},
$unset: {
webhook: '',
},
};
}
const toSet = {
$set: {
webhook: {} as Record<string, unknown>,
},
$unset: {},
};
if (typeof updateObject.webhook?.id === 'string') {
toSet.$set.webhook.id = updateObject.webhook.id;
if (typeof updateObject.webhook?.token === 'string') {
toSet.$set.webhook.url =
`https://discord.com/api/v9/webhooks/${updateObject.webhook.id}` +
`/${updateObject.webhook.token}`;
}
}
if (typeof updateObject.webhook?.name === 'string') {
toSet.$set.webhook.name = updateObject.webhook.name;
}
if (typeof updateObject.webhook?.iconUrl === 'string') {
toSet.$set.webhook.avatar = updateObject.webhook.iconUrl;
}
if (Object.keys(toSet.$set.webhook).length === 0) {
return {
$set: {},
$unset: {},
};
}
toSet.$set.webhook = {
...(existingFeedWebhook || {}),
...toSet.$set.webhook,
};
return toSet;
}
private async getRemainingFeedLimitCount(guildId: string) {
const [benefits] = await this.supportersService.getBenefitsOfServers([
guildId,
]);
const currentTotalFeeds = await this.feedModel.countDocuments({
guild: guildId,
});
return benefits.maxFeeds - currentTotalFeeds;
}
private async cloneSubscribers(
sourceFeedId: string,
targetFeedIds: string[],
) {
const subscribers: FeedSubscriber[] = await this.feedSubscriberModel
.find({
feed: new Types.ObjectId(sourceFeedId),
})
.lean();
const toInsert = targetFeedIds
.map((targetFeedId) => {
return subscribers.map((subscriber) => ({
...subscriber,
_id: new Types.ObjectId(),
feed: new Types.ObjectId(targetFeedId),
}));
})
.flat();
// Ideally this should use transactions, but tests are not set up for it yet
await this.feedSubscriberModel.deleteMany({
feed: {
$in: targetFeedIds.map((id) => new Types.ObjectId(id)),
},
});
await this.feedSubscriberModel.insertMany(toInsert);
}
/**
* See if a fail record should be valid and eligible for a refresh. If a fail record is invalid,
* then it's still on cycle.
*
* @param failRecord The fail record to check
* @param requiredLifetimeHours How long the fail record should be in the database to consider
* feeds as failures. Hardcoded as 18 for now to match the config until a separate service is
* ready to handle fail records.
* @returns
*/
private isValidFailRecord(
failRecord: FailRecord | null,
requiredLifetimeHours = 18,
) {
if (!failRecord) {
return false;
}
const hoursDiff = dayjs().diff(dayjs(failRecord.failedAt), 'hours');
return hoursDiff >= requiredLifetimeHours;
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/billingAccountsMappers";
import * as Parameters from "../models/parameters";
import { BillingManagementClientContext } from "../billingManagementClientContext";
/** Class representing a BillingAccounts. */
export class BillingAccounts {
private readonly client: BillingManagementClientContext;
/**
* Create a BillingAccounts.
* @param {BillingManagementClientContext} client Reference to the service client.
*/
constructor(client: BillingManagementClientContext) {
this.client = client;
}
/**
* Lists the billing accounts that a user has access to.
* @param [options] The optional parameters
* @returns Promise<Models.BillingAccountsListResponse>
*/
list(options?: Models.BillingAccountsListOptionalParams): Promise<Models.BillingAccountsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.BillingAccountListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: Models.BillingAccountsListOptionalParams, callback: msRest.ServiceCallback<Models.BillingAccountListResult>): void;
list(options?: Models.BillingAccountsListOptionalParams | msRest.ServiceCallback<Models.BillingAccountListResult>, callback?: msRest.ServiceCallback<Models.BillingAccountListResult>): Promise<Models.BillingAccountsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.BillingAccountsListResponse>;
}
/**
* Gets a billing account by its ID.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param [options] The optional parameters
* @returns Promise<Models.BillingAccountsGetResponse>
*/
get(billingAccountName: string, options?: Models.BillingAccountsGetOptionalParams): Promise<Models.BillingAccountsGetResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param callback The callback
*/
get(billingAccountName: string, callback: msRest.ServiceCallback<Models.BillingAccount>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param options The optional parameters
* @param callback The callback
*/
get(billingAccountName: string, options: Models.BillingAccountsGetOptionalParams, callback: msRest.ServiceCallback<Models.BillingAccount>): void;
get(billingAccountName: string, options?: Models.BillingAccountsGetOptionalParams | msRest.ServiceCallback<Models.BillingAccount>, callback?: msRest.ServiceCallback<Models.BillingAccount>): Promise<Models.BillingAccountsGetResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
options
},
getOperationSpec,
callback) as Promise<Models.BillingAccountsGetResponse>;
}
/**
* Updates the properties of a billing account. Currently, displayName and address can be updated.
* The operation is supported only for billing accounts with agreement type Microsoft Customer
* Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param parameters Request parameters that are provided to the update billing account operation.
* @param [options] The optional parameters
* @returns Promise<Models.BillingAccountsUpdateResponse>
*/
update(billingAccountName: string, parameters: Models.BillingAccountUpdateRequest, options?: msRest.RequestOptionsBase): Promise<Models.BillingAccountsUpdateResponse> {
return this.beginUpdate(billingAccountName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BillingAccountsUpdateResponse>;
}
/**
* Lists the invoice sections for which the user has permission to create Azure subscriptions. The
* operation is supported only for billing accounts with agreement type Microsoft Customer
* Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param [options] The optional parameters
* @returns
* Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionResponse>
*/
listInvoiceSectionsByCreateSubscriptionPermission(billingAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param callback The callback
*/
listInvoiceSectionsByCreateSubscriptionPermission(billingAccountName: string, callback: msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param options The optional parameters
* @param callback The callback
*/
listInvoiceSectionsByCreateSubscriptionPermission(billingAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>): void;
listInvoiceSectionsByCreateSubscriptionPermission(billingAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>, callback?: msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>): Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
options
},
listInvoiceSectionsByCreateSubscriptionPermissionOperationSpec,
callback) as Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionResponse>;
}
/**
* Updates the properties of a billing account. Currently, displayName and address can be updated.
* The operation is supported only for billing accounts with agreement type Microsoft Customer
* Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param parameters Request parameters that are provided to the update billing account operation.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(billingAccountName: string, parameters: Models.BillingAccountUpdateRequest, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
billingAccountName,
parameters,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Lists the billing accounts that a user has access to.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.BillingAccountsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingAccountsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingAccountListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingAccountListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingAccountListResult>, callback?: msRest.ServiceCallback<Models.BillingAccountListResult>): Promise<Models.BillingAccountsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.BillingAccountsListNextResponse>;
}
/**
* Lists the invoice sections for which the user has permission to create Azure subscriptions. The
* operation is supported only for billing accounts with agreement type Microsoft Customer
* Agreement.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns
* Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionNextResponse>
*/
listInvoiceSectionsByCreateSubscriptionPermissionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listInvoiceSectionsByCreateSubscriptionPermissionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listInvoiceSectionsByCreateSubscriptionPermissionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>): void;
listInvoiceSectionsByCreateSubscriptionPermissionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>, callback?: msRest.ServiceCallback<Models.InvoiceSectionListWithCreateSubPermissionResult>): Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listInvoiceSectionsByCreateSubscriptionPermissionNextOperationSpec,
callback) as Promise<Models.BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts",
queryParameters: [
Parameters.apiVersion0,
Parameters.expand
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingAccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}",
urlParameters: [
Parameters.billingAccountName
],
queryParameters: [
Parameters.apiVersion0,
Parameters.expand
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingAccount
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listInvoiceSectionsByCreateSubscriptionPermissionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission",
urlParameters: [
Parameters.billingAccountName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.InvoiceSectionListWithCreateSubPermissionResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}",
urlParameters: [
Parameters.billingAccountName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.BillingAccountUpdateRequest,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.BillingAccount
},
202: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BillingAccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listInvoiceSectionsByCreateSubscriptionPermissionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.InvoiceSectionListWithCreateSubPermissionResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import * as chai from 'chai';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as sinon from 'sinon';
import * as chaiAsPromised from 'chai-as-promised';
import { FabricWalletRegistryEntry } from '../../src/registries/FabricWalletRegistryEntry';
import { FabricWalletRegistry } from '../../src/registries/FabricWalletRegistry';
import { FabricRuntimeUtil } from '../../src/util/FabricRuntimeUtil';
import { FabricEnvironmentRegistryEntry, EnvironmentType } from '../../src/registries/FabricEnvironmentRegistryEntry';
import { FabricEnvironmentRegistry } from '../../src/registries/FabricEnvironmentRegistry';
import { FileConfigurations } from '../../src/registries/FileConfigurations';
import { FabricWalletGeneratorFactory } from '../../src/util/FabricWalletGeneratorFactory';
import { MicrofabEnvironment } from '../../src/environments/MicrofabEnvironment';
import { FileRegistry } from '../../src/registries/FileRegistry';
import { MicrofabClient } from '../../src/environments/MicrofabClient';
chai.use(chaiAsPromised);
chai.should();
describe('FabricWalletRegistry', () => {
const registry: FabricWalletRegistry = FabricWalletRegistry.instance();
const environmentRegistry: FabricEnvironmentRegistry = FabricEnvironmentRegistry.instance();
before(async () => {
const registryPath: string = path.join(__dirname, 'tmp', 'registries');
registry.setRegistryPath(registryPath);
environmentRegistry.setRegistryPath(registryPath);
const importIdentityStub: sinon.SinonStub = sinon.stub().resolves();
const getIdentitiesStub: sinon.SinonStub = sinon.stub().resolves([
{
id: 'org1admin',
display_name: 'Org1 Admin',
type: 'identity',
cert: 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJ6RENDQVhTZ0F3SUJBZ0lRZHBtaE9FOVkxQ3V3WHl2b3pmMjFRakFLQmdncWhrak9QUVFEQWpBU01SQXcKRGdZRFZRUURFd2RQY21jeElFTkJNQjRYRFRJd01EVXhOREV3TkRjd01Gb1hEVE13TURVeE1qRXdORGN3TUZvdwpKVEVPTUF3R0ExVUVDeE1GWVdSdGFXNHhFekFSQmdOVkJBTVRDazl5WnpFZ1FXUnRhVzR3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFSN0l4UmRGb0theE1ZWHFyK01zU1F6UDhIS1lITVphRmYrVmt3SnpsbisKNGJsa1M0aWVxZFRiRWhqUThvc1F2QmxpZk1Ca29YeUVKd3JkNHdmUzNtc1dvNEdZTUlHVk1BNEdBMVVkRHdFQgovd1FFQXdJRm9EQWRCZ05WSFNVRUZqQVVCZ2dyQmdFRkJRY0RBZ1lJS3dZQkJRVUhBd0V3REFZRFZSMFRBUUgvCkJBSXdBREFwQmdOVkhRNEVJZ1FnNEpNUmx6cVhxaEFTaE1EaHIrOE5Hd0FFVE85bDFld3lJcDh0RHBMMTZMa3cKS3dZRFZSMGpCQ1F3SW9BZ21qczI3VG56V0ZvZWZ4Y3RYMGRZWUl4UnJKRmpVeXdyTHJ3YzMzdkp3Tmd3Q2dZSQpLb1pJemowRUF3SURSZ0F3UXdJZkVkS2xoSCsySk4yNDhVQnE3UjBtWnU5NGxiK1BXRFA4QnAxN0hMSHpMQUlnClRSMVF4ZUUrUitkNDhpWjB0ZEZ2S1FRVGQvWTJlZXJZMnJiUDZsQzVYWUU9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K',
private_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR0hBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJHMHdhd0lCQVFRZ1RMdWdydldMaXVvNWM5dnUKenh4MjBmZzBJS1B2c0haV2NLenUrTUVUcmNhaFJBTkNBQVI3SXhSZEZvS2F4TVlYcXIrTXNTUXpQOEhLWUhNWgphRmYrVmt3Snpsbis0YmxrUzRpZXFkVGJFaGpROG9zUXZCbGlmTUJrb1h5RUp3cmQ0d2ZTM21zVwotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==',
msp_id: 'Org1MSP',
wallet: 'Org1'
}
]);
const existsStub: sinon.SinonStub = sinon.stub().resolves(true);
const mockFabricWallet: any = {
importIdentity: importIdentityStub,
getIdentities: getIdentitiesStub,
exists: existsStub
};
const mockFabricWalletGenerator: any = {
getWallet: sinon.stub().resolves(mockFabricWallet)
};
FabricWalletGeneratorFactory.setFabricWalletGenerator(mockFabricWalletGenerator);
});
describe('getAll', () => {
let sandbox: sinon.SinonSandbox;
beforeEach(async () => {
await registry.clear();
await environmentRegistry.clear();
sandbox = sinon.createSandbox();
});
afterEach(async () => {
await registry.clear();
await environmentRegistry.clear();
sandbox.restore();
});
it('should get all the wallets and put local fabric first', async () => {
const walletOne: FabricWalletRegistryEntry = new FabricWalletRegistryEntry({
name: 'walletOne',
walletPath: 'myPath',
});
const walletTwo: FabricWalletRegistryEntry = new FabricWalletRegistryEntry({
name: 'walletTwo',
walletPath: 'otherPath',
});
await registry.getAll().should.eventually.deep.equal([]);
await FabricEnvironmentRegistry.instance().add({name: FabricRuntimeUtil.LOCAL_FABRIC, environmentDirectory: path.join(__dirname, '..', '..', '..', '..', 'test', 'data', FabricRuntimeUtil.LOCAL_FABRIC), environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, numberOfOrgs: 1, managedRuntime: true, url: 'http://someurl:9000', fabricCapabilities: 'V2_0'});
sandbox.stub(MicrofabClient.prototype, 'isAlive').resolves(true);
// // This will get the code working.
sandbox.stub(MicrofabClient.prototype, 'getComponents').resolves([
{
id: 'org1admin',
display_name: 'Org1 Admin',
type: 'identity',
cert: 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJ6RENDQVhTZ0F3SUJBZ0lRZHBtaE9FOVkxQ3V3WHl2b3pmMjFRakFLQmdncWhrak9QUVFEQWpBU01SQXcKRGdZRFZRUURFd2RQY21jeElFTkJNQjRYRFRJd01EVXhOREV3TkRjd01Gb1hEVE13TURVeE1qRXdORGN3TUZvdwpKVEVPTUF3R0ExVUVDeE1GWVdSdGFXNHhFekFSQmdOVkJBTVRDazl5WnpFZ1FXUnRhVzR3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFSN0l4UmRGb0theE1ZWHFyK01zU1F6UDhIS1lITVphRmYrVmt3SnpsbisKNGJsa1M0aWVxZFRiRWhqUThvc1F2QmxpZk1Ca29YeUVKd3JkNHdmUzNtc1dvNEdZTUlHVk1BNEdBMVVkRHdFQgovd1FFQXdJRm9EQWRCZ05WSFNVRUZqQVVCZ2dyQmdFRkJRY0RBZ1lJS3dZQkJRVUhBd0V3REFZRFZSMFRBUUgvCkJBSXdBREFwQmdOVkhRNEVJZ1FnNEpNUmx6cVhxaEFTaE1EaHIrOE5Hd0FFVE85bDFld3lJcDh0RHBMMTZMa3cKS3dZRFZSMGpCQ1F3SW9BZ21qczI3VG56V0ZvZWZ4Y3RYMGRZWUl4UnJKRmpVeXdyTHJ3YzMzdkp3Tmd3Q2dZSQpLb1pJemowRUF3SURSZ0F3UXdJZkVkS2xoSCsySk4yNDhVQnE3UjBtWnU5NGxiK1BXRFA4QnAxN0hMSHpMQUlnClRSMVF4ZUUrUitkNDhpWjB0ZEZ2S1FRVGQvWTJlZXJZMnJiUDZsQzVYWUU9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K',
private_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR0hBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJHMHdhd0lCQVFRZ1RMdWdydldMaXVvNWM5dnUKenh4MjBmZzBJS1B2c0haV2NLenUrTUVUcmNhaFJBTkNBQVI3SXhSZEZvS2F4TVlYcXIrTXNTUXpQOEhLWUhNWgphRmYrVmt3Snpsbis0YmxrUzRpZXFkVGJFaGpROG9zUXZCbGlmTUJrb1h5RUp3cmQ0d2ZTM21zVwotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==',
msp_id: 'Org1MSP',
wallet: 'Org1'
}
]);
sandbox.stub(MicrofabEnvironment.prototype, 'getIdentities').resolves([
{
id: 'org1admin',
display_name: 'Org1 Admin',
type: 'identity',
cert: 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJ6RENDQVhTZ0F3SUJBZ0lRZHBtaE9FOVkxQ3V3WHl2b3pmMjFRakFLQmdncWhrak9QUVFEQWpBU01SQXcKRGdZRFZRUURFd2RQY21jeElFTkJNQjRYRFRJd01EVXhOREV3TkRjd01Gb1hEVE13TURVeE1qRXdORGN3TUZvdwpKVEVPTUF3R0ExVUVDeE1GWVdSdGFXNHhFekFSQmdOVkJBTVRDazl5WnpFZ1FXUnRhVzR3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFSN0l4UmRGb0theE1ZWHFyK01zU1F6UDhIS1lITVphRmYrVmt3SnpsbisKNGJsa1M0aWVxZFRiRWhqUThvc1F2QmxpZk1Ca29YeUVKd3JkNHdmUzNtc1dvNEdZTUlHVk1BNEdBMVVkRHdFQgovd1FFQXdJRm9EQWRCZ05WSFNVRUZqQVVCZ2dyQmdFRkJRY0RBZ1lJS3dZQkJRVUhBd0V3REFZRFZSMFRBUUgvCkJBSXdBREFwQmdOVkhRNEVJZ1FnNEpNUmx6cVhxaEFTaE1EaHIrOE5Hd0FFVE85bDFld3lJcDh0RHBMMTZMa3cKS3dZRFZSMGpCQ1F3SW9BZ21qczI3VG56V0ZvZWZ4Y3RYMGRZWUl4UnJKRmpVeXdyTHJ3YzMzdkp3Tmd3Q2dZSQpLb1pJemowRUF3SURSZ0F3UXdJZkVkS2xoSCsySk4yNDhVQnE3UjBtWnU5NGxiK1BXRFA4QnAxN0hMSHpMQUlnClRSMVF4ZUUrUitkNDhpWjB0ZEZ2S1FRVGQvWTJlZXJZMnJiUDZsQzVYWUU9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K',
private_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR0hBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJHMHdhd0lCQVFRZ1RMdWdydldMaXVvNWM5dnUKenh4MjBmZzBJS1B2c0haV2NLenUrTUVUcmNhaFJBTkNBQVI3SXhSZEZvS2F4TVlYcXIrTXNTUXpQOEhLWUhNWgphRmYrVmt3Snpsbis0YmxrUzRpZXFkVGJFaGpROG9zUXZCbGlmTUJrb1h5RUp3cmQ0d2ZTM21zVwotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==',
msp_id: 'Org1MSP',
wallet: 'Org1'
}
]);
const localFabricOrgEntry: FabricWalletRegistryEntry = await FabricWalletRegistry.instance().get('Org1', FabricRuntimeUtil.LOCAL_FABRIC);
await registry.add(walletOne);
await registry.add(walletTwo);
const wallets: any = await registry.getAll();
wallets.length.should.equal(3);
wallets[0].should.deep.equal(localFabricOrgEntry);
wallets[1].should.deep.equal(walletOne);
wallets[2].should.deep.equal(walletTwo);
});
it('should get all wallets but not show local fabric', async () => {
const walletOne: FabricWalletRegistryEntry = new FabricWalletRegistryEntry({
name: 'walletOne',
walletPath: 'myPath'
});
await registry.getAll().should.eventually.deep.equal([]);
await FabricEnvironmentRegistry.instance().add({name: FabricRuntimeUtil.LOCAL_FABRIC, environmentDirectory: path.join(__dirname, '..', 'data', FabricRuntimeUtil.LOCAL_FABRIC), environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, managedRuntime: true, numberOfOrgs: 1, url: 'http://someurl:9000', fabricCapabilities: 'V2_0'});
await FabricEnvironmentRegistry.instance().add({name: 'otherLocalEnv', environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, managedRuntime: true, environmentDirectory : path.join(__dirname, '..', 'data', 'otherLocalEnv'), numberOfOrgs: 1, url: 'http://anotherurl:9000', fabricCapabilities: 'V2_0'});
await registry.add(walletOne);
await registry.getAll(false).should.eventually.deep.equal([walletOne]);
}).timeout(35000);
it('should get all including environments ones', async () => {
const walletOne: FabricWalletRegistryEntry = new FabricWalletRegistryEntry({
name: 'walletOne',
walletPath: 'myPath'
});
await registry.getAll().should.eventually.deep.equal([]);
await registry.add(walletOne);
await environmentRegistry.add(new FabricEnvironmentRegistryEntry({
name: 'anotherMicrofabEnvironment',
environmentDirectory: path.join('test', 'data', 'microfab'),
environmentType: EnvironmentType.MICROFAB_ENVIRONMENT,
managedRuntime: false,
url: 'http://someurl:9002'
}));
await environmentRegistry.add(new FabricEnvironmentRegistryEntry({
name: 'microfabEnvironment',
environmentDirectory: path.join('test', 'data', 'microfab'),
environmentType: EnvironmentType.MICROFAB_ENVIRONMENT,
managedRuntime: false,
url: 'http://someurl:9001'
}));
const newMicrofabEnvironmentStub: sinon.SinonStub = sandbox.stub(FabricWalletRegistry.instance(), 'newMicrofabEnvironment');
const mockMicrofabEnvironment: sinon.SinonStubbedInstance<MicrofabEnvironment> = sinon.createStubInstance(MicrofabEnvironment);
mockMicrofabEnvironment.isAlive.resolves(true);
const mockClient: sinon.SinonStubbedInstance<MicrofabClient> = sinon.createStubInstance(MicrofabClient);
mockMicrofabEnvironment.url = 'http://someurl:9001';
mockMicrofabEnvironment['client'] = mockClient as any;
mockMicrofabEnvironment.setClient.returns(undefined);
mockMicrofabEnvironment.getWalletsAndIdentities.onCall(0).resolves([
{
name: 'myWallet',
displayName: 'microfabEnvironment - myWallet'
}
]);
mockMicrofabEnvironment.getWalletsAndIdentities.onCall(1).resolves([
{
name: 'myWallet',
displayName: 'anotherMicrofabEnvironment - myWallet'
}
]);
newMicrofabEnvironmentStub.callsFake((name: string, directory: string, url: string): sinon.SinonStubbedInstance<MicrofabEnvironment> => {
newMicrofabEnvironmentStub['wrappedMethod'](name, directory, url);
return mockMicrofabEnvironment;
});
const entries: FabricWalletRegistryEntry[] = await FabricWalletRegistry.instance().getAll();
entries.length.should.equal(3);
entries[0].displayName.should.equal('anotherMicrofabEnvironment - myWallet');
entries[1].displayName.should.equal('microfabEnvironment - myWallet');
entries[2].should.deep.equal(walletOne);
});
it('should get all including environments ones, but excluding Microfab ones that are not alive', async () => {
const walletOne: FabricWalletRegistryEntry = new FabricWalletRegistryEntry({
name: 'walletOne',
walletPath: 'myPath'
});
await registry.getAll().should.eventually.deep.equal([]);
await registry.add(walletOne);
await environmentRegistry.add(new FabricEnvironmentRegistryEntry({
name: 'microfabEnvironment',
environmentDirectory: path.join('test', 'data', 'microfab'),
environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT,
managedRuntime: false,
url: 'http://someurl:9001'
}));
const newMicrofabEnvironmentStub: sinon.SinonStub = sandbox.stub(FabricWalletRegistry.instance(), 'newMicrofabEnvironment');
const mockMicrofabEnvironment: sinon.SinonStubbedInstance<MicrofabEnvironment> = sinon.createStubInstance(MicrofabEnvironment);
mockMicrofabEnvironment.isAlive.resolves(false);
mockMicrofabEnvironment.getWalletsAndIdentities.rejects(new Error('should not be called'));
mockMicrofabEnvironment.setClient.returns(undefined);
mockMicrofabEnvironment.url = 'http://someurl:9001';
newMicrofabEnvironmentStub.callsFake((name: string, directory: string, url: string): sinon.SinonStubbedInstance<MicrofabEnvironment> => {
newMicrofabEnvironmentStub['wrappedMethod'](name, directory, url);
return mockMicrofabEnvironment;
});
const entries: FabricWalletRegistryEntry[] = await FabricWalletRegistry.instance().getAll();
entries.length.should.equal(1);
entries[0].should.deep.equal(walletOne);
});
});
describe('get', () => {
let walletOne: FabricWalletRegistryEntry;
let sandbox: sinon.SinonSandbox;
beforeEach(async () => {
await registry.clear();
await environmentRegistry.clear();
sandbox = sinon.createSandbox();
await FabricEnvironmentRegistry.instance().clear();
await FabricWalletRegistry.instance().clear();
walletOne = new FabricWalletRegistryEntry({
name: 'walletOne',
walletPath: 'myPath'
});
await FabricWalletRegistry.instance().add(walletOne);
await FabricEnvironmentRegistry.instance().add({name: 'otherLocalEnv', environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, managedRuntime: true, environmentDirectory : path.join(__dirname, '..', 'data', 'otherLocalEnv'), numberOfOrgs: 1, url: 'http://anotherurl:9000', fabricCapabilities: 'V2_0'});
await FabricEnvironmentRegistry.instance().add(new FabricEnvironmentRegistryEntry({ name: 'myEnvironment', environmentType: EnvironmentType.ENVIRONMENT }));
sandbox.stub(MicrofabClient.prototype, 'isAlive').resolves(true);
// // This will get the code working.
sandbox.stub(MicrofabClient.prototype, 'getComponents').resolves([
{
id: 'org1admin',
display_name: 'Org1 Admin',
type: 'identity',
cert: 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJ6RENDQVhTZ0F3SUJBZ0lRZHBtaE9FOVkxQ3V3WHl2b3pmMjFRakFLQmdncWhrak9QUVFEQWpBU01SQXcKRGdZRFZRUURFd2RQY21jeElFTkJNQjRYRFRJd01EVXhOREV3TkRjd01Gb1hEVE13TURVeE1qRXdORGN3TUZvdwpKVEVPTUF3R0ExVUVDeE1GWVdSdGFXNHhFekFSQmdOVkJBTVRDazl5WnpFZ1FXUnRhVzR3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFSN0l4UmRGb0theE1ZWHFyK01zU1F6UDhIS1lITVphRmYrVmt3SnpsbisKNGJsa1M0aWVxZFRiRWhqUThvc1F2QmxpZk1Ca29YeUVKd3JkNHdmUzNtc1dvNEdZTUlHVk1BNEdBMVVkRHdFQgovd1FFQXdJRm9EQWRCZ05WSFNVRUZqQVVCZ2dyQmdFRkJRY0RBZ1lJS3dZQkJRVUhBd0V3REFZRFZSMFRBUUgvCkJBSXdBREFwQmdOVkhRNEVJZ1FnNEpNUmx6cVhxaEFTaE1EaHIrOE5Hd0FFVE85bDFld3lJcDh0RHBMMTZMa3cKS3dZRFZSMGpCQ1F3SW9BZ21qczI3VG56V0ZvZWZ4Y3RYMGRZWUl4UnJKRmpVeXdyTHJ3YzMzdkp3Tmd3Q2dZSQpLb1pJemowRUF3SURSZ0F3UXdJZkVkS2xoSCsySk4yNDhVQnE3UjBtWnU5NGxiK1BXRFA4QnAxN0hMSHpMQUlnClRSMVF4ZUUrUitkNDhpWjB0ZEZ2S1FRVGQvWTJlZXJZMnJiUDZsQzVYWUU9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K',
private_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR0hBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJHMHdhd0lCQVFRZ1RMdWdydldMaXVvNWM5dnUKenh4MjBmZzBJS1B2c0haV2NLenUrTUVUcmNhaFJBTkNBQVI3SXhSZEZvS2F4TVlYcXIrTXNTUXpQOEhLWUhNWgphRmYrVmt3Snpsbis0YmxrUzRpZXFkVGJFaGpROG9zUXZCbGlmTUJrb1h5RUp3cmQ0d2ZTM21zVwotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==',
msp_id: 'Org1MSP',
wallet: 'Org1'
}
]);
sandbox.stub(MicrofabEnvironment.prototype, 'getIdentities').resolves([
{
id: 'org1admin',
display_name: 'Org1 Admin',
type: 'identity',
cert: 'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJ6RENDQVhTZ0F3SUJBZ0lRZHBtaE9FOVkxQ3V3WHl2b3pmMjFRakFLQmdncWhrak9QUVFEQWpBU01SQXcKRGdZRFZRUURFd2RQY21jeElFTkJNQjRYRFRJd01EVXhOREV3TkRjd01Gb1hEVE13TURVeE1qRXdORGN3TUZvdwpKVEVPTUF3R0ExVUVDeE1GWVdSdGFXNHhFekFSQmdOVkJBTVRDazl5WnpFZ1FXUnRhVzR3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFSN0l4UmRGb0theE1ZWHFyK01zU1F6UDhIS1lITVphRmYrVmt3SnpsbisKNGJsa1M0aWVxZFRiRWhqUThvc1F2QmxpZk1Ca29YeUVKd3JkNHdmUzNtc1dvNEdZTUlHVk1BNEdBMVVkRHdFQgovd1FFQXdJRm9EQWRCZ05WSFNVRUZqQVVCZ2dyQmdFRkJRY0RBZ1lJS3dZQkJRVUhBd0V3REFZRFZSMFRBUUgvCkJBSXdBREFwQmdOVkhRNEVJZ1FnNEpNUmx6cVhxaEFTaE1EaHIrOE5Hd0FFVE85bDFld3lJcDh0RHBMMTZMa3cKS3dZRFZSMGpCQ1F3SW9BZ21qczI3VG56V0ZvZWZ4Y3RYMGRZWUl4UnJKRmpVeXdyTHJ3YzMzdkp3Tmd3Q2dZSQpLb1pJemowRUF3SURSZ0F3UXdJZkVkS2xoSCsySk4yNDhVQnE3UjBtWnU5NGxiK1BXRFA4QnAxN0hMSHpMQUlnClRSMVF4ZUUrUitkNDhpWjB0ZEZ2S1FRVGQvWTJlZXJZMnJiUDZsQzVYWUU9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K',
private_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR0hBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJHMHdhd0lCQVFRZ1RMdWdydldMaXVvNWM5dnUKenh4MjBmZzBJS1B2c0haV2NLenUrTUVUcmNhaFJBTkNBQVI3SXhSZEZvS2F4TVlYcXIrTXNTUXpQOEhLWUhNWgphRmYrVmt3Snpsbis0YmxrUzRpZXFkVGJFaGpROG9zUXZCbGlmTUJrb1h5RUp3cmQ0d2ZTM21zVwotLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tCg==',
msp_id: 'Org1MSP',
wallet: 'Org1'
}
]);
});
afterEach(async () => {
await registry.clear();
await environmentRegistry.clear();
sandbox.restore();
});
it('should get the wallet just based on the name', async () => {
const result: FabricWalletRegistryEntry = await FabricWalletRegistry.instance().get('walletOne');
result.should.deep.equal(walletOne);
});
it('should get the wallet based on the env name and name', async () => {
const result: FabricWalletRegistryEntry = await FabricWalletRegistry.instance().get('Org1', 'otherLocalEnv');
result.name.should.equal('Org1');
});
it('should get the wallet if it has environmentGroups', async () => {
walletOne.environmentGroups = ['myEnvironment'];
await FabricWalletRegistry.instance().update(walletOne);
const result: FabricWalletRegistryEntry = await FabricWalletRegistry.instance().get('walletOne');
result.should.deep.equal(walletOne);
});
it('should get the wallet if it has been associated with the env name', async () => {
walletOne.environmentGroups = ['myEnvironment'];
await FabricWalletRegistry.instance().update(walletOne);
const result: FabricWalletRegistryEntry = await FabricWalletRegistry.instance().get('walletOne', 'myEnvironment');
result.should.deep.equal(walletOne);
});
it('should throw an error if does not exist', async () => {
await FabricWalletRegistry.instance().get('blah', 'myEnvironment').should.eventually.be.rejectedWith(`Entry "blah" from environment "myEnvironment" in registry "${FileConfigurations.FABRIC_WALLETS}" does not exist`);
});
it('should throw an error if does not exist and no from environment', async () => {
await FabricWalletRegistry.instance().get('blah').should.eventually.be.rejectedWith(`Entry "blah" in registry "${FileConfigurations.FABRIC_WALLETS}" does not exist`);
});
});
describe('update', () => {
let sandbox: sinon.SinonSandbox;
beforeEach(async () => {
await registry.clear();
await environmentRegistry.clear();
sandbox = sinon.createSandbox();
});
afterEach(async () => {
await registry.clear();
await environmentRegistry.clear();
sandbox.restore();
});
it('should call the super update function', async () => {
const updateStub: sinon.SinonStub = sandbox.stub(FileRegistry.prototype, 'update').resolves();
const walletOne: FabricWalletRegistryEntry = new FabricWalletRegistryEntry({
name: 'walletOne',
walletPath: 'myPath'
});
await registry.getAll().should.eventually.deep.equal([]);
await registry.add(walletOne);
await FabricWalletRegistry.instance().update(walletOne);
updateStub.should.have.been.calledWith(walletOne);
});
it('should write a config file if from an environment', async () => {
const ensureDirStub: sinon.SinonStub = sandbox.stub(fs, 'ensureDir').resolves(true);
const writeStub: sinon.SinonStub = sandbox.stub(fs, 'writeJSON').resolves();
const walletOne: FabricWalletRegistryEntry = new FabricWalletRegistryEntry({
name: 'walletOne',
walletPath: 'myPath',
fromEnvironment: 'myEnvironment'
});
await registry.getAll().should.eventually.deep.equal([]);
await registry.add(walletOne);
await FabricWalletRegistry.instance().update(walletOne);
ensureDirStub.should.have.been.calledWith(path.join(walletOne.walletPath));
writeStub.should.have.been.calledWith(path.join(walletOne.walletPath, '.config.json'), walletOne);
});
});
}); | the_stack |
/**
* @license Copyright © 2013 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview Configuration UI abstractions.
*/
namespace VRS
{
/**
* The settings used to create a new OptionField.
*/
export interface OptionField_Settings
{
/**
* The unique name of the field.
*/
name: string;
/**
* The name to use for the event dispatcher. For internal use.
*/
dispatcherName?: string;
/**
* The VRS.optionsControlType enum value that determines which control will be used to display and/or edit this field.
*/
controlType?: OptionControlTypesEnum;
/**
* The index into VRS.$$ of the label to use when displaying the field or a function that returns the translated text.
*/
labelKey?: string | VoidFuncReturning<string>;
/**
* A callback that returns the value to display / edit from the object being configured.
*/
getValue?: () => any;
/**
* A callback that is passed the edited value. It is expected to copy the value into the object being configured.
*/
setValue?: (value: any) => void;
/**
* A callback that can save the current state of the object being configured.
*/
saveState?: () => void;
/**
* If true then the field is to be displayed next to the field that follows it.
*/
keepWithNext?: boolean;
/**
* A hook function that can be used to pick up changes to the value that is returned by getValue - for fields whose value may change while the configuration UI is on display.
*/
hookChanged?: (callback: Function, forceThis?: Object) => any;
/**
* An unhook function that can unhook the event hooked by hookChanged.
*/
unhookChanged?: (eventHandle: IEventHandle | IEventHandleJQueryUI) => void;
/**
* An indication of how wide the input field needs to be.
*/
inputWidth?: InputWidthEnum;
/**
* Indicates whether the field should be visible to the user.
*/
visible?: boolean | VoidFuncReturning<boolean>;
}
/**
* Describes a single editable option - there is usually one of these for each configurable property on an object.
*/
export class OptionField
{
// Events
protected _Dispatcher: EventHandler;
private _Events = {
refreshFieldContent: 'refreshFieldContent',
refreshFieldState: 'refreshFieldState',
refreshFieldVisibility: 'refreshFieldVisibility'
};
protected _Settings: OptionField_Settings;
constructor(settings: OptionField_Settings)
{
if(!settings) throw 'You must supply settings';
if(!settings.name) throw 'You must supply a name for the field';
if(!settings.controlType) throw 'You must supply the field\'s control type';
if(!VRS.optionControlTypeBroker.controlTypeHasHandler(settings.controlType)) throw 'There is no control type handler for ' + settings.controlType;
settings = $.extend({
name: null,
dispatcherName: 'VRS.OptionField', // Filled in by derivees to get a better name for the dispatcher
controlType: null,
labelKey: '',
getValue: $.noop,
setValue: $.noop,
saveState: $.noop,
keepWithNext: false,
hookChanged: null,
unhookChanged: null,
inputWidth: VRS.InputWidth.Auto,
visible: true
}, settings);
this._Settings = settings;
this._Dispatcher = new VRS.EventHandler({ name: settings.dispatcherName });
}
private _ChangedHookResult: IEventHandle | IEventHandleJQueryUI = null;
getName() : string
{
return this._Settings.name;
}
getControlType() : OptionControlTypesEnum
{
return this._Settings.controlType;
}
getKeepWithNext() : boolean
{
return this._Settings.keepWithNext;
}
setKeepWithNext(value: boolean)
{
this._Settings.keepWithNext = value;
}
getLabelKey() : string | VoidFuncReturning<string>
{
return this._Settings.labelKey;
}
getLabelText() : string
{
return VRS.globalisation.getText(this._Settings.labelKey);
}
getInputWidth() : InputWidthEnum
{
return this._Settings.inputWidth;
}
getVisible() : boolean
{
return VRS.Utility.ValueOrFuncReturningValue(this._Settings.visible, true);
}
/**
* Hooks an event that is raised when something wants the content of the field to be refreshed. Not all fields respond to this event.
*/
hookRefreshFieldContent(callback: () => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._Events.refreshFieldContent, callback, forceThis);
}
raiseRefreshFieldContent()
{
this._Dispatcher.raise(this._Events.refreshFieldContent);
}
/**
* Hooks an event that is raised when something wants the enabled / disabled state of the field to be refreshed. Not all fields response to this event.
*/
hookRefreshFieldState(callback: () => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._Events.refreshFieldState, callback, forceThis);
}
raiseRefreshFieldState()
{
this._Dispatcher.raise(this._Events.refreshFieldState);
}
/**
* Hooks an event that is raised when the visibility of the field should be refreshed.
*/
hookRefreshFieldVisibility(callback: () => void, forceThis?: Object)
{
return this._Dispatcher.hook(this._Events.refreshFieldVisibility, callback, forceThis);
}
raiseRefreshFieldVisibility()
{
this._Dispatcher.raise(this._Events.refreshFieldVisibility);
}
/**
* Unhooks a previously hooked event on the field.
*/
unhook(hookResult: IEventHandle)
{
this._Dispatcher.unhook(hookResult);
}
/**
* Calls the getValue method and returns the result.
*/
getValue() : any
{
return this._Settings.getValue();
}
/**
* Calls the setValue method with the value passed across.
*/
setValue(value: any)
{
this._Settings.setValue(value);
}
/**
* Calls the saveState method.
*/
saveState()
{
this._Settings.saveState();
}
/**
* Returns the input class based on the setting for inputWidth.
*/
getInputClass()
{
return this.getInputWidth();
}
/**
* Applies an input class to a jQuery element based on the setting for inputWidth.
*/
applyInputClass(jqElement: JQuery)
{
var inputClass = this.getInputClass();
if(inputClass && jqElement) {
jqElement.addClass(inputClass);
}
}
/**
* Calls the hookChanged event hooker and records the result.
*/
hookEvents(callback: () => void, forceThis?: Object)
{
if(this._Settings.hookChanged) {
this._ChangedHookResult = this._Settings.hookChanged(callback, forceThis);
}
}
/**
* Calls the unhookChanged event hooker with the result from the previous hookChanged call.
*/
unhookEvents()
{
if(this._Settings.unhookChanged && this._ChangedHookResult) {
this._Settings.unhookChanged(this._ChangedHookResult);
this._ChangedHookResult = null;
}
}
}
/**
* The settings to pass when creating an OptionFieldButton.
*/
export interface OptionFieldButton_Settings extends OptionField_Settings
{
/**
* The name of the jQuery UI icon to display on the button without the leading 'ui-icon-'.
*/
icon?: string;
/**
* The name of the jQuery UI icon to display on the button when it isn't pressed, without the leading 'ui-icon-'.
*/
primaryIcon?: string;
/**
* The name of the jQuery UI icon to display on the button when it is pressed, without the leading 'ui-icon'.
*/
secondaryIcon?: string;
/**
* True if the text is to be displayed, false if only the icon is to be displayed.
*/
showText?: boolean;
}
/**
* Describes an option field that shows a button to the user.
*/
export class OptionFieldButton extends OptionField
{
protected _Settings: OptionFieldButton_Settings;
private _Enabled: boolean;
constructor(settings: OptionFieldButton_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldButton',
controlType: VRS.optionControlTypes.button,
icon: null,
primaryIcon: null,
secondaryIcon: null,
showText: true
}, settings);
super(settings);
this._Enabled = true;
}
getPrimaryIcon() : string
{
return this._Settings.primaryIcon || this._Settings.icon;
}
getSecondaryIcon() : string
{
return this._Settings.secondaryIcon;
}
getShowText() : boolean
{
return this._Settings.showText;
}
getEnabled() : boolean
{
return this._Enabled;
}
setEnabled(value: boolean)
{
if(value !== this._Enabled) {
this._Enabled = value;
this.raiseRefreshFieldState();
}
}
}
/**
* The settings that need to be passed when creating new OptionFieldCheckBox objects.
*/
export interface OptionFieldCheckBox_Settings extends OptionField_Settings
{
}
/**
* The options for a checkbox field.
*/
export class OptionFieldCheckBox extends OptionField
{
constructor(settings: OptionFieldCheckBox_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldCheckBox',
controlType: VRS.optionControlTypes.checkBox
}, settings);
super(settings);
}
}
/**
* The settings used to create an OptionsFieldColour.
*/
export interface OptionFieldColour_Settings extends OptionField_Settings
{
}
/**
* Describes the options for a colour picker field.
*/
export class OptionFieldColour extends OptionField
{
constructor(settings: OptionFieldColour_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldColour',
controlType: VRS.optionControlTypes.colour,
inputWidth: VRS.InputWidth.NineChar
}, settings);
super(settings);
}
}
/**
* The settings used when creating an OptionsFieldComboBox.
*/
export interface OptionFieldComboBox_Settings extends OptionField_Settings
{
/**
* The values to display in the drop-down. text values are displayed as-is, textKey is an index into VRS.$$ or a function that returns the translated text.
*/
values?: ValueText[];
/**
* Called whenever the combo box value changes, gets passed the current value of the combo box.
*/
changed?: (any) => void;
}
/**
* The settings that can be associated with a combo-box control.
*/
export class OptionFieldComboBox extends OptionField
{
protected _Settings: OptionFieldComboBox_Settings;
constructor(settings: OptionFieldComboBox_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldComboBox',
controlType: VRS.optionControlTypes.comboBox,
values: [],
changed: $.noop
}, settings);
super(settings);
}
/**
* Gets the values and associated identifiers to show in the dropdown list.
*/
getValues() : ValueText[]
{
return this._Settings.values;
}
/**
* Calls the changed value callback, if supplied.
*/
callChangedCallback(selectedValue: any)
{
this._Settings.changed(selectedValue);
}
}
/**
* The settings to pass when creating a new instance of OptionFieldDate.
*/
export interface OptionFieldDate_Settings extends OptionField_Settings
{
/**
* The default date to display in the control. Defaults to today.
*/
defaultDate?: Date;
/**
* The earliest date that can be selected by the user. Leave undefined when there is no minimum date.
*/
minDate?: Date;
/**
* The latest date that can be selected by the user. Leave undefined when there is no maximum date.
*/
maxDate?: Date;
}
/**
* Describes the options for a date field.
*/
export class OptionFieldDate extends OptionField
{
protected _Settings: OptionFieldDate_Settings;
constructor(settings: OptionFieldDate_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldDate',
controlType: VRS.optionControlTypes.date,
defaultDate: null,
minDate: null,
maxDate: null
}, settings);
super(settings);
}
getDefaultDate() : Date
{
return this._Settings.defaultDate;
}
getMinDate() : Date
{
return this._Settings.minDate;
}
getMaxDate() : Date
{
return this._Settings.maxDate;
}
}
/**
* The settings that need to be passed when creating a new instance of OptionFieldLabel.
*/
export interface OptionFieldLabel_Settings extends OptionField_Settings
{
/**
* The width to assign to the label.
*/
labelWidth?: LabelWidthEnum;
}
/**
* The settings that can be associated with a label control.
*/
export class OptionFieldLabel extends OptionField
{
protected _Settings: OptionFieldLabel_Settings;
constructor(settings: OptionFieldLabel_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldLabel',
controlType: VRS.optionControlTypes.label,
labelWidth: VRS.LabelWidth.Auto
}, settings);
super(settings);
}
getLabelWidth() : LabelWidthEnum
{
return this._Settings.labelWidth;
}
}
/**
* The settings to pass when creating a new OptionFieldLinkLabel.
*/
export interface OptionFieldLinkLabel_Settings extends OptionField_Settings
{
/**
* A callback that returns the href for the link label. getValue() returns the text to display for the href.
*/
getHref?: () => string;
/**
* A callback that returns the target for the link. If missing or if the function returns null/undefined then no target is used.
*/
getTarget?: () => string;
}
/**
* The settings that can be associated with a link label control.
*/
export class OptionFieldLinkLabel extends OptionFieldLabel
{
protected _Settings: OptionFieldLinkLabel_Settings;
constructor(settings: OptionFieldLinkLabel_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldLinkLabel',
controlType: VRS.optionControlTypes.linkLabel,
getHref: $.noop,
getTarget: $.noop
}, settings);
super(settings);
}
getHref() : string
{
return this._Settings.getHref() || '#';
}
getTarget() : string
{
return this._Settings.getTarget() || null;
}
}
/**
* The settings to pass when creating new instances of OptionFieldNumeric.
*/
export interface OptionFieldNumeric_Settings extends OptionField_Settings
{
/**
* The smallest value that the user can enter.
*/
min?: number;
/**
* The largest value that the user can enter.
*/
max?: number;
/**
* The number of decimal places that will be shown to the user.
*/
decimals?: number;
/**
* The increment to use when automatically stepping values up or down.
*/
step?: number;
/**
* True if a slider control should be shown rather than a numeric control.
*/
showSlider?: boolean;
/**
* The increment to use when paging on the slider control. If undefined then step is used instead.
*/
sliderStep?: number;
/**
* If true then nulls are not translated into zero before being passed to the setValue method.
*/
allowNullValue?: boolean;
}
/**
* The settings that can be associated with a number editor control.
*/
export class OptionFieldNumeric extends OptionField
{
protected _Settings: OptionFieldNumeric_Settings;
constructor(settings: OptionFieldNumeric_Settings)
{
settings = $.extend(<OptionFieldNumeric_Settings> {
name: null,
dispatcherName: 'VRS.OptionFieldNumeric',
controlType: VRS.optionControlTypes.numeric,
min: undefined,
max: undefined,
decimals: undefined,
step: 1,
showSlider: false,
sliderStep: undefined,
allowNullValue: false
}, settings);
super(settings);
}
getMin() : number
{
return this._Settings.min;
}
getMax() : number
{
return this._Settings.max;
}
getDecimals() : number
{
return this._Settings.decimals;
}
getStep() : number
{
return this._Settings.step;
}
showSlider() : boolean
{
return this._Settings.showSlider;
}
getSliderStep() : number
{
return this._Settings.sliderStep === undefined ? this._Settings.step : this._Settings.sliderStep;
}
getAllowNullValue() : boolean
{
return this._Settings.allowNullValue;
}
}
/**
* The settings to pass when creating new instances of OptionFieldOrderedSubset.
*/
export interface OptionFieldOrderedSubset_Settings extends OptionField_Settings
{
/**
* The set of values that the user can choose from.
*/
values?: ValueText[];
/**
* True if the set of options that the user can choose from should be kept in alphabetical order.
*/
keepValuesSorted?: boolean;
}
/**
* The settings that can be associated with an editor that lets users choose a subset from a set of values.
*/
export class OptionFieldOrderedSubset extends OptionField
{
protected _Settings: OptionFieldOrderedSubset_Settings;
constructor(settings: OptionFieldOrderedSubset_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldOrderedSubset',
controlType: VRS.optionControlTypes.orderedSubset,
values: [],
keepValuesSorted: false
}, settings);
super(settings);
}
getValues() : ValueText[]
{
return this._Settings.values;
}
getKeepValuesSorted() : boolean
{
return this._Settings.keepValuesSorted;
}
}
/**
* The settings to use when creating a new instance of OptionFieldPaneList.
*/
export interface OptionFieldPaneList_Settings extends OptionField_Settings
{
/**
* The option panes to show to the user.
*/
panes?: OptionPane[];
/**
* The maximum number of panes (and by extension, items in the array being edited) that can be displayed / edited.
* Undefined or -1 indicates there is no maximum.
*/
maxPanes?: number;
/**
* An option pane containing the controls that can be used to add a new pane (and therefore a new array item).
*/
addPane?: OptionPane;
/**
* True if the UI to remove individual items is not shown to the user. Defaults to false.
*/
suppressRemoveButton?: boolean;
/**
* An optional method that it called to disable the add controls.
*/
refreshAddControls?: (disabled: boolean, addPanel: JQuery) => void;
}
interface IOptionFieldPaneList_Events
{
paneAdded: string;
paneRemoved: string;
maxPanesChanged: string;
}
//region OptionFieldPaneList
/**
* The settings that can be associated with an editor for an array of objects, where each object is edited via its own option pane.
*/
export class OptionFieldPaneList extends OptionField
{
protected _Settings: OptionFieldPaneList_Settings;
private _PaneListEvents: IOptionFieldPaneList_Events; // Need to do it this way round, have to initialise the list in the ctor
constructor(settings: OptionFieldPaneList_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldPaneList',
controlType: VRS.optionControlTypes.paneList,
panes: [],
maxPanes: -1,
addPane: null,
suppressRemoveButton: false,
refreshAddControls: function(disabled: boolean, addParentJQ: JQuery) {
$(':input', addParentJQ).prop('disabled', disabled);
$(':button', addParentJQ).button('option', 'disabled', disabled);
}
}, settings);
super(settings);
this._PaneListEvents = {
paneAdded: 'paneAdded',
paneRemoved: 'paneRemoved',
maxPanesChanged: 'maxPanesChanged'
};
}
getMaxPanes() : number
{
return this._Settings.maxPanes;
}
setMaxPanes(value: number)
{
if(value !== this._Settings.maxPanes) {
this._Settings.maxPanes = value;
this.trimExcessPanes();
this.onMaxPanesChanged();
}
}
getPanes() : OptionPane[]
{
return this._Settings.panes;
}
getAddPane() : OptionPane
{
return this._Settings.addPane;
}
setAddPane(value: OptionPane)
{
this._Settings.addPane = value;
}
getSuppressRemoveButton() : boolean
{
return this._Settings.suppressRemoveButton;
}
setSuppressRemoveButton(value: boolean)
{
this._Settings.suppressRemoveButton = value;
}
getRefreshAddControls() : (disabled: boolean, addParentJQ: JQuery) => void
{
return this._Settings.refreshAddControls;
}
setRefreshAddControls(value: (disabled: boolean, addParentJQ: JQuery) => void)
{
this._Settings.refreshAddControls = value;
}
/**
* Raised when the user adds a new pane. The listener is expected to add the associated array item.
*/
hookPaneAdded(callback: (newPane: OptionPane, index: number) => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._PaneListEvents.paneAdded, callback, forceThis);
}
private onPaneAdded(pane: OptionPane, index: number)
{
this._Dispatcher.raise(this._PaneListEvents.paneAdded, [ pane, index ]);
}
/**
* Raised when the user removes an existing pane.
*/
hookPaneRemoved(callback: (removedPane: OptionPane, index: number) => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._PaneListEvents.paneRemoved, callback, forceThis);
}
private onPaneRemoved(pane: OptionPane, index: number)
{
this._Dispatcher.raise(this._PaneListEvents.paneRemoved, [ pane, index]);
}
/**
* Raised after the maximum number of panes has changed.
* @param {function()} callback
* @param {object} forceThis
* @returns {{}}
*/
hookMaxPanesChanged(callback: () => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._PaneListEvents.maxPanesChanged, callback, forceThis);
}
private onMaxPanesChanged()
{
this._Dispatcher.raise(this._PaneListEvents.maxPanesChanged);
}
/**
* Adds a new pane to the array at the index specified.
*/
addPane(pane: OptionPane, index?: number)
{
if(index !== undefined) {
this._Settings.panes.splice(index, 0, pane);
this.onPaneAdded(pane, index);
} else {
this._Settings.panes.push(pane);
this.onPaneAdded(pane, this._Settings.panes.length - 1);
}
}
/**
* Removes the pane from the array.
*/
removePane(pane: OptionPane)
{
var index = this.findPaneIndex(pane);
if(index === -1) throw 'Cannot find the pane to remove';
this.removePaneAt(index);
}
/**
* Removes panes until the count of panes no longer exceeds the maximum allowed.
*/
trimExcessPanes()
{
if(this._Settings.maxPanes !== -1) {
while(this._Settings.maxPanes > this._Settings.panes.length) {
this.removePane(this._Settings.panes[this._Settings.panes.length - 1]);
}
}
}
/**
* Returns the index of the pane in the array or -1 if the pane is not in the arrary.
*/
private findPaneIndex(pane: OptionPane) : number
{
var result = -1;
var length = this._Settings.panes.length;
for(var i = 0;i < length;++i) {
if(this._Settings.panes[i] === pane) {
result = i;
break;
}
}
return result;
}
/**
* Removes the pane at the index specified.
*/
removePaneAt(index: number)
{
var pane = this._Settings.panes[index];
this._Settings.panes.splice(index, 1);
pane.dispose(null); // <-- this was not passed in the original JavaScript, need to look at existing dispose methods once I've converted everything to TypeScript
this.onPaneRemoved(pane, index);
}
}
/**
* The settings to pass when creating a new instance of OptionFieldRadioButton.
*/
export interface OptionFieldRadioButton_Settings extends OptionField_Settings
{
/**
* The values for each of the radio buttons to show to the user.
*/
values?: ValueText[];
}
export class OptionFieldRadioButton extends OptionField
{
protected _Settings: OptionFieldRadioButton_Settings;
constructor(settings: OptionFieldRadioButton_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldRadioButton',
controlType: VRS.optionControlTypes.radioButton,
values: []
}, settings);
super(settings);
}
getValues(): ValueText[]
{
return this._Settings.values;
}
}
/**
* The settings to pass when creating a new instance of OptionFieldTextBox.
*/
export interface OptionFieldTextBox_Settings extends OptionField_Settings
{
/**
* True if the text is to be forced into upper-case.
*/
upperCase?: boolean;
/**
* True if the text is to be forced into lower-case.
*/
lowerCase?: boolean;
/**
* The maximum number of characters allowed in the box.
*/
maxLength?: number;
}
/**
* The settings that can be associated with an editor that can display and edit strings.
*/
export class OptionFieldTextBox extends OptionField
{
protected _Settings: OptionFieldTextBox_Settings;
constructor(settings: OptionFieldTextBox_Settings)
{
settings = $.extend({
dispatcherName: 'VRS.OptionFieldTextBox',
controlType: VRS.optionControlTypes.textBox,
upperCase: false,
lowerCase: false,
maxLength: undefined
}, settings);
super(settings);
}
getUpperCase() : boolean
{
return this._Settings.upperCase;
}
getLowerCase() : boolean
{
return this._Settings.lowerCase;
}
getMaxLength() : number
{
return this._Settings.maxLength;
}
}
/**
* The settings to pass when creating a new instance of an OptionPane.
*/
export interface OptionPane_Settings
{
/**
* The name of the pane.
*/
name: string;
/**
* The index into VRS.$$ or a method that returns a string. Used as the title for the pane on the page.
*/
titleKey?: string | VoidFuncReturning<string>;
/**
* The relative display order of the pane. Lower display orders appear before higher display orders.
*/
displayOrder?: number;
/**
* The initial set of fields on the pane.
*/
fields?: OptionField[];
/**
* A method to call when the pane is disposed of. Passed an object carrying the OptionPane and the OptionPageParent.
*/
dispose?: (objects: OptionPane_DisposeObjects) => void;
/**
* A method to call when a page parent is created.
*/
pageParentCreated?: (parent: OptionPageParent) => void;
}
/**
* The object passed to an OptionPane's dispose callback.
*/
export interface OptionPane_DisposeObjects
{
optionPane: OptionPane;
optionPageParent: OptionPageParent;
}
/**
* Describes a pane of related options in the options UI.
*/
export class OptionPane
{
private _Settings: OptionPane_Settings;
/**
* The array of fields that the pane contains.
*/
private _OptionFields: OptionField[] = [];
/**
* A value that is incremented any time a field is added to or removed from the pane.
*/
private _Generation = 0;
constructor(settings: OptionPane_Settings)
{
if(!settings) throw 'You must supply settings';
if(!settings.name) throw 'You must supply a name for the pane';
settings = $.extend({
name: null,
titleKey: null,
displayOrder: 0,
fields: [],
dispose: $.noop,
pageParentCreated: $.noop
}, settings);
this._Settings = settings;
if(settings.fields) {
for(var i = 0;i < settings.fields.length;++i) {
this.addField(settings.fields[i]);
}
}
}
getName() : string
{
return this._Settings.name;
}
getTitleKey() : string | VoidFuncReturning<string>
{
return this._Settings.titleKey;
}
getTitleText() : string
{
return VRS.globalisation.getText(this._Settings.titleKey);
}
setTitleKey(value: string | VoidFuncReturning<string>)
{
this._Settings.titleKey = value;
}
getDisplayOrder() : number
{
return this._Settings.displayOrder;
}
setDisplayOrder(value : number)
{
this._Settings.displayOrder = value;
}
getFieldCount() : number
{
return this._OptionFields.length;
}
getField(idx: number) : OptionField
{
return this._OptionFields[idx];
}
getFieldByName(optionFieldName: string) : OptionField
{
var index = this.findIndexByName(optionFieldName);
return index === -1 ? null : this.getField(index);
}
dispose(options: OptionPane_DisposeObjects)
{
this._Settings.dispose(options);
}
/**
* Invokes a callback, registered when the pane was created, that the pane is being rendered into a page and
* passes the callback the VRS.OptionPageParent that will live for the duration of the render.
*/
pageParentCreated(optionPageParent: OptionPageParent)
{
this._Settings.pageParentCreated(optionPageParent);
}
/**
* Adds a field to the pane. Throws if the field already exists.
*/
addField(optionField: OptionField)
{
var existingIndex = this.findIndexByName(optionField.getName());
if(existingIndex !== -1) throw 'There is already a field in this pane called ' + optionField.getName();
this._OptionFields.push(optionField);
++this._Generation;
}
/**
* Removes a field from the pane by its name. Throws if the field does not exist.
*/
removeFieldByName(optionFieldName: string)
{
var index = this.findIndexByName(optionFieldName);
if(index === -1) throw 'Cannot remove option field ' + optionFieldName + ', it does not exist.';
this._OptionFields.splice(index, 1);
++this._Generation;
}
/**
* Passes every field on the pane to a callback method. The callback is not allowed to add or remove fields from the pane.
*/
foreachField(callback: (field: OptionField) => void)
{
var length = this._OptionFields.length;
var generation = this._Generation;
for(var i = 0;i < length;++i) {
callback(this._OptionFields[i]);
if(this._Generation !== generation) {
throw 'Cannot continue to iterate through the fields after the collection has been modified';
}
}
}
/**
* Returns the index of the named field or -1 if there is no field with that name.
*/
private findIndexByName(optionFieldName: string) : number
{
var result = -1;
$.each(this._OptionFields, function(idx, val) {
var breakLoop = val.getName() === optionFieldName;
if(breakLoop) result = idx;
return !breakLoop;
});
return result;
}
}
/**
* The settings to pass when creating a new instance of OptionPage.
*/
export interface OptionPage_Settings
{
/**
* The unique name of the page.
*/
name: string;
/**
* The VRS.$$ label for the page's title, or a void function that returns the page's title.
*/
titleKey?: string | VoidFuncReturning<string>;
/**
* The relative order of the page within a group of pages. Pages with a lower display order come before those with a higher order.
*/
displayOrder?: number;
/**
* The initial set of panes.
*/
panes?: OptionPane[] | OptionPane[][];
}
/**
* Describes a page of panes in the configuration UI.
*/
export class OptionPage
{
private _Settings: OptionPage_Settings;
/**
* The panes held by the page.
*/
private _OptionPanes: OptionPane[] = [];
/**
* A value that is incremented every time a pane is added to or removed from the page.
*/
private _Generation = 0;
/**
* The generation number as-at the last time the page was sorted. Used to optimise the sort method.
*/
private _SortGeneration = -1;
constructor(settings: OptionPage_Settings)
{
if(!settings) throw 'You must supply settings';
if(!settings.name) throw 'You must give the page a name';
this._Settings = settings;
if(settings.panes) {
for(var i = 0;i < settings.panes.length;++i) {
this.addPane(settings.panes[i]);
}
}
}
getName() : string
{
return this._Settings.name;
}
setName(value: string)
{
this._Settings.name = value;
}
getTitleKey() : string | VoidFuncReturning<string>
{
return this._Settings.titleKey;
}
setTitleKey(value: string | VoidFuncReturning<string>)
{
this._Settings.titleKey = value;
}
getDisplayOrder() : number
{
return this._Settings.displayOrder;
}
setDisplayOrder(value: number)
{
if(!isNaN(value)) {
this._Settings.displayOrder = value;
}
}
/**
* Adds one or more panes to the page. If there is already a pane on the page with the same name then an exception is thrown.
*/
addPane(optionPane: OptionPane | OptionPane[])
{
if(!(optionPane instanceof VRS.OptionPane)) {
var length = (<OptionPane[]>optionPane).length;
for(var i = 0;i < length;++i) {
this.addPane(optionPane[i]);
}
} else {
var index = this.findIndexByName(optionPane.getName());
if(index !== -1) throw 'There is already a pane on this page called ' + optionPane.getName();
this._OptionPanes.push(optionPane);
++this._Generation;
}
}
/**
* Removes the pane with the name passed across. If there is no pane on the page with this name then an exception is thrown.
*/
removePaneByName(optionPaneName: string)
{
var index = this.findIndexByName(optionPaneName);
if(index === -1) throw 'There is no pane called ' + optionPaneName;
this._OptionPanes.splice(index, 1);
++this._Generation;
}
/**
* Passes each pane on the page to a callback method, one at a time. The callback must not add or remove panes on the page.
*/
foreachPane(callback: (pane: OptionPane) => void)
{
this.sortPanes();
var generation = this._Generation;
var length = this._OptionPanes.length;
for(var i = 0;i < length;++i) {
callback(this._OptionPanes[i]);
if(this._Generation != generation) throw 'Cannot continue to iterate through the panes, they have been changed';
}
}
/**
* Returns the index of a pane or -1 if there is no pane with the name passed across.
*/
private findIndexByName(optionPaneName: string) : number
{
var result = -1;
$.each(this._OptionPanes, function(idx, val) {
var foundMatch = val.getName() === optionPaneName;
if(foundMatch) result = idx;
return !foundMatch;
});
return result;
}
/**
* Sorts panes into display order.
*/
private sortPanes()
{
if(this._SortGeneration !== this._Generation) {
this._OptionPanes.sort(function(lhs, rhs) {
return lhs.getDisplayOrder() - rhs.getDisplayOrder();
});
this._SortGeneration = this._Generation;
}
}
}
/**
* An object that exposes events across all of the options in a group of pages.
*/
export class OptionPageParent
{
private _Dispatcher = new EventHandler({ name: 'VRS.OptionPageParent' });
private _Events = {
fieldChanged: 'fieldChanged'
}
/**
* Hooks an event that is raised whenever a field changes on the object.
*/
hookFieldChanged(callback: () => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._Events.fieldChanged, callback, forceThis);
}
raiseFieldChanged()
{
this._Dispatcher.raise(this._Events.fieldChanged);
}
/**
* Unhooks an event previously hooked.
*/
unhook(hookResult: IEventHandle)
{
this._Dispatcher.unhook(hookResult);
}
}
/**
* The base options that are passed to all plugins that represent the different kinds of OptionField.
* All plugins should extend their options from this interface. In particular they should override
* field with the OptionField type that they are handling.
*/
export interface OptionControl_BaseOptions
{
field: OptionField;
fieldParentJQ: JQuery;
optionPageParent: OptionPageParent;
}
/**
* An object that can translate between control types and the jQuery UI plugin that handles the control.
*/
export class OptionControlTypeBroker
{
/**
* The associative array of control types and the method to use to create the appropriate jQuery UI plugin.
*/
private _ControlTypes: { [index: /*OptionControlTypesEnum - TS1.7 does not allow types as index, even if they resolve to string... */string]: (settings: OptionControl_BaseOptions) => JQuery } = {};
/**
* Adds a handler for a control type handler. Throws an exception if there is already a handler for the control type.
*/
addControlTypeHandler(controlType: OptionControlTypesEnum, creatorCallback: (options: OptionControl_BaseOptions) => JQuery)
{
if(this._ControlTypes[controlType]) throw 'There is already a handler registered for ' + controlType + ' control types';
this._ControlTypes[controlType] = creatorCallback;
}
/**
* Adds a handler for a control type, but only if one is not already registered. Does nothing if one is already registered.
*/
addControlTypeHandlerIfNotRegistered(controlType: OptionControlTypesEnum, creatorCallback: (options: OptionControl_BaseOptions) => JQuery)
{
if(!this.controlTypeHasHandler(controlType)) {
this.addControlTypeHandler(controlType, creatorCallback);
}
}
/**
* Removes the handler for a control type. Throws an exception if the control type does not have a handler registered.
*/
removeControlTypeHandler(controlType: OptionControlTypesEnum)
{
if(!this._ControlTypes[controlType]) throw 'There is no handler registered for ' + controlType + ' control types';
delete this._ControlTypes[controlType];
}
/**
* Returns true if the control type has a handler registered for it, false if it does not.
*/
controlTypeHasHandler(controlType: OptionControlTypesEnum) : boolean
{
return !!this._ControlTypes[controlType];
}
/**
* Creates the jQuery UI plugin that will manage the display and editing of an option field.
*/
createControlTypeHandler(options: OptionControl_BaseOptions) : JQuery
{
var controlType = options.field.getControlType();
var creator = this._ControlTypes[controlType];
if(!creator) throw 'There is no handler registered for ' + controlType + ' control types';
return creator(options);
}
}
/*
* Pre-builts
*/
export var optionControlTypeBroker = new VRS.OptionControlTypeBroker();
export type OptionControlTypesEnum = string;
/*
* A modifiable enumeration of the different control types. 3rd parties can add their own control types to this.
*/
export var optionControlTypes = VRS.optionControlTypes || {};
VRS.optionControlTypes.button = 'vrsButton';
VRS.optionControlTypes.checkBox = 'vrsCheckBox';
VRS.optionControlTypes.colour = 'vrsColour';
VRS.optionControlTypes.comboBox = 'vrsComboBox';
VRS.optionControlTypes.date = 'vrsDate';
VRS.optionControlTypes.label = 'vrsLabel';
VRS.optionControlTypes.linkLabel = 'vrsLinkLabel';
VRS.optionControlTypes.numeric = 'vrsNumeric';
VRS.optionControlTypes.orderedSubset = 'vrsOrderedSubset';
VRS.optionControlTypes.paneList = 'vrsPaneList';
VRS.optionControlTypes.radioButton = 'vrsRadioButton';
VRS.optionControlTypes.textBox = 'vrsTextBox';
} | the_stack |
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import { AwsKmsMrkAwareSymmetricDiscoveryKeyringClass } from '../src/kms_mrk_discovery_keyring'
import {
NodeAlgorithmSuite,
AlgorithmSuiteIdentifier,
KeyringTraceFlag,
NodeDecryptionMaterial,
EncryptedDataKey,
Keyring,
Newable,
} from '@aws-crypto/material-management'
chai.use(chaiAsPromised)
const { expect } = chai
describe('AwsKmsMrkAwareSymmetricDiscoveryKeyring: _onDecrypt', () => {
it('returns material', async () => {
const discoveryFilter = { accountIDs: ['2222222222222'], partition: 'aws' }
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const keyOtherRegion =
'arn:aws:kms:us-west-2:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function decrypt({
KeyId,
CiphertextBlob,
EncryptionContext,
GrantTokens,
}: any) {
expect(KeyId).to.equal(keyId)
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: Buffer.from(CiphertextBlob as Uint8Array).toString('utf8'),
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyOtherRegion,
encryptedDataKey: Buffer.from(keyId),
})
const otherEDK = new EncryptedDataKey({
providerId: 'other-provider',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
const seedMaterial = new NodeDecryptionMaterial(suite, context)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# OnDecrypt MUST take decryption materials (structures.md#decryption-
//# materials) and a list of encrypted data keys
//# (structures.md#encrypted-data-key) as input.
const material = await testKeyring.onDecrypt(seedMaterial, [edk, otherEDK])
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# Since the response does satisfies these requirements then OnDecrypt
//# MUST do the following with the response:
expect(seedMaterial === material).to.equal(true)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(material.keyringTrace).to.have.lengthOf(1)
const [traceDecrypt] = material.keyringTrace
expect(traceDecrypt.keyNamespace).to.equal('aws-kms')
expect(traceDecrypt.keyName).to.equal(keyId)
expect(
traceDecrypt.flags & KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY
).to.equal(KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY)
expect(
traceDecrypt.flags & KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX
).to.equal(KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX)
})
it('do not attempt to decrypt anything if we already a unencrypted data key.', async () => {
const client: any = { config: { region: 'temp' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
})
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const seedMaterial = new NodeDecryptionMaterial(
suite,
context
).setUnencryptedDataKey(new Uint8Array(suite.keyLengthBytes), {
keyNamespace: 'k',
keyName: 'k',
flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY,
})
// The Provider info is malformed,
// if the keyring filters this,
// it should throw.
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: 'Not:an/arn',
encryptedDataKey: new Uint8Array(1),
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# If the decryption materials (structures.md#decryption-materials)
//# already contained a valid plaintext data key OnDecrypt MUST
//# immediately return the unmodified decryption materials
//# (structures.md#decryption-materials).
const material = await testKeyring.onDecrypt(seedMaterial, [edk])
expect(material === seedMaterial).to.equal(true)
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# For each encrypted data key in the filtered set, one at a time, the
//# OnDecrypt MUST attempt to decrypt the data key.
it('does not halt on decrypt errors', async () => {
const discoveryFilter = { accountIDs: ['2222222222222'], partition: 'aws' }
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const otherKeyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-0000abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let kmsCalls = 0
let errorThrown = false
async function decrypt({
KeyId,
// CiphertextBlob,
EncryptionContext,
GrantTokens,
}: any) {
if (kmsCalls === 0) {
expect(KeyId).to.equal(keyId)
kmsCalls += 1
// This forces me to wait to throw an error
await new Promise((resolve) => setTimeout(resolve, 10))
errorThrown = true
throw new Error('failed to decrypt')
}
// If this is not true, then we have attempted
// the next edk before the last key was attempted.
expect(errorThrown).to.equal(true)
expect(kmsCalls).to.equal(1)
expect(KeyId).to.equal(otherKeyId)
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
kmsCalls += 1
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: otherKeyId,
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: otherKeyId,
encryptedDataKey: Buffer.from(otherKeyId),
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
[edk1, edk2]
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(material.keyringTrace).to.have.lengthOf(1)
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# The set of encrypted data keys MUST first be filtered to match this
//# keyring's configuration.
describe('Only attemts to decrypt EDKs that match its configuration', () => {
it('does not attempt to decrypt non-AWS KMS EDKs', async () => {
const discoveryFilter = {
accountIDs: ['2222222222222'],
partition: 'aws',
}
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let kmsCalled = false
function decrypt() {
kmsCalled = true
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: keyId,
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'not aws kms edk',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * Its provider ID MUST exactly match the value "aws-kms".
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [edk])
).to.rejectedWith(Error, 'Unable to decrypt data key')
expect(kmsCalled).to.equal(false)
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key-
//# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or
//# OnDecrypt MUST fail.
describe('halts and throws an error if encounters aws-kms EDK ProviderInfo with', () => {
const client: any = { config: { region: 'us-east-1' } }
const discoveryFilter = {
accountIDs: ['2222222222222'],
partition: 'aws',
}
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
it('a non-valid keyId', async () => {
const keyId = 'Not:an/arn'
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
return expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk,
])
).to.rejectedWith(Error, 'Malformed arn')
})
it('raw key id', async () => {
const keyId = 'mrk-80bd8ecdcd4342aebd84b7dc9da498a7'
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
return expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk,
])
).to.rejectedWith(Error, 'Unexpected EDK ProviderInfo for AWS KMS EDK')
})
it('a alias ARN', async () => {
const keyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
return expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk,
])
).to.rejectedWith(Error, 'Unexpected EDK ProviderInfo for AWS KMS EDK')
})
})
describe('does not attempt to decrypt CMKs which do not match discovery filter', () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
// This works because both these do NOT expect to call KMS
let kmsCalled = false
function decrypt() {
kmsCalled = true
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: keyId,
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
it('according to accountID', async () => {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * If a discovery filter is configured, its set of accounts MUST
//# contain the provider info account.
await expect(
new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
grantTokens,
discoveryFilter: {
accountIDs: ['Not: 2222222222222'],
partition: 'aws',
},
}).onDecrypt(new NodeDecryptionMaterial(suite, context), [edk])
).to.rejectedWith(Error, 'Unable to decrypt data key')
expect(kmsCalled).to.equal(false)
})
it('according to partition', async () => {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * If a discovery filter is configured, its partition and the
//# provider info partition MUST match.
await expect(
new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
grantTokens,
discoveryFilter: {
accountIDs: ['2222222222222'],
partition: 'notAWS',
},
}).onDecrypt(new NodeDecryptionMaterial(suite, context), [edk])
).to.rejectedWith(Error, 'Unable to decrypt data key')
expect(kmsCalled).to.equal(false)
})
})
it('does not attempt to decrypt non-MRK CMK ARNs if it is not in our region', async () => {
const discoveryFilter = {
accountIDs: ['2222222222222'],
partition: 'aws',
}
const keyId =
'arn:aws:kms:us-east-2:2222222222222:key/4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let kmsCalled = false
function decrypt() {
kmsCalled = true
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: keyId,
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * If the provider info is not identified as a multi-Region key (aws-
//# kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then the
//# provider info's Region MUST match the AWS KMS client region.
await expect(
new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
grantTokens,
discoveryFilter,
}).onDecrypt(new NodeDecryptionMaterial(suite, context), [edk])
).to.rejectedWith(Error, 'Unable to decrypt data key')
expect(kmsCalled).to.equal(false)
})
})
it('calls KMS Decrypt with keyId as an ARN indicating the configured region if an MRK-indicating ARN', async () => {
const discoveryFilter = { accountIDs: ['2222222222222'], partition: 'aws' }
const usWest2Key =
'arn:aws:kms:us-west-2:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const usEast1Key =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const encryptedDataKey = Buffer.from(usEast1Key)
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# To attempt to decrypt a particular encrypted data key
//# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS
//# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) with the configured AWS KMS client.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# When calling AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html), the keyring MUST call with a request constructed
//# as follows:
function decrypt({
KeyId,
EncryptionContext,
GrantTokens,
CiphertextBlob,
}: any) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * "KeyId": If the provider info's resource type is "key" and its
//# resource is a multi-Region key then a new ARN MUST be created
//# where the region part MUST equal the AWS KMS client region and
//# every other part MUST equal the provider info.
expect(KeyId).to.equal(usWest2Key)
expect(CiphertextBlob).to.deep.equal(encryptedDataKey)
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId,
}
}
const client: any = { decrypt, config: { region: 'us-west-2' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: usEast1Key,
encryptedDataKey,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
[edk]
)
expect(material.hasUnencryptedDataKey).to.equal(true)
})
it('calls KMS Decrypt with keyId as the exact ARN if not an MRK ARN', async () => {
const discoveryFilter = { accountIDs: ['2222222222222'], partition: 'aws' }
const keyId =
'arn:aws:kms:us-west-2:2222222222222:key/4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function decrypt({
KeyId,
CiphertextBlob,
EncryptionContext,
GrantTokens,
}: any) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# Otherwise it MUST
//# be the provider info.
expect(KeyId).to.equal(keyId)
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId: Buffer.from(CiphertextBlob as Uint8Array).toString('utf8'),
}
}
const client: any = { decrypt, config: { region: 'us-west-2' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
[edk]
)
expect(material.hasUnencryptedDataKey).to.equal(true)
})
it('collects an error if the KeyId from KMS Decrypt does not match the requested KeyID.', async () => {
const discoveryFilter = { accountIDs: ['2222222222222'], partition: 'aws' }
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function decrypt({ KeyId, EncryptionContext }: any) {
expect(EncryptionContext).to.deep.equal(context)
expect(KeyId).to.equal(keyId)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * The "KeyId" field in the response MUST equal the requested "KeyId"
KeyId: 'Not the right ARN',
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
return expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [edk])
).to.rejectedWith(
Error,
'KMS Decryption key does not match the requested key id.'
)
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# If the response does not satisfies these requirements then an error
//# is collected and the next encrypted data key in the filtered set MUST
//# be attempted.
it('collects an error if the decrypted unencryptedDataKey length does not match the algorithm specification.', async () => {
const discoveryFilter = { accountIDs: ['2222222222222'], partition: 'aws' }
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let awsKmsCalled = 0
function decrypt({ CiphertextBlob, EncryptionContext, GrantTokens }: any) {
awsKmsCalled += 1
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
return {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# * The length of the response's "Plaintext" MUST equal the key
//# derivation input length (algorithm-suites.md#key-derivation-input-
//# length) specified by the algorithm suite (algorithm-suites.md)
//# included in the input decryption materials
//# (structures.md#decryption-materials).
Plaintext: new Uint8Array(suite.keyLengthBytes - 5),
KeyId: Buffer.from(CiphertextBlob as Uint8Array).toString('utf8'),
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk1,
edk2,
])
).to.rejectedWith(
Error,
'Key length does not agree with the algorithm specification.'
)
expect(awsKmsCalled).to.equal(2)
})
describe('throws an error if does not successfully decrypt any EDK', () => {
it('because it encountered no EDKs to decrypt', async () => {
const discoveryFilter = {
accountIDs: ['2222222222222'],
partition: 'aws',
}
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const client: any = { config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [])
).to.rejectedWith(Error, 'Unable to decrypt data key: No EDKs supplied.')
})
it('because it encountered decryption errors', async () => {
const discoveryFilter = {
accountIDs: ['2222222222222'],
partition: 'aws',
}
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const otherKeyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-0000abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let edkCount = 0
function decrypt({ KeyId }: any) {
if (edkCount === 0) {
expect(KeyId).to.equal(keyId)
edkCount += 1
throw new Error('Decrypt Error 1')
} else {
expect(KeyId).to.equal(otherKeyId)
edkCount += 1
throw new Error('Decrypt Error 2')
}
}
const client: any = { decrypt, config: { region: 'us-east-1' } }
class TestAwsKmsMrkAwareSymmetricDiscoveryKeyring extends AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricDiscoveryKeyring({
client,
discoveryFilter,
grantTokens,
})
const edk1 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: keyId,
encryptedDataKey: Buffer.from(keyId),
})
const edk2 = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: otherKeyId,
encryptedDataKey: Buffer.from(otherKeyId),
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=test
//# If OnDecrypt fails to successfully decrypt any encrypted data key
//# (structures.md#encrypted-data-key), then it MUST yield an error that
//# includes all collected errors.
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), [
edk1,
edk2,
])
).to.rejectedWith(
Error,
/Unable to decrypt data key[\s\S]*Decrypt Error 1[\s\S]*Decrypt Error 2/
)
})
})
}) | the_stack |
import Long from 'long';
import {X86Unit} from '../X86Unit';
import {X87RegsStore, X87Tag} from './X87Regs';
import {X86InstructionSet} from '../X86InstructionSet';
import {X86OpcodesList} from '../X86CPU';
import {X86AbstractCPU} from '../types';
import {
X87Error,
X87ErrorCode,
} from './X87Error';
/**
* Floating point intel 8087 fpu
*
* @export
* @class X87
* @extends {X86Unit}
*/
export class X87 extends X86Unit {
static PREDEFINED_CONSTANTS = {
ZERO: +0.0,
ONE: +1.0,
L2T: Math.LOG10E,
L2E: Math.LOG2E,
PI: Math.PI,
LG2: Math.log10(2),
LN2: Math.log(Math.E),
};
private registers: X87RegsStore;
private opcodes: X86OpcodesList;
static isX87Opcode(opcode: number): boolean {
return opcode === 0x9B || (opcode >= 0xD8 && opcode <= 0xDF);
}
/**
* Round value
*
* @static
* @param {number} num
* @returns {number}
* @memberof X87
*/
static truncate(num: number): number {
return num > 0 ? Math.floor(num) : Math.ceil(num);
}
/**
* Returns number parts of digit
*
* @static
* @param {number} num
* @returns
* @memberof X87
*/
static numberParts(num: number) {
const float = new Float64Array(1);
const bytes = new Uint8Array(float.buffer);
float[0] = num;
const sign = bytes[7] >> 7;
const exponent = (((bytes[7] & 0x7f) << 4) | (bytes[6] >> 4)) - 0x3ff;
bytes[7] = 0x3f;
bytes[6] |= 0xf0;
return {
mantissa: float[0],
sign,
exponent,
};
}
/**
* Prints to console all registers
*
* @memberof X87
*/
debugDumpRegisters() {
const {cpu, registers} = this;
if (registers.isStackInitialized()) {
cpu.logger.table(
registers.debugDump().regs,
);
} else
console.warn('FPU is not initialized!');
}
/**
* Handles opcode
*
* @param {number} opcode *
* @memberof X87
*/
tick(opcode: number) {
const {opcodes, cpu, registers} = this;
const operand = opcodes[opcode];
if (operand) {
registers.stackFault = false;
registers.invalidOperation = false;
registers.fip = cpu.registers.ip - 0x1; // remove already fetched opcode
registers.fdp = 0x0; // todo
operand();
registers.lastInstructionOpcode = opcode;
} else
cpu.halt(`Unknown FPU opcode 0x${opcode.toString(16).toUpperCase()}`);
}
/**
* Checks FPU operand flags and sets them
*
* @param {number} a
* @param {number} b
* @returns {boolean}
* @memberof X87
*/
checkOperandFlags(a: number, b: number): boolean {
const {registers} = this;
if (Number.isNaN(a) || Number.isNaN(b) || !Number.isFinite(a) || !Number.isFinite(b)) {
registers.invalidOperation = true;
if (!registers.invalidOpExceptionMask)
throw new X87Error(X87ErrorCode.INVALID_ARITHMETIC_OPERATION);
return false;
}
return true;
}
/**
* Divides number by number, if b zero throws div exception
*
* @param {number} a
* @param {number} b
* @returns {number}
* @memberof X87
*/
fdiv(a: number, b: number): number {
const {registers} = this;
if (!b) {
registers.zeroDivide = true;
if (!registers.zeroDivExceptionMask)
throw new X87Error(X87ErrorCode.DIVIDE_BY_ZERO);
} else {
registers.zeroDivide = false;
this.checkOperandFlags(a, b);
}
return a / b;
}
/**
* Substract values, check flags
*
* @param {number} a
* @param {number} b
* @returns {number}
* @memberof X87
*/
fsub(a: number, b: number): number {
this.checkOperandFlags(a, b);
return a - b;
}
/**
* Add values, check flags
*
* @param {number} a
* @param {number} b
* @returns {number}
* @memberof X87
*/
fadd(a: number, b: number): number {
this.checkOperandFlags(a, b);
return a + b;
}
/**
* Multiplies values, check flags
*
* @param {number} a
* @param {number} b
* @returns {number}
* @memberof X87
*/
fmul(a: number, b: number): number {
this.checkOperandFlags(a, b);
return a * b;
}
/**
* Compares two numbers
*
* @param {number} a Generally should be st0
* @param {number} b
* @memberof X87
*/
fcom(a: number, b: number): void {
const {registers: regs} = this;
if (!this.checkOperandFlags(a, b)) {
regs.c3 = true; regs.c2 = true; regs.c0 = true;
} else if (a > b) {
regs.c3 = false; regs.c2 = false; regs.c0 = false;
} else if (a < b) {
regs.c3 = false; regs.c2 = false; regs.c0 = true;
} else if (a === b) {
regs.c3 = true; regs.c2 = false; regs.c0 = false;
}
}
/**
* @todo
* Add unordered compare
*
* @param {number} a
* @param {number} b
* @memberof X87
*/
fucom(a: number, b: number): void {
this.fcom(a, b);
}
/**
* Checks number and sets flags
*
* @param {number} a
* @memberof X87
*/
fxam(): void {
const {registers: regs} = this;
const num = regs.st0;
if (Number.isNaN(num)) {
regs.c3 = false; regs.c2 = false; regs.c0 = false;
} else if (!Number.isFinite(num)) {
regs.c3 = false; regs.c2 = true; regs.c0 = true;
} else if (!num) {
regs.c3 = true; regs.c2 = false; regs.c0 = false;
} else if (regs.getNthTag(0) === X87Tag.EMPTY) {
regs.c3 = true; regs.c2 = false; regs.c0 = true;
} else {
regs.c3 = false; regs.c2 = true; regs.c0 = false;
}
// todo: add unsupported, denormal
}
/**
* Stores ST0 at address
*
* @param {number} byteSize
* @param {number} destAddress
* @memberof X87
*/
fist(byteSize: number, destAddress: number): void {
const {cpu, registers} = this;
const long = Long.fromNumber(registers.st0).toBytesBE();
long.splice(0, long.length - byteSize);
cpu.memIO.writeBytesLE(destAddress, long);
}
/**
* Store FPU env
*
* @see {@link https://www.felixcloutier.com/x86/fstenv:fnstenv}
* @see {@link https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-vol-1-manual.pdf}
* Figure 8-10. Real Mode x87 FPU State Image in Memory, 32-Bit Format
*
* @see
* Not sure if it is correct for real mode
*
* @param {number} destAddress
* @returns write bytes count
* @memberof X87
*/
fstenv(destAddress: number): number {
const {cpu: {memIO}, registers: regs} = this;
let offset = 0;
memIO.write[0x2](regs.control, destAddress); offset += 2;
memIO.write[0x2](regs.status, destAddress + offset); offset += 2;
memIO.write[0x2](regs.tags, destAddress + offset); offset += 2;
memIO.write[0x2](regs.fip, destAddress + offset); offset += 2;
memIO.write[0x2](regs.fcs, destAddress + offset); offset += 2;
memIO.write[0x2](regs.fdp, destAddress + offset); offset += 2;
memIO.write[0x2](regs.fds, destAddress + offset); offset += 2;
return offset;
}
/**
* Load env
*
* @see
* Not sure if it is correct for real mode
*
* @param {number} srcAddress
* @returns read bytes
* @memberof X87
*/
fldenv(srcAddress: number): number {
const {cpu: {memIO}, registers: regs} = this;
let offset = 0;
regs.control = memIO.read[0x2](srcAddress); offset += 2;
regs.setStatus(memIO.read[0x2](srcAddress + offset)); offset += 2;
regs.tags = memIO.read[0x2](srcAddress + offset); offset += 2;
regs.fip = memIO.read[0x2](srcAddress + offset); offset += 2;
regs.fcs = memIO.read[0x2](srcAddress + offset); offset += 2;
regs.fdp = memIO.read[0x2](srcAddress + offset); offset += 2;
regs.fds = memIO.read[0x2](srcAddress + offset); offset += 2;
return offset;
}
/**
* Saves whole FPU state into mem addr
*
* @param {number} destAddress
* @memberof X87
*/
fsave(destAddress: number): void {
const {cpu: {memIO}, registers: regs} = this;
let offset = this.fstenv(destAddress);
for (let i = 0; i < 8; ++i) {
memIO.ieee754.write.extended(regs.nth(i), destAddress + offset);
offset += 10;
}
regs.reset();
}
/**
* Loads whole FPU state from mem addr
*
* @param {number} srcAddress
* @memberof X87
*/
frstor(srcAddress: number): void {
const {cpu: {memIO}, registers: regs} = this;
let offset = this.fldenv(srcAddress);
for (let i = 0; i < 8; ++i) {
regs.setNthValue(i, memIO.ieee754.read.extended(srcAddress + offset), true);
offset += 10;
}
}
/**
* Loads FPU
*
* @returns
* @memberof X87
*/
init() {
this.registers = new X87RegsStore;
this.opcodes = [];
const {cpu, registers: regs} = this;
const {memIO} = cpu;
const {ieee754: ieee754Mem} = memIO;
Object.assign(this.opcodes, {
0x9B: () => {
const bits = cpu.fetchOpcode(0x2, false);
switch (bits) {
/* FINIT */ case 0xE3DB:
regs.reset();
cpu.incrementIP(0x2);
break;
/* FCLEX */ case 0xE2DB:
regs.status = 0x0;
cpu.incrementIP(0x2);
break;
/* FENI */ case 0xE0DB:
/* FDISI */ case 0xE1DB:
cpu.incrementIP(0x2);
break;
default:
/* FWAIT */
}
},
0xD8: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch: (byte) => {
/* D8 C0+i FADD ST(0), ST(i) */
if (byte >= 0xC0 && byte <= 0xC7) {
regs.setNthValue(0x0, this.fadd(regs.st0, regs.nth(byte - 0xC0)));
return 1;
}
/* D8 C8+i FMUL ST(0), ST(i) */
if (byte >= 0xC8 && byte <= 0xCF) {
regs.setNthValue(0x0, this.fmul(regs.st0, regs.nth(byte - 0xC8)));
return 1;
}
/* D8 D0+i FCOM ST(i) */
if (byte >= 0xD0 && byte <= 0xD7) {
this.fcom(regs.st0, regs.nth(byte - 0xD0));
return 1;
}
/* D8 D8+i FCOMP ST(i) */
if (byte >= 0xD8 && byte <= 0xDF) {
this.fcom(regs.st0, regs.nth(byte - 0xD8));
regs.safePop();
return 1;
}
/* D8 E0+i FSUB ST(0), ST(i) */
if (byte >= 0xE0 && byte <= 0xE7) {
regs.setNthValue(0x0, this.fsub(regs.st0, regs.nth(byte - 0xE0)));
return 1;
}
/* D8 E8+i FSUBR ST(0), ST(i) */
if (byte >= 0xE8 && byte <= 0xEF) {
regs.setNthValue(0x0, this.fsub(regs.nth(byte - 0xE8), regs.st0));
return 1;
}
/* D8 F0+i FDIV ST(0), ST(i) */
if (byte >= 0xF0 && byte <= 0xF7) {
regs.setNthValue(0x0, this.fdiv(regs.st0, regs.nth(byte - 0xF0)));
return 1;
}
/* D8 F8+i FDIVR ST(0), ST(i) */
if (byte >= 0xF8 && byte <= 0xFF) {
regs.setNthValue(0x0, this.fdiv(regs.nth(byte - 0xF8), regs.st0));
return 1;
}
return 0;
},
/* FADD mdr(32) */ 0x0: (address) => { regs.setNthValue(0x0, this.fadd(regs.st0, ieee754Mem.read.single(address))); },
/* FMUL mdr(32) */ 0x1: (address) => { regs.setNthValue(0x0, this.fmul(regs.st0, ieee754Mem.read.single(address))); },
/* FCOM mdr(32) */ 0x2: (address) => { this.fcom(regs.st0, ieee754Mem.read.single(address)); },
/* FCOMP mdr(32) */ 0x3: (address) => {
this.fcom(regs.st0, ieee754Mem.read.single(address));
regs.safePop();
},
/* FSUB mdr(32) */ 0x4: (address) => { regs.setNthValue(0x0, this.fsub(regs.st0, ieee754Mem.read.single(address))); },
/* FSUBR mdr(32) */ 0x5: (address) => { regs.setNthValue(0x0, this.fsub(ieee754Mem.read.single(address), regs.st0)); },
/* FDIV mdr(32) */ 0x6: (address) => { regs.setNthValue(0x0, this.fdiv(regs.st0, ieee754Mem.read.single(address))); },
/* FDIVR mdr(32) */ 0x7: (address) => { regs.setNthValue(0x0, this.fdiv(ieee754Mem.read.single(address), regs.st0)); },
}),
0xD9: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch: (byte) => {
switch (byte) {
/* FNOP */ case 0xD0: return 1;
/* FCHS */ case 0xE0: regs.setNthValue(0x0, -regs.st0); return 1;
/* FABS */ case 0xE1: regs.setNthValue(0x0, Math.abs(regs.st0)); return 1;
/* FTST */ case 0xE4: this.fcom(regs.st0, 0.0); return 1;
/* FXAM */ case 0xE5: this.fxam(); return 1;
/* FLD1 */ case 0xE8: regs.safePush(X87.PREDEFINED_CONSTANTS.ONE); return 1;
/* FLDL2T */ case 0xE9: regs.safePush(X87.PREDEFINED_CONSTANTS.L2T); return 1;
/* FLDL2E */ case 0xEA: regs.safePush(X87.PREDEFINED_CONSTANTS.L2E); return 1;
/* FLDPI */ case 0xEB: regs.safePush(X87.PREDEFINED_CONSTANTS.PI); return 1;
/* FLDLG2 */ case 0xEC: regs.safePush(X87.PREDEFINED_CONSTANTS.LG2); return 1;
/* FLDLN2 */ case 0xED: regs.safePush(X87.PREDEFINED_CONSTANTS.LN2); return 1;
/* FLDZ */ case 0xEE: regs.safePush(X87.PREDEFINED_CONSTANTS.ZERO); return 1;
/* F2XM1 */ case 0xF0: regs.setNthValue(0x0, (2 ** regs.st0) - 1); return 1;
/* FYL2X */ case 0xF1:
regs.setNthValue(0x1, regs.st1 * Math.log2(regs.st0));
regs.safePop();
return 1;
/* FPTAN */ case 0xF2:
regs.setNthValue(0x0, Math.tan(regs.st0));
regs.safePush(1.0);
return 1;
/* FPATAN */ case 0xF3:
regs.setNthValue(0x1, Math.atan(this.fdiv(regs.st1, regs.st0)));
regs.safePop();
return 1;
/* FXTRACT */ case 0xF4: {
const {exponent, mantissa} = X87.numberParts(regs.st0);
regs.setNthValue(0x0, exponent);
regs.safePush(mantissa);
} return 1;
/* FPREM1 */ case 0xF5: regs.setNthValue(0x0, regs.st0 % regs.st1); return 1;
/* FDECSTP */ case 0xF6: regs.setStackPointer(regs.stackPointer - 0x1); return 1;
/* FINCSTP */ case 0xF7: regs.setStackPointer(regs.stackPointer + 0x1); return 1;
/* FPREM */ case 0xF8: {
const [st0, st1] = [regs.st0, regs.st1];
const quotient = Math.trunc(st0 / st1);
regs.setNthValue(0x0, st0 % st1);
regs.c2 = false;
if (quotient & 1)
regs.c1 = true;
if (quotient & (1 << 1))
regs.c3 = true;
if (quotient & (1 << 2))
regs.c0 = true;
} return 1;
/* FYL2XP1 */ case 0xF9:
regs.setNthValue(0x1, regs.st1 * Math.log2(regs.st0 + 1));
regs.safePop();
return 1;
/* FSINCOS */ case 0xFB: {
const rad = regs.st0;
regs.setNthValue(0x0, Math.sin(rad));
regs.safePush(Math.cos(rad));
} return 1;
/* FSQRT */ case 0xFA: regs.setNthValue(0x0, Math.sqrt(regs.st0)); return 1;
/* FRND */ case 0xFC: regs.setNthValue(0x0, Math.round(regs.st0)); return 1;
/* FSCALE */ case 0xFD: regs.setNthValue(0x0, regs.st0 * (0x2 ** X87.truncate(regs.st1))); return 1;
/* FSIN */ case 0xFE: regs.setNthValue(0x0, Math.sin(regs.st0)); return 1;
/* FCOS */ case 0xFF: regs.setNthValue(0x0, Math.cos(regs.st0)); return 1;
default:
}
/* FLD st(i), C0+i */
if (byte >= 0xC0 && byte <= 0xC7) {
regs.safePush(regs[byte - 0xC0]);
return 1;
}
/* FXCH st(i), C8+i */
if (byte >= 0xC8 && byte <= 0xCF) {
const cached = regs.st0;
const destIndex = byte - 0xC8;
regs.setNthValue(0, regs.nth(destIndex));
regs.setNthValue(destIndex, cached);
return 1;
}
return 0;
},
/* FLD mdr(32) D9 /0 d0 d1 */ 0x0: (address) => { regs.safePush(ieee754Mem.read.single(address)); },
/* FST mdr(32) D9 /2 d0 d1 */ 0x2: (address) => { ieee754Mem.write.single(regs.st0, address); },
/* FSTP mdr(32) D9 /3 d0 d1 */ 0x3: (address) => { ieee754Mem.write.single(regs.safePop(), address); },
/* FLDENV m14/28byte */ 0x4: (address) => { this.fldenv(address); },
/* FLDCW mw */ 0x5: (address) => { regs.control = memIO.read[0x2](address); },
/* FSTENV m14/28byte */ 0x6: (address) => { this.fstenv(address); },
/* FNSTCW m2byte */ 0x7: (address) => { memIO.write[0x2](regs.control, address); },
}),
0xDB: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch(byte) {
switch (byte) {
/* FNCLEX */ case 0xE2:
regs.status &= 0b0111111100000000;
return 1;
/* FNENI */ case 0xE0:
/* FDISI */ case 0xE1:
/* FNINIT */ case 0xE3:
/* FSETPM */ case 0xE4:
return 1;
default:
return 0;
}
},
/* FILD mdr(32) DB /0 d0 d1 */ 0x0: (address) => {
regs.safePush(
X86AbstractCPU.getSignedNumber(memIO.read[0x4](address), 0x4),
);
},
/* FIST m32int */ 0x2: (address) => this.fist(0x4, address),
/* FIST m32int */ 0x3: (address) => {
this.fist(0x4, address);
regs.safePop();
},
/* FLD mtr(80) DB /5 d0 d1 */ 0x5: (address) => { regs.safePush(ieee754Mem.read.extended(address)); },
/* FSTP mtr(80) DB /7 d0 d1 */ 0x7: (address) => { ieee754Mem.write.extended(regs.safePop(), address); },
}),
0xDA: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch(byte) {
/* FUCOMPP */ if (byte === 0xE9) {
this.fucom(regs.st0, regs.st1);
regs.safePop(); // pops twice
regs.safePop();
}
return 0;
},
/* FIADD mdr(32) DA /0 */ 0x0: (address) => {
regs.setNthValue(0, this.fadd(memIO.readSignedInt(address, 0x4), regs.st0));
},
/* FIMUL mdr(32) DA /1 */ 0x1: (address) => {
regs.setNthValue(0, this.fmul(memIO.readSignedInt(address, 0x4), regs.st0));
},
/* FICOM DA /2 m32int */ 0x2: (address) => {
this.fcom(regs.st0, memIO.readSignedInt(address, 0x4));
},
/* FICOMP DA /3 m32int */ 0x3: (address) => {
this.fcom(regs.st0, memIO.readSignedInt(address, 0x4));
regs.safePop();
},
/* FISUB mdr(32) DA /4 */ 0x4: (address) => {
regs.setNthValue(0, this.fsub(regs.st0, memIO.readSignedInt(address, 0x4)));
},
/* FISUBR mdr(32) DA /5 */ 0x5: (address) => {
regs.setNthValue(0, this.fsub(memIO.readSignedInt(address, 0x4), regs.st0));
},
/* FIDIV mdr(32) DA /6 */ 0x6: (address) => {
regs.setNthValue(0, this.fdiv(regs.st0, memIO.readSignedInt(address, 0x4)));
},
/* FIDIVR mdr(32) DA /7 */ 0x7: (address) => {
regs.setNthValue(0, this.fdiv(memIO.readSignedInt(address, 0x4), regs.st0));
},
}),
0xDC: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch: (byte) => {
/* FADD ST(i), ST(0) DC C0+i */
if (byte >= 0xC0 && byte <= 0xC7) {
const registerIndex = byte - 0xC0;
regs.setNthValue(registerIndex, this.fadd(regs.nth(registerIndex), regs.st0));
return 1;
}
/* FMUL ST(i), ST(0) DC C8+i */
if (byte >= 0xC8 && byte <= 0xCF) {
const registerIndex = byte - 0xC8;
regs.setNthValue(registerIndex, this.fmul(regs.nth(registerIndex), regs.st0));
return 1;
}
/* FSUBR ST(i), ST(0) DC E8+i */
if (byte >= 0xE0 && byte <= 0xE7) {
const registerIndex = byte - 0xE0;
regs.setNthValue(registerIndex, this.fsub(regs.st0, regs.nth(registerIndex)));
return 1;
}
/* FSUB ST(i), ST(0) DC E8+i */
if (byte >= 0xE8 && byte <= 0xEF) {
const registerIndex = byte - 0xE8;
regs.setNthValue(registerIndex, this.fsub(regs.nth(registerIndex), regs.st0));
return 1;
}
/* FDIVR ST(i), ST(0) DC F0+i */
if (byte >= 0xF0 && byte <= 0xF7) {
const registerIndex = byte - 0xF0;
regs.setNthValue(registerIndex, this.fdiv(regs.st0, regs.nth(registerIndex)));
return 1;
}
/* FDIV ST(i), ST(0) DC F8+i */
if (byte >= 0xF8 && byte <= 0xFF) {
const registerIndex = byte - 0xF8;
regs.setNthValue(registerIndex, this.fdiv(regs.nth(registerIndex), regs.st0));
return 1;
}
return 0;
},
/* FADD mqr(64) */ 0x0: (address) => { regs.setNthValue(0x0, this.fadd(regs.st0, ieee754Mem.read.double(address))); },
/* FMUL mqr(64) */ 0x1: (address) => { regs.setNthValue(0x0, this.fmul(regs.st0, ieee754Mem.read.double(address))); },
/* FCOM mqr(64) */ 0x2: (address) => { this.fcom(regs.st0, ieee754Mem.read.double(address)); },
/* FCOMP mqr(64) */ 0x3: (address) => {
this.fcom(regs.st0, ieee754Mem.read.double(address));
regs.safePop();
},
/* FSUB mqr(64) */ 0x4: (address) => { regs.setNthValue(0x0, this.fsub(regs.st0, ieee754Mem.read.double(address))); },
/* FSUB mqr(64) */ 0x5: (address) => { regs.setNthValue(0x0, this.fsub(ieee754Mem.read.double(address), regs.st0)); },
/* FDIV mqr(64) */ 0x6: (address) => { regs.setNthValue(0x0, this.fdiv(regs.st0, ieee754Mem.read.double(address))); },
/* FDIVR mqr(64) */ 0x7: (address) => { regs.setNthValue(0x0, this.fdiv(ieee754Mem.read.double(address), regs.st0)); },
}),
0xDD: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch: (byte) => {
/* FUCOM ST(i) */ if (byte >= 0xE0 && byte <= 0xE7) {
this.fucom(regs.st0, regs.nth(byte - 0xE0));
return 1;
}
/* FUCOMP ST(i) */ if (byte >= 0xE8 && byte <= 0xEF) {
this.fucom(regs.st0, regs.nth(byte - 0xE8));
regs.safePop();
return 1;
}
/* FFREE st(i) DD C0+i */
if (byte >= 0xC0 && byte <= 0xC7) {
regs.setNthTag(byte - 0xC0, X87Tag.EMPTY);
return 1;
}
/* FST st(i) DD D0+i */
if (byte >= 0xD0 && byte <= 0xD7) {
regs.setNthValue(byte - 0xD0, regs.st0);
return 1;
}
/* FSTP st(i) DD D8+i */
if (byte >= 0xD8 && byte <= 0xDF) {
regs.setNthValue(byte - 0xD8, regs.st0);
regs.safePop();
return 1;
}
return 0;
},
/* FLD mqr(64) DD /0 d0 d1 */ 0x0: (address) => { regs.safePush(ieee754Mem.read.double(address)); },
/* FST mqr(64) DD /2 d0 d1 */ 0x2: (address) => { ieee754Mem.write.double(regs.st0, address); },
/* FSTP mqr(64) DD /3 d0 d1 */ 0x3: (address) => { ieee754Mem.write.double(regs.safePop(), address); },
/* FRSTR m94 */ 0x4: (address) => { this.frstor(address); },
/* FSAVE m94 */ 0x6: (address) => { this.fsave(address); },
/* FNSTSW m2byte */ 0x7: (address) => { memIO.write[0x2](regs.status, address); },
}),
0xDE: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch: (byte) => {
/* FCOMPP (pops twice) */
if (byte === 0xD9) {
this.fcom(regs.st0, regs.st1);
regs.safePop();
regs.safePop();
return 1;
}
/* FADDP ST(i), ST(0) DE C8+i */
if (byte >= 0xC0 && byte <= 0xC7) {
const registerIndex = byte - 0xC0;
regs.setNthValue(registerIndex, this.fadd(regs.nth(registerIndex), regs.st0));
regs.safePop();
return 1;
}
/* FMULP ST(i), ST(0) DE C8+i */
if (byte >= 0xC8 && byte <= 0xCF) {
const registerIndex = byte - 0xC8;
regs.setNthValue(registerIndex, this.fmul(regs.nth(registerIndex), regs.st0));
regs.safePop();
return 1;
}
/* FSUBRP ST(i), ST(0) DE E0+i */
if (byte >= 0xE0 && byte <= 0xE7) {
const registerIndex = byte - 0xE0;
regs.setNthValue(registerIndex, this.fsub(regs.st0, regs.nth(registerIndex)));
regs.safePop();
return 1;
}
/* FSUBP ST(i), ST(0) DE E8+i */
if (byte >= 0xE8 && byte <= 0xEF) {
const registerIndex = byte - 0xE8;
regs.setNthValue(registerIndex, this.fsub(regs.nth(registerIndex), regs.st0));
regs.safePop();
return 1;
}
/* FDIVRP ST(i), ST(0) DE F0+i */
if (byte >= 0xF0 && byte <= 0xF7) {
const registerIndex = byte - 0xF0;
regs.setNthValue(registerIndex, this.fdiv(regs.st0, regs.nth(registerIndex)));
regs.safePop();
return 1;
}
/* FDIVP ST(i), ST(0) DE F8+i */
if (byte >= 0xF8 && byte <= 0xFF) {
const registerIndex = byte - 0xF8;
regs.setNthValue(registerIndex, this.fdiv(regs.nth(registerIndex), regs.st0));
regs.safePop();
return 1;
}
return 0;
},
/* FIADD mw(16) DE /0 */ 0x0: (address) => {
regs.setNthValue(0, this.fadd(regs.st0, memIO.readSignedInt(address, 0x2)));
},
/* FIMUL mw(16) DE /1 */ 0x1: (address) => {
regs.setNthValue(0, this.fmul(regs.st0, memIO.readSignedInt(address, 0x2)));
},
/* FICOM m16int DE /2 */ 0x2: (address) => {
this.fcom(regs.st0, memIO.readSignedInt(address, 0x2));
},
/* FICOMP m16int DE /3 */ 0x3: (address) => {
this.fcom(regs.st0, memIO.readSignedInt(address, 0x2));
regs.safePop();
},
/* FISUB mw(16) DE /4 */ 0x4: (address) => {
regs.setNthValue(0, this.fsub(regs.st0, memIO.readSignedInt(address, 0x2)));
},
/* FISUBR mw(16) DE /5 */ 0x5: (address) => {
regs.setNthValue(0, this.fsub(memIO.readSignedInt(address, 0x2), regs.st0));
},
/* FDIV mw(16) DE /6 */ 0x6: (address) => {
regs.setNthValue(0, this.fdiv(regs.st0, memIO.readSignedInt(address, 0x2)));
},
/* FDIVR mw(16) DE /7 */ 0x7: (address) => {
regs.setNthValue(0, this.fdiv(memIO.readSignedInt(address, 0x2), regs.st0));
},
}),
0xDF: X86InstructionSet.switchRMOpcodeInstruction(cpu, null, {
nonRMMatch(byte) {
/* FNSTSW ax */ if (byte === 0xE0) {
cpu.registers.ax = regs.status;
return 1;
}
return 0;
},
/* FILD m16int */ 0x0: (address) => {
regs.safePush(
X86AbstractCPU.getSignedNumber(memIO.read[0x2](address), 0x2),
);
},
/* FIST m16int */ 0x2: (address) => this.fist(0x2, address),
/* FISTP m16int */ 0x3: (address) => {
this.fist(0x2, address);
regs.safePop();
},
/* FILD m64int */ 0x5: (address) => {
const [low, high] = memIO.read[0x8](address);
regs.safePush(
new Long(low, high).toNumber(),
);
},
/* FISTP m64int */ 0x7: (address) => {
this.fist(0x8, address);
regs.safePop();
},
}),
});
}
} | the_stack |
import * as ESTree from 'estree';
import Scope from '../scope';
import { Value } from '../value';
import Signal from '../signal';
import Environment from '../environment';
import { slice, toString } from '../tool';
export function ExpressionStatement(env: Environment<ESTree.ExpressionStatement>) {
return env.evaluate(env.node.expression, { extra: env.extra });
}
export function BlockStatement(env: Environment<ESTree.BlockStatement>) {
let scope: Scope;
if (!env.scope.invasive) {
scope = env.createBlockScope();
} else {
scope = env.scope;
scope.invasive = false;
}
for (const node of env.node.body) {
if (node.type === 'FunctionDeclaration') {
env.evaluate(node, { scope });
} else if (node.type === 'VariableDeclaration' && node.kind === 'var') {
for (const declarator of node.declarations) {
scope.varDeclare((<ESTree.Identifier>declarator.id).name);
}
}
}
for (const node of env.node.body) {
if (node.type === 'FunctionDeclaration') {
continue;
}
const signal: Signal = env.evaluate(node, { scope, extra: env.extra });
if (Signal.isSignal(signal)) {
return signal;
}
}
}
export function VariableDeclaration(env: Environment<ESTree.VariableDeclaration>) {
for (const declarator of env.node.declarations) {
const v = declarator.init ? env.evaluate(declarator.init) : undefined;
declarePatternValue({ node: declarator.id, v, env, scope: env.scope, kind: env.node.kind });
}
}
export function ArrayExpression(env: Environment<ESTree.ArrayExpression>) {
let arr: any[] = [];
for (let element of env.node.elements) {
if (element.type !== 'SpreadElement') {
arr.push(env.evaluate(element));
} else {
arr = [...arr, ...env.evaluate(element.argument)];
}
}
return arr;
}
export function ObjectExpression(env: Environment<ESTree.ObjectExpression>) {
const obj: { [key: string]: any } = {};
for (const prop of env.node.properties) {
let key: string;
if (!prop.computed) {
if (prop.key.type === 'Identifier') {
key = prop.key.name;
} else {
key = (<ESTree.Literal>prop.key).value as string;
}
} else {
if (prop.key.type === 'Identifier') {
const value = env.scope.get(prop.key.name);
key = value.v;
} else {
key = env.evaluate(prop.key);
}
}
const value = env.evaluate(prop.value);
if (prop.kind === 'init') {
obj[key] = value;
} else if (prop.kind === 'get') {
Object.defineProperty(obj, key, { get: value });
} else if (prop.kind === 'set') {
Object.defineProperty(obj, key, { set: value });
} else {
throw new Error(`evil-eval: [ObjectExpression] Unsupported property kind "${prop.kind}"`);
}
}
return obj;
}
export function FunctionExpression(env: Environment<ESTree.FunctionExpression>) {
const node = env.node;
let fn: Function;
if (!node.generator) {
fn = function (this: any) {
const scope = env.createFunctionScope(true);
scope.constDeclare('this', this);
scope.constDeclare('arguments', arguments);
if (env.extra && env.extra.SuperClass) {
if (env.extra.isConstructor || env.extra.isStaticMethod) {
scope.constDeclare('@@evil-eval/super', env.extra.SuperClass);
} else if (env.extra.isMethod) {
scope.constDeclare('@@evil-eval/super', env.extra.SuperClass.prototype);
}
}
for (let i = 0, l = node.params.length; i < l; i++) {
const { name } = <ESTree.Identifier>node.params[i];
scope.varDeclare(name, arguments[i]);
}
const signal = env.evaluate(node.body, { scope, extra: env.extra });
if (Signal.isReturn(signal)) {
return signal.value;
}
};
} else {
throw new Error('evil-eval: Generator Function not implemented');
}
Object.defineProperties(fn, {
name: { value: node.id ? node.id.name : '' },
length: { value: node.params.length }
});
return fn;
}
export function CallExpression(env: Environment<ESTree.CallExpression>) {
const fn: Function = env.evaluate(env.node.callee);
const args = env.node.arguments.map(it => env.evaluate(it));
let thisValue: any;
if (env.node.callee.type === 'MemberExpression') {
if (env.node.callee.object.type !== 'Super') {
thisValue = env.evaluate(env.node.callee.object);
} else {
const value = env.scope.get('this');
thisValue = value.v;
}
} else if (env.extra && env.extra.isConstructor) {
const value = env.scope.get('this');
thisValue = value.v;
}
return fn.apply(thisValue, args);
}
// -- es2015 new feature --
export function ForOfStatement(env: Environment<ESTree.ForOfStatement>) {
const { left, right, body } = env.node;
let scope = env.scope;
for (const v of env.evaluate(right)) {
if (left.type === 'VariableDeclaration') {
if (left.kind === 'let' || left.kind === 'const') {
scope = env.createBlockScope(true);
}
const id = left.declarations[0].id;
// for (let it of list);
// for (let { id } of list);
declarePatternValue({ node: id, v, env, scope, kind: left.kind });
} else {
// for (it of list);
// for ({ id } of list);
declarePatternValue({ node: left, v, env, scope });
}
const signal: Signal = env.evaluate(body, { scope });
if (Signal.isSignal(signal)) {
if (Signal.isBreak(signal)) {
if (!signal.value || signal.value === env.label) break;
} else if (Signal.isContinue(signal)) {
if (!signal.value || signal.value === env.label) continue;
}
return signal;
}
}
}
export function Super(env: Environment<ESTree.Super>) {
const value = env.scope.get('@@evil-eval/super');
return value.v;
}
/**
* see: ArrayExpression
*/
export function SpreadElement(env: Environment<ESTree.SpreadElement>) {
throw new Error(`evil-eval: [SpreadElement] Should not happen`);
}
export function ArrowFunctionExpression(env: Environment<ESTree.ArrowFunctionExpression>) {
const node = env.node;
const fn = function (this: any) {
const scope = env.createFunctionScope(true);
for (let i = 0, l = node.params.length; i < l; i++) {
const { name } = <ESTree.Identifier>node.params[i];
scope.varDeclare(name, arguments[i]);
}
const signal = env.evaluate(node.body, { scope, extra: env.extra });
if (Signal.isReturn(signal)) {
return signal.value;
}
};
Object.defineProperties(fn, {
length: { value: node.params.length }
});
return fn;
}
export function YieldExpression(env: Environment<ESTree.YieldExpression>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function TemplateLiteral(env: Environment<ESTree.TemplateLiteral>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function TaggedTemplateExpression(env: Environment<ESTree.TaggedTemplateExpression>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function TemplateElement(env: Environment<ESTree.TemplateElement>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ObjectPattern(env: Environment<ESTree.ObjectPattern>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ArrayPattern(env: Environment<ESTree.ArrayPattern>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function RestElement(env: Environment<ESTree.RestElement>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function AssignmentPattern(env: Environment<ESTree.AssignmentPattern>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ClassBody(env: Environment<ESTree.ClassBody>) {
const body = env.node.body;
const ctor = body.find(n => n.kind === 'constructor');
let Class: Function;
if (ctor) {
Class = env.evaluate(ctor.value, { extra: { ...env.extra, isConstructor: true } });
} else {
Class = function () { }
}
if (env.extra && env.extra.SuperClass) {
extends_(Class, env.extra.SuperClass);
}
let staticProperties: PropertyDescriptorMap = {};
let properties: PropertyDescriptorMap = {};
for (const node of body) {
let key = (<ESTree.Identifier>node.key).name;
if (node.computed) {
const value = env.scope.get(key)
key = value.v;
}
let prop: PropertyDescriptor;
if (node.kind === 'method') {
if (!node.static) {
prop = properties[key];
if (!prop || !prop.value) {
prop = {
configurable: true,
enumerable: true
};
}
prop.value = env.evaluate(node.value, { extra: { ...env.extra, isMethod: true } });
properties[key] = prop;
} else {
prop = staticProperties[key];
if (!prop || !prop.value) {
prop = {
configurable: true,
enumerable: true
};
}
prop.value = env.evaluate(node.value, { extra: { ...env.extra, isStaticMethod: true } });
staticProperties[key] = prop;
}
} else if (node.kind === 'get') {
if (!node.static) {
prop = properties[key];
if (!prop || prop.value) {
prop = {
configurable: true,
enumerable: true
};
}
prop.get = env.evaluate(node.value);
properties[key] = prop;
} else {
prop = staticProperties[key];
if (!prop || prop.value) {
prop = {
configurable: true,
enumerable: true
};
}
prop.get = env.evaluate(node.value);
staticProperties[key] = prop;
}
} else if (node.kind === 'set') {
if (!node.static) {
prop = properties[key];
if (!prop || prop.value) {
prop = {
configurable: true,
enumerable: true
};
}
prop.set = env.evaluate(node.value);
properties[key] = prop;
} else {
prop = staticProperties[key];
if (!prop || prop.value) {
prop = {
configurable: true,
enumerable: true
};
}
prop.set = env.evaluate(node.value);
staticProperties[key] = prop;
}
}
}
Object.defineProperties(Class, staticProperties);
Object.defineProperties(Class.prototype, properties);
return Class;
}
/**
* see: ClassBody
*/
export function MethodDefinition(env: Environment<ESTree.MethodDefinition>) {
throw new Error(`evil-eval: [MethodDefinition] Should not happen`);
}
export function ClassDeclaration(env: Environment<ESTree.ClassDeclaration>) {
const Class = ClassExpression(<any>env);
env.scope.constDeclare(env.node.id.name, Class);
return Class;
}
export function ClassExpression(env: Environment<ESTree.ClassExpression>) {
const { node } = env;
let SuperClass;
if (node.superClass) {
SuperClass = env.evaluate(node.superClass);
}
const Class = env.evaluate(node.body, { extra: { SuperClass } });
if (node.id) {
Object.defineProperty(Class, 'name', { value: node.id.name });
}
return Class;
}
export function MetaProperty(env: Environment<ESTree.MetaProperty>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ImportDeclaration(env: Environment<ESTree.ImportDeclaration>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ImportSpecifier(env: Environment<ESTree.ImportSpecifier>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ImportDefaultSpecifier(env: Environment<ESTree.ImportDefaultSpecifier>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ImportNamespaceSpecifier(env: Environment<ESTree.ImportNamespaceSpecifier>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ExportNamedDeclaration(env: Environment<ESTree.ExportNamedDeclaration>) {
const { node, scope } = env;
const exportsValue = scope.get('exports');
if (node.declaration) {
if (node.declaration.type === 'VariableDeclaration') {
for (const declarator of node.declaration.declarations) {
const v = env.evaluate(declarator.init!);
const declarationNames: string[] = [];
declarePatternValue({ node: declarator.id, v, env, scope: env.scope, kind: node.declaration.kind, declarationNames });
for (const name of declarationNames) {
exportsValue.v[name] = scope.get(name).v;
}
}
} else {
exportsValue.v[node.declaration.id.name] = env.evaluate(node.declaration);
}
} else {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
}
export function ExportSpecifier(env: Environment<ESTree.ExportSpecifier>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
export function ExportDefaultDeclaration(env: Environment<ESTree.ExportDefaultDeclaration>) {
const value = env.scope.get('exports')
value.v.default = env.evaluate(env.node.declaration);
}
export function ExportAllDeclaration(env: Environment<ESTree.ExportAllDeclaration>) {
throw new Error(`evil-eval: "${env.node.type}" not implemented`);
}
// -- private --
interface DeclarePatternValueOptions<T> {
node: T;
v: any;
env: Environment<ESTree.Node>;
scope: Scope;
kind?: 'var' | 'let' | 'const';
declarationNames?: string[];
}
function declarePatternValue(options: DeclarePatternValueOptions<ESTree.Pattern>) {
if (options.node.type === 'Identifier') {
if (options.kind) {
options.scope.declare(options.node.name, options.v, options.kind);
options.declarationNames && options.declarationNames.push(options.node.name);
} else {
const value = options.scope.get(options.node.name, true);
value.v = options.v;
}
} else if (options.node.type === 'ObjectPattern') {
declareObjectPatternValue(<DeclarePatternValueOptions<ESTree.ObjectPattern>>options);
} else if (options.node.type === 'ArrayPattern') {
declareArrayPatternValue(<DeclarePatternValueOptions<ESTree.ArrayPattern>>options);
} else {
throw new Error(`evil-eval: Not support to declare pattern value of node type "${options.node.type}"`);
}
}
function declareObjectPatternValue({ node, v: vObj, env, scope, kind, declarationNames }: DeclarePatternValueOptions<ESTree.ObjectPattern>) {
for (const prop of node.properties) {
let key: string;
if (!prop.computed) {
if (prop.key.type === 'Identifier') {
key = prop.key.name;
} else {
key = (<ESTree.Literal>prop.key).value as string;
}
} else {
key = env.evaluate(prop.key);
}
const v = vObj[key];
if (prop.value.type === 'Identifier') {
if (v === null || v === undefined) {
throw new TypeError(`Cannot destructure property \`${key}\` of 'undefined' or 'null'.`)
}
if (kind) {
scope.declare(prop.value.name, v, kind);
declarationNames && declarationNames.push(prop.value.name);
} else {
const value = scope.get(prop.value.name, true);
value.v = v;
}
} else {
declarePatternValue({ node: prop.value, v, env, scope, kind, declarationNames });
}
}
}
function declareArrayPatternValue({ node, v: vArr, env, scope, kind, declarationNames }: DeclarePatternValueOptions<ESTree.ArrayPattern>) {
for (let i = 0, l = node.elements.length; i < l; i++) {
const element = node.elements[i];
let v = vArr[i];
if (element.type === 'Identifier') {
if (v === undefined) {
throw new TypeError(`Cannot read property 'Symbol(Symbol.iterator)' of undefined`);
} else if (v === null) {
throw new TypeError(`Cannot read property 'Symbol(Symbol.iterator)' of object`);
}
if (kind) {
scope.declare(element.name, v, kind);
declarationNames && declarationNames.push(element.name);
} else {
const value = scope.get(element.name, true);
value.v = v;
}
} else if (element.type === 'RestElement') {
const name = (<ESTree.Identifier>element.argument).name;
v = slice.call(vArr, i);
if (kind) {
scope.declare(name, v, kind);
declarationNames && declarationNames.push(name);
} else {
const value = scope.get(name, true);
value.v = v;
}
} else {
declarePatternValue({ node: element, v, env, scope, kind, declarationNames });
}
}
}
const extendStatics = Object.setPrototypeOf
|| ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; })
|| function (Class: any, SuperClass: any) { for (var p in SuperClass) if (SuperClass.hasOwnProperty(p)) Class[p] = SuperClass[p]; };
function extends_(Class: Function, SuperClass: Function) {
extendStatics(Class, SuperClass);
function __(this: any) { this.constructor = Class; }
Class.prototype = SuperClass === null
? Object.create(SuperClass)
: (__.prototype = SuperClass.prototype, new (<{ new(): any; }><any>__)());
} | the_stack |
import { Activity, TurnContext, TurnContextStateCollection } from 'botbuilder-core';
import { Choice } from './choices';
import { Dialog, DialogInstance, DialogReason, DialogTurnResult, DialogTurnStatus, DialogEvent } from './dialog';
import { DialogSet } from './dialogSet';
import { PromptOptions } from './prompts';
import { DialogStateManager, TurnPath } from './memory';
import { DialogContainer } from './dialogContainer';
import { DialogEvents } from './dialogEvents';
import { DialogManager } from './dialogManager';
import { DialogTurnStateConstants } from './dialogTurnStateConstants';
import { DialogContextError } from './dialogContextError';
/**
* Wraps a promise in a try-catch that automatically enriches errors with extra dialog context.
*
* @param dialogContext source dialog context from which enriched error properties are sourced
* @param promise a promise to await inside a try-catch for error enrichment
*/
const wrapErrors = async <T>(dialogContext: DialogContext, promise: Promise<T>): Promise<T> => {
try {
return await promise;
} catch (err) {
if (err instanceof DialogContextError) {
throw err;
} else {
throw new DialogContextError(err, dialogContext);
}
}
};
/**
* @private
*/
const ACTIVITY_RECEIVED_EMITTED = Symbol('ActivityReceivedEmitted');
/**
* Contains dialog state, information about the state of the dialog stack, for a specific [DialogSet](xref:botbuilder-dialogs.DialogSet).
*
* @remarks
* State is read from and saved to storage each turn, and state cache for the turn is managed through
* the [TurnContext](xref:botbuilder-core.TurnContext).
*
* For more information, see the articles on
* [Managing state](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-state) and
* [Dialogs library](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog).
*/
export interface DialogState {
/**
* Contains state information for each [Dialog](xref:botbuilder-dialogs.Dialog) on the stack.
*/
dialogStack: DialogInstance[];
}
/**
* The context for the current dialog turn with respect to a specific [DialogSet](xref:botbuilder-dialogs.DialogSet).
*
* @remarks
* This includes the turn context, information about the dialog set, and the state of the dialog stack.
*
* From code outside of a dialog in the set, use [DialogSet.createContext](xref:botbuilder-dialogs.DialogSet.createContext)
* to create the dialog context. Then use the methods of the dialog context to manage the progression of dialogs in the set.
*
* When you implement a dialog, the dialog context is a parameter available to the various methods you override or implement.
*
* For example:
* ```JavaScript
* const dc = await dialogs.createContext(turnContext);
* const result = await dc.continueDialog();
* ```
*/
export class DialogContext {
/**
* Creates an new instance of the [DialogContext](xref:botbuilder-dialogs.DialogContext) class.
* @param dialogs The [DialogSet](xref:botbuilder-dialogs.DialogSet) for which to create the dialog context.
* @param contextOrDC The [TurnContext](xref:botbuilder-core.TurnContext) object for the current turn of the bot.
* @param state The state object to use to read and write [DialogState](xref:botbuilder-dialogs.DialogState) to storage.
* @remarks
* Passing in a [DialogContext](xref:botbuilder-dialogs.DialogContext) instance will clone the dialog context.
*/
constructor(dialogs: DialogSet, contextOrDC: TurnContext, state: DialogState);
/**
* Creates an new instance of the [DialogContext](xref:botbuilder-dialogs.DialogContext) class.
* @param dialogs The [DialogSet](xref:botbuilder-dialogs.DialogSet) for which to create the dialog context.
* @param contextOrDC The [DialogContext](xref:botbuilder-dialogs.DialogContext) object for the current turn of the bot.
* @param state The state object to use to read and write [DialogState](xref:botbuilder-dialogs.DialogState) to storage.
* @remarks
* Passing in a [DialogContext](xref:botbuilder-dialogs.DialogContext) instance will clone the dialog context.
*/
constructor(dialogs: DialogSet, contextOrDC: DialogContext, state: DialogState);
/**
* Creates an new instance of the [DialogContext](xref:botbuilder-dialogs.DialogContext) class.
* @param dialogs The [DialogSet](xref:botbuilder-dialogs.DialogSet) for which to create the dialog context.
* @param contextOrDC The [TurnContext](xref:botbuilder-core.TurnContext) or [DialogContext](xref:botbuilder-dialogs.DialogContext) for the current turn of the bot.
* @param state The state object to use to read and write [DialogState](xref:botbuilder-dialogs.DialogState) to storage.
* @remarks Passing in a [DialogContext](xref:botbuilder-dialogs.DialogContext) instance will clone the dialog context.
*/
constructor(dialogs: DialogSet, contextOrDC: TurnContext | DialogContext, state: DialogState) {
this.dialogs = dialogs;
if (contextOrDC instanceof DialogContext) {
this.context = contextOrDC.context;
this.parent = contextOrDC;
if (this.parent.services) {
this.parent.services.forEach((value, key): void => {
this.services.set(key, value);
});
}
} else {
this.context = contextOrDC;
}
if (!Array.isArray(state.dialogStack)) {
state.dialogStack = [];
}
this.stack = state.dialogStack;
this.state = new DialogStateManager(this);
this.state.setValue(TurnPath.activity, this.context.activity);
}
/**
* Gets the dialogs that can be called directly from this context.
*/
dialogs: DialogSet;
/**
* Gets the context object for the turn.
*/
context: TurnContext;
/**
* Gets the current dialog stack.
*/
stack: DialogInstance[];
/**
* The parent dialog context for this dialog context, or `undefined` if this context doesn't have a parent.
*
* @remarks
* When it attempts to start a dialog, the dialog context searches for the [Dialog.id](xref:botbuilder-dialogs.Dialog.id)
* in its [dialogs](xref:botbuilder-dialogs.DialogContext.dialogs). If the dialog to start is not found
* in this dialog context, it searches in its parent dialog context, and so on.
*/
parent: DialogContext | undefined;
/**
* Returns dialog context for child if the active dialog is a container.
*/
get child(): DialogContext | undefined {
const instance = this.activeDialog;
if (instance != undefined) {
// Is active dialog a container?
const dialog = this.findDialog(instance.id);
if (dialog instanceof DialogContainer) {
return dialog.createChildContext(this);
}
}
return undefined;
}
/**
* Returns the state information for the dialog on the top of the dialog stack, or `undefined` if
* the stack is empty.
*/
get activeDialog(): DialogInstance | undefined {
return this.stack.length > 0 ? this.stack[this.stack.length - 1] : undefined;
}
/**
* Gets the DialogStateManager which manages view of all memory scopes.
*/
state: DialogStateManager;
/**
* Gets the services collection which is contextual to this dialog context.
*/
services: TurnContextStateCollection = new TurnContextStateCollection();
/**
* Returns the current dialog manager instance. This property is obsolete.
*
* @obsolete This property serves no function.
*/
get dialogManager(): DialogManager {
return this.context.turnState.get(DialogTurnStateConstants.dialogManager);
}
/**
* Obtain the CultureInfo in DialogContext.
* @returns a locale string.
*/
getLocale(): string {
const _turnLocaleProperty = 'turn.locale';
const turnLocaleValue = this.state.getValue(_turnLocaleProperty);
if (turnLocaleValue) {
return turnLocaleValue;
}
const locale = this.context.activity?.locale;
if (locale !== undefined) {
return locale;
}
return Intl.DateTimeFormat().resolvedOptions().locale;
}
/**
* Starts a dialog instance and pushes it onto the dialog stack.
* Creates a new instance of the dialog and pushes it onto the stack.
*
* @param dialogId ID of the dialog to start.
* @param options Optional. Arguments to pass into the dialog when it starts.
*
* @remarks
* If there's already an active dialog on the stack, that dialog will be paused until
* it is again the top dialog on the stack.
*
* The [status](xref:botbuilder-dialogs.DialogTurnResult.status) of returned object describes
* the status of the dialog stack after this method completes.
*
* This method throws an exception if the requested dialog can't be found in this dialog context
* or any of its ancestors.
*
* For example:
* ```JavaScript
* const result = await dc.beginDialog('greeting', { name: user.name });
* ```
*
* **See also**
* - [endDialog](xref:botbuilder-dialogs.DialogContext.endDialog)
* - [prompt](xref:botbuilder-dialogs.DialogContext.prompt)
* - [replaceDialog](xref:botbuilder-dialogs.DialogContext.replaceDialog)
* - [Dialog.beginDialog](xref:botbuilder-dialogs.Dialog.beginDialog)
*/
async beginDialog(dialogId: string, options?: object): Promise<DialogTurnResult> {
// Lookup dialog
const dialog: Dialog<{}> = this.findDialog(dialogId);
if (!dialog) {
throw new DialogContextError(
`DialogContext.beginDialog(): A dialog with an id of '${dialogId}' wasn't found.`,
this
);
}
// Push new instance onto stack.
const instance: DialogInstance<any> = {
id: dialogId,
state: {},
};
this.stack.push(instance);
// Call dialogs begin() method.
return wrapErrors(this, dialog.beginDialog(this, options));
}
/**
* Cancels all dialogs on the dialog stack, and clears stack.
*
* @param cancelParents Optional. If `true` all parent dialogs will be cancelled as well.
* @param eventName Optional. Name of a custom event to raise as dialogs are cancelled. This defaults to [cancelDialog](xref:botbuilder-dialogs.DialogEvents.cancelDialog).
* @param eventValue Optional. Value to pass along with custom cancellation event.
*
* @remarks
* This calls each dialog's [Dialog.endDialog](xref:botbuilder-dialogs.Dialog.endDialog) method before
* removing the dialog from the stack.
*
* If there were any dialogs on the stack initially, the [status](xref:botbuilder-dialogs.DialogTurnResult.status)
* of the return value is [cancelled](xref:botbuilder-dialogs.DialogTurnStatus.cancelled); otherwise, it's
* [empty](xref:botbuilder-dialogs.DialogTurnStatus.empty).
*
* This example clears a dialog stack, `dc`, before starting a 'bookFlight' dialog.
* ```JavaScript
* await dc.cancelAllDialogs();
* return await dc.beginDialog('bookFlight');
* ```
*
* **See also**
* - [endDialog](xref:botbuilder-dialogs.DialogContext.endDialog)
*/
async cancelAllDialogs(
cancelParents = false,
eventName?: string,
eventValue?: any
): Promise<DialogTurnResult> {
eventName = eventName || DialogEvents.cancelDialog;
if (this.stack.length > 0 || this.parent != undefined) {
// Cancel all local and parent dialogs while checking for interception
let notify = false;
let dc: DialogContext = this;
while (dc != undefined) {
if (dc.stack.length > 0) {
// Check to see if the dialog wants to handle the event
// - We skip notifying the first dialog which actually called cancelAllDialogs()
if (notify) {
const handled = await dc.emitEvent(eventName, eventValue, false, false);
if (handled) {
break;
}
}
// End the active dialog
await dc.endActiveDialog(DialogReason.cancelCalled);
} else {
dc = cancelParents ? dc.parent : undefined;
}
notify = true;
}
return { status: DialogTurnStatus.cancelled };
} else {
return { status: DialogTurnStatus.empty };
}
}
/**
* Searches for a dialog with a given ID.
*
* @param dialogId ID of the dialog to search for.
*
* @remarks
* If the dialog to start is not found in the [DialogSet](xref:botbuilder-dialogs.DialogSet) associated
* with this dialog context, it attempts to find the dialog in its parent dialog context.
*
* **See also**
* - [dialogs](xref:botbuilder-dialogs.DialogContext.dialogs)
* - [parent](xref:botbuilder-dialogs.DialogContext.parent)
*/
findDialog(dialogId: string): Dialog | undefined {
let dialog = this.dialogs.find(dialogId);
if (!dialog && this.parent) {
dialog = this.parent.findDialog(dialogId);
}
return dialog;
}
/**
* Helper function to simplify formatting the options for calling a prompt dialog.
* @param dialogId ID of the prompt dialog to start.
* @param promptOrOptions The text of the initial prompt to send the user,
* the activity to send as the initial prompt, or
* the object with which to format the prompt dialog.
* @param choices Optional. Array of choices for the user to choose from,
* for use with a [ChoicePrompt](xref:botbuilder-dialogs.ChoicePrompt).
*
* @remarks
* This helper method formats the object to use as the `options` parameter, and then calls
* [beginDialog](xref:botbuilder-dialogs.DialogContext.beginDialog) to start the specified prompt dialog.
*
* ```JavaScript
* return await dc.prompt('confirmPrompt', `Are you sure you'd like to quit?`);
* ```
*/
async prompt(
dialogId: string,
promptOrOptions: string | Partial<Activity> | PromptOptions
): Promise<DialogTurnResult>;
/**
* Helper function to simplify formatting the options for calling a prompt dialog.
* @param dialogId ID of the prompt dialog to start.
* @param promptOrOptions The text of the initial prompt to send the user,
* the [Activity](xref:botframework-schema.Activity) to send as the initial prompt, or
* the object with which to format the prompt dialog.
* @param choices Optional. Array of choices for the user to choose from,
* for use with a [ChoicePrompt](xref:botbuilder-dialogs.ChoicePrompt).
* @remarks
* This helper method formats the object to use as the `options` parameter, and then calls
* [beginDialog](xref:botbuilder-dialogs.DialogContext.beginDialog) to start the specified prompt dialog.
*
* ```JavaScript
* return await dc.prompt('confirmPrompt', `Are you sure you'd like to quit?`);
* ```
*/
async prompt(
dialogId: string,
promptOrOptions: string | Partial<Activity> | PromptOptions,
choices: (string | Choice)[]
): Promise<DialogTurnResult>;
/**
* Helper function to simplify formatting the options for calling a prompt dialog.
* @param dialogId ID of the prompt dialog to start.
* @param promptOrOptions The text of the initial prompt to send the user,
* or the [Activity](xref:botframework-schema.Activity) to send as the initial prompt.
* @param choices Optional. Array of choices for the user to choose from,
* for use with a [ChoicePrompt](xref:botbuilder-dialogs.ChoicePrompt).
* @remarks This helper method formats the object to use as the `options` parameter, and then calls
* beginDialog to start the specified prompt dialog.
*
* ```JavaScript
* return await dc.prompt('confirmPrompt', `Are you sure you'd like to quit?`);
* ```
*/
async prompt(
dialogId: string,
promptOrOptions: string | Partial<Activity>,
choices?: (string | Choice)[]
): Promise<DialogTurnResult> {
let options: PromptOptions;
if (
(typeof promptOrOptions === 'object' && (promptOrOptions as Activity).type !== undefined) ||
typeof promptOrOptions === 'string'
) {
options = { prompt: promptOrOptions as string | Partial<Activity> };
} else {
options = { ...(promptOrOptions as PromptOptions) };
}
if (choices) {
options.choices = choices;
}
return wrapErrors(this, this.beginDialog(dialogId, options));
}
/**
* Continues execution of the active dialog, if there is one, by passing this dialog context to its
* [Dialog.continueDialog](xref:botbuilder-dialogs.Dialog.continueDialog) method.
*
* @remarks
* After the call completes, you can check the turn context's [responded](xref:botbuilder-core.TurnContext.responded)
* property to determine if the dialog sent a reply to the user.
*
* The [status](xref:botbuilder-dialogs.DialogTurnResult.status) of returned object describes
* the status of the dialog stack after this method completes.
*
* Typically, you would call this from within your bot's turn handler.
*
* For example:
* ```JavaScript
* const result = await dc.continueDialog();
* if (result.status == DialogTurnStatus.empty && dc.context.activity.type == ActivityTypes.message) {
* // Send fallback message
* await dc.context.sendActivity(`I'm sorry. I didn't understand.`);
* }
* ```
*/
async continueDialog(): Promise<DialogTurnResult> {
// if we are continuing and haven't emitted the activityReceived event, emit it
// NOTE: This is backward compatible way for activity received to be fired even if you have legacy dialog loop
if (!this.context.turnState.has(ACTIVITY_RECEIVED_EMITTED)) {
this.context.turnState.set(ACTIVITY_RECEIVED_EMITTED, true);
// Dispatch "activityReceived" event
// - This fired from teh leaf and will queue up any interruptions.
await this.emitEvent(DialogEvents.activityReceived, this.context.activity, true, true);
}
// Check for a dialog on the stack
const instance: DialogInstance<any> = this.activeDialog;
if (instance) {
// Lookup dialog
const dialog: Dialog<{}> = this.findDialog(instance.id);
if (!dialog) {
throw new DialogContextError(
`DialogContext.continueDialog(): Can't continue dialog. A dialog with an id of '${instance.id}' wasn't found.`,
this
);
}
// Continue execution of dialog
return wrapErrors(this, dialog.continueDialog(this));
} else {
return { status: DialogTurnStatus.empty };
}
}
/**
* Ends a dialog and pops it off the stack. Returns an optional result to the dialog's parent.
*
* @param result Optional. A result to pass to the parent logic. This might be the next dialog
* on the stack, or if this was the last dialog on the stack, a parent dialog context or
* the bot's turn handler.
*
* @remarks
* The _parent_ dialog is the next dialog on the dialog stack, if there is one. This method
* calls the parent's [Dialog.resumeDialog](xref:botbuilder-dialogs.Dialog.resumeDialog) method,
* passing the result returned by the ending dialog. If there is no parent dialog, the turn ends
* and the result is available to the bot through the returned object's
* [result](xref:botbuilder-dialogs.DialogTurnResult.result) property.
*
* The [status](xref:botbuilder-dialogs.DialogTurnResult.status) of returned object describes
* the status of the dialog stack after this method completes.
*
* Typically, you would call this from within the logic for a specific dialog to signal back to
* the dialog context that the dialog has completed, the dialog should be removed from the stack,
* and the parent dialog should resume.
*
* For example:
* ```JavaScript
* return await dc.endDialog(returnValue);
* ```
*
* **See also**
* - [beginDialog](xref:botbuilder-dialogs.DialogContext.beginDialog)
* - [replaceDialog](xref:botbuilder-dialogs.DialogContext.replaceDialog)
* - [Dialog.endDialog](xref:botbuilder-dialogs.Dialog.endDialog)
*/
async endDialog(result?: any): Promise<DialogTurnResult> {
// End the active dialog
await this.endActiveDialog(DialogReason.endCalled, result);
// Resume parent dialog
const instance: DialogInstance<any> = this.activeDialog;
if (instance) {
// Lookup dialog
const dialog: Dialog<{}> = this.findDialog(instance.id);
if (!dialog) {
throw new DialogContextError(
`DialogContext.endDialog(): Can't resume previous dialog. A dialog with an id of '${instance.id}' wasn't found.`,
this
);
}
// Return result to previous dialog
return wrapErrors(this, dialog.resumeDialog(this, DialogReason.endCalled, result));
} else {
// Signal completion
return { status: DialogTurnStatus.complete, result: result };
}
}
/**
* Ends the active dialog and starts a new dialog in its place.
*
* @param dialogId ID of the dialog to start.
* @param options Optional. Arguments to pass into the new dialog when it starts.
*
* @remarks
* This is particularly useful for creating a loop or redirecting to another dialog.
*
* The [status](xref:botbuilder-dialogs.DialogTurnResult.status) of returned object describes
* the status of the dialog stack after this method completes.
*
* This method is similar to ending the current dialog and immediately beginning the new one.
* However, the parent dialog is neither resumed nor otherwise notified.
*
* **See also**
* - [beginDialog](xref:botbuilder-dialogs.DialogContext.beginDialog)
* - [endDialog](xref:botbuilder-dialogs.DialogContext.endDialog)
*/
async replaceDialog(dialogId: string, options?: object): Promise<DialogTurnResult> {
// End the active dialog
await this.endActiveDialog(DialogReason.replaceCalled);
// Start replacement dialog
return this.beginDialog(dialogId, options);
}
/**
* Requests the active dialog to re-prompt the user for input.
*
* @remarks
* This calls the active dialog's [repromptDialog](xref:botbuilder-dialogs.Dialog.repromptDialog) method.
*
* For example:
* ```JavaScript
* await dc.repromptDialog();
* ```
*/
async repromptDialog(): Promise<void> {
// Try raising event first
const handled = await this.emitEvent(DialogEvents.repromptDialog, undefined, false, false);
if (!handled) {
// Check for a dialog on the stack
const instance: DialogInstance<any> = this.activeDialog;
if (instance) {
// Lookup dialog
const dialog: Dialog<{}> = this.findDialog(instance.id);
if (!dialog) {
throw new DialogContextError(
`DialogContext.repromptDialog(): Can't find a dialog with an id of '${instance.id}'.`,
this
);
}
// Ask dialog to re-prompt if supported
await wrapErrors(this, dialog.repromptDialog(this.context, instance));
}
}
}
/**
* Searches for a dialog with a given ID.
* @remarks
* Emits a named event for the current dialog, or someone who started it, to handle.
* @param name Name of the event to raise.
* @param value Optional. Value to send along with the event.
* @param bubble Optional. Flag to control whether the event should be bubbled to its parent if not handled locally. Defaults to a value of `true`.
* @param fromLeaf Optional. Whether the event is emitted from a leaf node.
* @returns `true` if the event was handled.
*/
async emitEvent(name: string, value?: any, bubble = true, fromLeaf = false): Promise<boolean> {
// Initialize event
const dialogEvent: DialogEvent = {
bubble: bubble,
name: name,
value: value,
};
// Find starting dialog
let dc: DialogContext = this;
if (fromLeaf) {
while (true) {
const childDc = dc.child;
if (childDc != undefined) {
dc = childDc;
} else {
break;
}
}
}
// Dispatch to active dialog first
// - The active dialog will decide if it should bubble the event to its parent.
const instance = dc.activeDialog;
if (instance != undefined) {
const dialog = dc.findDialog(instance.id);
if (dialog != undefined) {
return wrapErrors(this, dialog.onDialogEvent(dc, dialogEvent));
}
}
return false;
}
/**
* @private
* @param reason
* @param result
*/
private async endActiveDialog(reason: DialogReason, result?: any): Promise<void> {
const instance: DialogInstance<any> = this.activeDialog;
if (instance) {
// Lookup dialog
const dialog: Dialog<{}> = this.findDialog(instance.id);
if (dialog) {
// Notify dialog of end
await wrapErrors(this, dialog.endDialog(this.context, instance, reason));
}
// Pop dialog off stack
this.stack.pop();
this.state.setValue(TurnPath.lastResult, result);
}
}
} | the_stack |
import { isNullOrUndefined, isUndefined, extend, setValue, getValue, deleteObject, createElement } from '@syncfusion/ej2-base';
import { Gantt } from '../base/gantt';
import { TaskFieldsModel, EditSettingsModel, ResourceFieldsModel } from '../models/models';
import { IGanttData, ITaskData, ITaskbarEditedEventArgs, IValidateArgs, IParent, IPredecessor } from '../base/interface';
import { IActionBeginEventArgs, ITaskAddedEventArgs, ITaskDeletedEventArgs, RowDropEventArgs } from '../base/interface';
import { ColumnModel, Column as GanttColumn } from '../models/column';
import { ColumnModel as GanttColumnModel } from '../models/column';
import { DataManager, DataUtil, Query, AdaptorOptions, ODataAdaptor, WebApiAdaptor } from '@syncfusion/ej2-data';
import { ReturnType, RecordDoubleClickEventArgs, Row, Column, IEditCell, EJ2Intance, getUid } from '@syncfusion/ej2-grids';
import { getSwapKey, isScheduledTask, getTaskData, isRemoteData, getIndex, isCountRequired, updateDates } from '../base/utils';
import { RowPosition } from '../base/enum';
import { CellEdit } from './cell-edit';
import { TaskbarEdit } from './taskbar-edit';
import { DialogEdit } from './dialog-edit';
import { Dialog } from '@syncfusion/ej2-popups';
import { NumericTextBoxModel } from '@syncfusion/ej2-inputs';
import { MultiSelect, CheckBoxSelection, DropDownList } from '@syncfusion/ej2-dropdowns';
import { ConnectorLineEdit } from './connector-line-edit';
import { ITreeData } from '@syncfusion/ej2-treegrid';
/**
* The Edit Module is used to handle editing actions.
*
*/
export class Edit {
private parent: Gantt;
public validatedChildItems: IGanttData[];
private isFromDeleteMethod: boolean = false;
private targetedRecords: IGanttData[] = [];
/**
* @private
*/
/** @hidden */
private ganttData: Object[] | DataManager;
/** @hidden */
private treeGridData: ITreeData[];
/** @hidden */
private draggedRecord: IGanttData;
/** @hidden */
private updateParentRecords: IGanttData[] = [];
/** @hidden */
private droppedRecord: IGanttData;
/** @hidden */
private isTreeGridRefresh: boolean;
/** @hidden */
public isaddtoBottom: boolean = false;
/** @hidden */
public addRowPosition: RowPosition;
/** @hidden */
public addRowIndex: number;
/** @hidden */
private dropPosition: string;
public confirmDialog: Dialog = null;
private taskbarMoved: boolean = false;
private predecessorUpdated: boolean = false;
public newlyAddedRecordBackup: IGanttData;
public isBreakLoop: boolean = false;
public addRowSelectedItem: IGanttData;
public cellEditModule: CellEdit;
public taskbarEditModule: TaskbarEdit;
public dialogModule: DialogEdit;
constructor(parent?: Gantt) {
this.parent = parent;
this.validatedChildItems = [];
if (this.parent.editSettings.allowEditing && this.parent.editSettings.mode === 'Auto') {
this.cellEditModule = new CellEdit(this.parent);
}
if (this.parent.taskFields.dependency) {
this.parent.connectorLineEditModule = new ConnectorLineEdit(this.parent);
}
if (this.parent.editSettings.allowAdding || (this.parent.editSettings.allowEditing &&
(this.parent.editSettings.mode === 'Dialog' || this.parent.editSettings.mode === 'Auto'))) {
this.dialogModule = new DialogEdit(this.parent);
}
if (this.parent.editSettings.allowTaskbarEditing) {
this.taskbarEditModule = new TaskbarEdit(this.parent);
}
if (this.parent.editSettings.allowDeleting) {
const confirmDialog: HTMLElement = createElement('div', {
id: this.parent.element.id + '_deleteConfirmDialog'
});
this.parent.element.appendChild(confirmDialog);
this.renderDeleteConfirmDialog();
}
this.parent.treeGrid.recordDoubleClick = this.recordDoubleClick.bind(this);
this.parent.treeGrid.editSettings.allowAdding = this.parent.editSettings.allowAdding;
this.parent.treeGrid.editSettings.allowDeleting = this.parent.editSettings.allowDeleting;
this.parent.treeGrid.editSettings.showDeleteConfirmDialog = this.parent.editSettings.showDeleteConfirmDialog;
this.parent.treeGrid.editSettings.allowNextRowEdit = this.parent.editSettings.allowNextRowEdit;
this.updateDefaultColumnEditors();
}
private getModuleName(): string {
return 'edit';
}
/**
* Method to update default edit params and editors for Gantt
*
* @returns {void} .
*/
private updateDefaultColumnEditors(): void {
const customEditorColumns: string[] =
[this.parent.taskFields.id, this.parent.taskFields.progress, this.parent.taskFields.resourceInfo, 'taskType'];
for (let i: number = 0; i < customEditorColumns.length; i++) {
if (!isNullOrUndefined(customEditorColumns[i]) && customEditorColumns[i].length > 0) {
// eslint-disable-next-line
const column: ColumnModel = this.parent.getColumnByField(customEditorColumns[i], this.parent.treeGridModule.treeGridColumns);
if (column) {
if (column.field === this.parent.taskFields.id) {
this.updateIDColumnEditParams(column);
} else if (column.field === this.parent.taskFields.progress) {
this.updateProgessColumnEditParams(column);
} else if (column.field === this.parent.taskFields.resourceInfo) {
this.updateResourceColumnEditor(column);
} else if (column.field === 'taskType') {
this.updateTaskTypeColumnEditor(column);
}
}
}
}
}
/**
* Method to update editors for id column in Gantt
*
* @param {ColumnModel} column .
* @returns {void} .
*/
private updateIDColumnEditParams(column: ColumnModel): void {
const editParam: NumericTextBoxModel = {
min: 0,
decimals: 0,
validateDecimalOnType: true,
format: 'n0',
showSpinButton: false
};
this.updateEditParams(column, editParam);
}
/**
* Method to update edit params of default progress column
*
* @param {ColumnModel} column .
* @returns {void} .
*/
private updateProgessColumnEditParams(column: ColumnModel): void {
const editParam: NumericTextBoxModel = {
min: 0,
decimals: 0,
validateDecimalOnType: true,
max: 100,
format: 'n0'
};
this.updateEditParams(column, editParam);
}
/**
* Assign edit params for id and progress columns
*
* @param {ColumnModel} column .
* @param {object} editParam .
* @returns {void} .
*/
private updateEditParams(column: ColumnModel, editParam: object): void {
if (isNullOrUndefined(column.edit)) {
column.edit = {};
column.edit.params = {};
} else if (isNullOrUndefined(column.edit.params)) {
column.edit.params = {};
}
extend(editParam, column.edit.params);
column.edit.params = editParam;
const ganttColumn: ColumnModel = this.parent.getColumnByField(column.field, this.parent.ganttColumns);
ganttColumn.edit = column.edit;
}
/**
* Method to update resource column editor for default resource column
*
* @param {ColumnModel} column .
* @returns {void} .
*/
private updateResourceColumnEditor(column: ColumnModel): void {
if (this.parent.editSettings.allowEditing && isNullOrUndefined(column.edit) && this.parent.editSettings.mode === 'Auto') {
column.editType = 'dropdownedit';
column.edit = this.getResourceEditor();
const ganttColumn: ColumnModel = this.parent.getColumnByField(column.field, this.parent.ganttColumns);
ganttColumn.editType = 'dropdownedit';
ganttColumn.edit = column.edit;
}
}
/**
* Method to create resource custom editor
*
* @returns {IEditCell} .
*/
private getResourceEditor(): IEditCell {
const resourceSettings: ResourceFieldsModel = this.parent.resourceFields;
const editObject: IEditCell = {};
let editor: MultiSelect;
MultiSelect.Inject(CheckBoxSelection);
editObject.write = (args: { rowData: Object, element: Element, column: GanttColumn, row: HTMLElement, requestType: string }) => {
this.parent.treeGridModule.currentEditRow = {};
editor = new MultiSelect({
dataSource: new DataManager(this.parent.resources),
fields: { text: resourceSettings.name, value: resourceSettings.id },
mode: 'CheckBox',
showDropDownIcon: true,
popupHeight: '350px',
delimiterChar: ',',
value: this.parent.treeGridModule.getResourceIds(args.rowData as IGanttData) as number[]
});
editor.appendTo(args.element as HTMLElement);
};
editObject.read = (element: HTMLElement): string => {
let value: Object[] = (<EJ2Intance>element).ej2_instances[0].value;
const resourcesName: string[] = [];
if (isNullOrUndefined(value)) {
value = [];
}
for (let i: number = 0; i < value.length; i++) {
for (let j: number = 0; j < this.parent.resources.length; j++) {
if (this.parent.resources[j][resourceSettings.id] === value[i]) {
resourcesName.push(this.parent.resources[j][resourceSettings.name]);
break;
}
}
}
this.parent.treeGridModule.currentEditRow[this.parent.taskFields.resourceInfo] = value;
return resourcesName.join(',');
};
editObject.destroy = () => {
if (editor) {
editor.destroy();
}
};
return editObject;
}
/**
* Method to update task type column editor for task type
*
* @param {ColumnModel} column .
* @returns {void} .
*/
private updateTaskTypeColumnEditor(column: ColumnModel): void {
if (this.parent.editSettings.allowEditing && isNullOrUndefined(column.edit) && this.parent.editSettings.mode === 'Auto') {
column.editType = 'dropdownedit';
column.edit = this.getTaskTypeEditor();
const ganttColumn: ColumnModel = this.parent.getColumnByField(column.field, this.parent.ganttColumns);
ganttColumn.editType = 'dropdownedit';
ganttColumn.edit = column.edit;
}
}
/**
* Method to create task type custom editor
*
* @returns {IEditCell} .
*/
private getTaskTypeEditor(): IEditCell {
const editObject: IEditCell = {};
let editor: DropDownList;
const types: Object[] = [{ 'ID': 1, 'Value': 'FixedUnit' }, { 'ID': 2, 'Value': 'FixedWork' }, { 'ID': 3, 'Value': 'FixedDuration' }];
editObject.write = (args: { rowData: Object, element: Element, column: GanttColumn, row: HTMLElement, requestType: string }) => {
this.parent.treeGridModule.currentEditRow = {};
editor = new DropDownList({
dataSource: new DataManager(types),
fields: { value: 'Value' },
popupHeight: '350px',
value: getValue('taskType', (args.rowData as IGanttData).ganttProperties)
});
editor.appendTo(args.element as HTMLElement);
};
editObject.read = (element: HTMLElement): string => {
const value: string = (<EJ2Intance>element).ej2_instances[0].value;
const key: string = 'taskType';
this.parent.treeGridModule.currentEditRow[key] = value;
return value;
};
editObject.destroy = () => {
if (editor) {
editor.destroy();
}
};
return editObject;
}
/**
* @returns {void} .
* @private
*/
public reUpdateEditModules(): void {
const editSettings: EditSettingsModel = this.parent.editSettings;
if (editSettings.allowEditing) {
if (this.parent.editModule.cellEditModule && editSettings.mode === 'Dialog') {
this.cellEditModule.destroy();
this.parent.treeGrid.recordDoubleClick = this.recordDoubleClick.bind(this);
} else if (isNullOrUndefined(this.parent.editModule.cellEditModule) && editSettings.mode === 'Auto') {
this.cellEditModule = new CellEdit(this.parent);
}
if (this.parent.editModule.dialogModule && editSettings.mode === 'Auto') {
this.parent.treeGrid.recordDoubleClick = undefined;
} else if (isNullOrUndefined(this.parent.editModule.dialogModule)) {
this.dialogModule = new DialogEdit(this.parent);
}
} else {
if (this.cellEditModule) {
this.cellEditModule.destroy();
}
if (this.dialogModule) {
this.dialogModule.destroy();
}
}
if (editSettings.allowDeleting && editSettings.showDeleteConfirmDialog) {
if (isNullOrUndefined(this.confirmDialog)) {
const confirmDialog: HTMLElement = createElement('div', {
id: this.parent.element.id + '_deleteConfirmDialog'
});
this.parent.element.appendChild(confirmDialog);
this.renderDeleteConfirmDialog();
}
} else if (!editSettings.allowDeleting || !editSettings.showDeleteConfirmDialog) {
if (this.confirmDialog && !this.confirmDialog.isDestroyed) {
this.confirmDialog.destroy();
}
}
if (editSettings.allowTaskbarEditing) {
if (isNullOrUndefined(this.parent.editModule.taskbarEditModule)) {
this.taskbarEditModule = new TaskbarEdit(this.parent);
}
} else {
if (this.taskbarEditModule) {
this.taskbarEditModule.destroy();
}
}
}
private recordDoubleClick(args: RecordDoubleClickEventArgs): void {
if (this.parent.editSettings.allowEditing && this.parent.editSettings.mode === 'Dialog') {
let ganttData: IGanttData;
if (args.row) {
const rowIndex: number = getValue('rowIndex', args.row);
ganttData = this.parent.currentViewData[rowIndex];
}
if (!isNullOrUndefined(ganttData)) {
this.dialogModule.openEditDialog(ganttData);
}
}
this.parent.ganttChartModule.recordDoubleClick(args);
}
/**
* @returns {void} .
* @private
*/
public destroy(): void {
if (this.cellEditModule) {
this.cellEditModule.destroy();
}
if (this.taskbarEditModule) {
this.taskbarEditModule.destroy();
}
if (this.dialogModule) {
this.dialogModule.destroy();
}
if (this.confirmDialog && !this.confirmDialog.isDestroyed) {
this.confirmDialog.destroy();
}
}
/**
* @private
*/
public deletedTaskDetails: IGanttData[] = [];
/**
* Method to update record with new values.
*
* @param {Object} data - Defines new data to update.
* @returns {void} .
*/
public updateRecordByID(data: Object): void {
if (!this.parent.readOnly) {
const tasks: TaskFieldsModel = this.parent.taskFields;
if (isNullOrUndefined(data) || isNullOrUndefined(data[tasks.id])) {
return;
}
const ganttData: IGanttData = this.parent.viewType === 'ResourceView' ?
this.parent.flatData[this.parent.getTaskIds().indexOf('T' + data[tasks.id])] : this.parent.getRecordByID(data[tasks.id]);
if (!isNullOrUndefined(this.parent.editModule) && ganttData) {
this.parent.isOnEdit = true;
this.validateUpdateValues(data, ganttData, true);
if (data[this.parent.taskFields.resourceInfo]) {
this.updateResourceRelatedFields(ganttData,'resource');
}
const keys: string[] = Object.keys(data);
if (keys.indexOf(tasks.startDate) !== -1 || keys.indexOf(tasks.endDate) !== -1 ||
keys.indexOf(tasks.duration) !== -1) {
this.parent.dataOperation.calculateScheduledValues(ganttData, ganttData.taskData, false);
}
this.parent.dataOperation.updateWidthLeft(ganttData);
if (!isUndefined(data[this.parent.taskFields.dependency]) &&
data[this.parent.taskFields.dependency] !== ganttData.ganttProperties.predecessorsName) {
this.parent.connectorLineEditModule.updatePredecessor(
ganttData, data[this.parent.taskFields.dependency]);
} else {
const args: ITaskbarEditedEventArgs = {} as ITaskbarEditedEventArgs;
args.data = ganttData;
if (this.parent.viewType === 'ResourceView') {
args.action = 'methodUpdate';
}
this.parent.editModule.initiateUpdateAction(args);
}
}
}
}
/**
*
* @param {object} data .
* @param {IGanttData} ganttData .
* @param {boolean} isFromDialog .
* @returns {void} .
* @private
*/
public validateUpdateValues(data: Object, ganttData: IGanttData, isFromDialog?: boolean): void {
const ganttObj: Gantt = this.parent;
const tasks: TaskFieldsModel = ganttObj.taskFields;
const ganttPropByMapping: Object = getSwapKey(ganttObj.columnMapping);
const scheduleFieldNames: string[] = [];
let isScheduleValueUpdated: boolean = false;
for (const key of Object.keys(data)) {
if ([tasks.startDate, tasks.endDate, tasks.duration].indexOf(key) !== -1) {
if (isNullOrUndefined(data[key]) && !ganttObj.allowUnscheduledTasks) {
continue;
}
if (isFromDialog) {
if (tasks.duration === key) {
ganttObj.dataOperation.updateDurationValue(data[key], ganttData.ganttProperties);
if (ganttData.ganttProperties.duration > 0 && ganttData.ganttProperties.isMilestone) {
this.parent.setRecordValue('isMilestone', false, ganttData.ganttProperties, true);
}
ganttObj.dataOperation.updateMappingData(ganttData, ganttPropByMapping[key]);
} else {
const tempDate: Date = typeof data[key] === 'string' ? new Date(data[key] as string) : data[key];
ganttObj.setRecordValue(ganttPropByMapping[key], tempDate, ganttData.ganttProperties, true);
ganttObj.dataOperation.updateMappingData(ganttData, ganttPropByMapping[key]);
}
} else {
scheduleFieldNames.push(key);
isScheduleValueUpdated = true;
}
} else if (tasks.resourceInfo === key) {
const resourceData: Object[] = ganttObj.dataOperation.setResourceInfo(data);
if (this.parent.viewType === 'ResourceView') {
if (JSON.stringify(resourceData) !== JSON.stringify(ganttData.ganttProperties.resourceInfo)) {
this.parent.editModule.dialogModule.isResourceUpdate = true;
this.parent.editModule.dialogModule.previousResource = !isNullOrUndefined(ganttData.ganttProperties.resourceInfo) ?
[...ganttData.ganttProperties.resourceInfo] : [];
} else {
this.parent.editModule.dialogModule.isResourceUpdate = false;
}
}
ganttData.ganttProperties.resourceInfo = resourceData;
ganttObj.dataOperation.updateMappingData(ganttData, 'resourceInfo');
} else if (tasks.dependency === key) {
//..
} else if ([tasks.progress, tasks.notes, tasks.durationUnit, tasks.expandState,
tasks.milestone, tasks.name, tasks.baselineStartDate,
tasks.baselineEndDate, tasks.id, tasks.segments].indexOf(key) !== -1) {
const column: ColumnModel = ganttObj.columnByField[key];
/* eslint-disable-next-line */
let value: any = data[key];
if (!isNullOrUndefined(column) && (column.editType === 'datepickeredit' || column.editType === 'datetimepickeredit')) {
value = ganttObj.dataOperation.getDateFromFormat(value);
}
let ganttPropKey: string = ganttPropByMapping[key];
if (key === tasks.id) {
ganttPropKey = 'taskId';
} else if (key === tasks.name) {
ganttPropKey = 'taskName';
} else if (key === tasks.segments) {
ganttPropKey = 'segments';
/* eslint-disable-next-line */
if (data && !isNullOrUndefined(data[this.parent.taskFields.segments]) && data[this.parent.taskFields.segments].length > 0) {
let totDuration: number = 0;
for (let i: number = 0; i < ganttData.ganttProperties.segments.length; i++) {
totDuration = totDuration + ganttData.ganttProperties.segments[i].duration;
}
const sdate: Date = ganttData.ganttProperties.startDate;
/* eslint-disable-next-line */
const edate: Date = this.parent.dataOperation.getEndDate(sdate, totDuration, ganttData.ganttProperties.durationUnit, ganttData.ganttProperties, false);
ganttObj.setRecordValue('endDate', ganttObj.dataOperation.getDateFromFormat(edate), ganttData.ganttProperties, true);
}
}
if (!isNullOrUndefined(ganttPropKey)) {
ganttObj.setRecordValue(ganttPropKey, value, ganttData.ganttProperties, true);
}
if ((key === tasks.baselineStartDate || key === tasks.baselineEndDate) &&
(ganttData.ganttProperties.baselineStartDate && ganttData.ganttProperties.baselineEndDate)) {
ganttObj.setRecordValue(
'baselineLeft', ganttObj.dataOperation.calculateBaselineLeft(
ganttData.ganttProperties),
ganttData.ganttProperties, true);
ganttObj.setRecordValue(
'baselineWidth', ganttObj.dataOperation.calculateBaselineWidth(
ganttData.ganttProperties),
ganttData.ganttProperties, true);
}
ganttObj.setRecordValue('taskData.' + key, value, ganttData);
/* eslint-disable-next-line */
if (key === tasks.segments && data && !isNullOrUndefined(data[this.parent.taskFields.segments]) && data[this.parent.taskFields.segments].length > 0) {
ganttObj.dataOperation.setSegmentsInfo(ganttData, true);
}
ganttObj.setRecordValue(key, value, ganttData);
} else if (tasks.indicators === key) {
const value: Object[] = data[key];
ganttObj.setRecordValue('indicators', value, ganttData.ganttProperties, true);
ganttObj.setRecordValue('taskData.' + key, value, ganttData);
ganttObj.setRecordValue(key, value, ganttData);
} else if (tasks.work === key) {
ganttObj.setRecordValue('work', data[key], ganttData.ganttProperties, true);
this.parent.dataOperation.updateMappingData(ganttData, 'work');
this.parent.dataOperation.updateMappingData(ganttData, 'duration');
this.parent.dataOperation.updateMappingData(ganttData, 'endDate');
} else if (key === 'taskType') {
ganttObj.setRecordValue('taskType', data[key], ganttData.ganttProperties, true);
//this.parent.dataOperation.updateMappingData(ganttData, 'taskType');
} else if (ganttObj.customColumns.indexOf(key) !== -1) {
const column: ColumnModel = ganttObj.columnByField[key];
/* eslint-disable-next-line */
let value: any = data[key];
if (isNullOrUndefined(column.edit)) {
if (column.editType === 'datepickeredit' || column.editType === 'datetimepickeredit') {
value = ganttObj.dataOperation.getDateFromFormat(value);
}
}
ganttObj.setRecordValue('taskData.' + key, value, ganttData);
ganttObj.setRecordValue(key, value, ganttData);
} else if (tasks.manual === key) {
ganttObj.setRecordValue('isAutoSchedule', !data[key], ganttData.ganttProperties, true);
this.parent.setRecordValue(key, data[key], ganttData);
this.updateTaskScheduleModes(ganttData);
}
}
if (isScheduleValueUpdated) {
this.validateScheduleValues(scheduleFieldNames, ganttData, data);
}
}
/**
* To update duration, work, resource unit
*
* @param {IGanttData} currentData .
* @param {string} column .
* @returns {void} .
*/
public updateResourceRelatedFields(currentData: IGanttData, column: string): void {
const ganttProp: ITaskData = currentData.ganttProperties;
const taskType: string = ganttProp.taskType;
let isEffectDriven: boolean;
const isAutoSchedule: boolean = ganttProp.isAutoSchedule;
if (!isNullOrUndefined(ganttProp.resourceInfo)) {
if (ganttProp.work > 0 || column === 'work') {
switch (taskType) {
case 'FixedUnit':
if (ganttProp.resourceInfo.length === 0) {
return;
}
else if (isAutoSchedule && ganttProp.resourceInfo.length &&
(column === 'work' || (column === 'resource'))) {
this.parent.dataOperation.updateDurationWithWork(currentData);
} else if (!isAutoSchedule && column === 'work') {
this.parent.dataOperation.updateUnitWithWork(currentData);
} else {
this.parent.dataOperation.updateWorkWithDuration(currentData);
}
break;
case 'FixedWork':
if (ganttProp.resourceInfo.length === 0) {
return;
} else if (isAutoSchedule) {
if (column === 'duration' || column === 'endDate') {
this.parent.dataOperation.updateUnitWithWork(currentData);
if (ganttProp.duration === 0) {
this.parent.setRecordValue('work', 0, ganttProp, true);
if (!isNullOrUndefined(this.parent.taskFields.work)) {
this.parent.dataOperation.updateMappingData(currentData, 'work');
}
}
} else {
this.parent.dataOperation.updateDurationWithWork(currentData);
}
} else {
if (column === 'work') {
this.parent.dataOperation.updateUnitWithWork(currentData);
} else {
this.parent.dataOperation.updateWorkWithDuration(currentData);
}
}
break;
case 'FixedDuration':
if (ganttProp.resourceInfo.length && (column === 'work' || (isAutoSchedule &&
isEffectDriven && (column === 'resource')))) {
this.parent.dataOperation.updateUnitWithWork(currentData);
} else {
this.parent.dataOperation.updateWorkWithDuration(currentData);
}
break;
}
} else {
this.parent.dataOperation.updateWorkWithDuration(currentData);
}
}
}
private validateScheduleValues(fieldNames: string[], ganttData: IGanttData, data: Object): void {
const ganttObj: Gantt = this.parent;
if (fieldNames.length > 2) {
ganttObj.dataOperation.calculateScheduledValues(ganttData, data, false);
} else if (fieldNames.length > 1) {
this.validateScheduleByTwoValues(data, fieldNames, ganttData);
} else {
this.dialogModule.validateScheduleValuesByCurrentField(fieldNames[0], data[fieldNames[0]], ganttData);
}
}
private validateScheduleByTwoValues(data: Object, fieldNames: string[], ganttData: IGanttData): void {
const ganttObj: Gantt = this.parent; let startDate: Date; let endDate: Date; let duration: string;
const tasks: TaskFieldsModel = ganttObj.taskFields; const ganttProp: ITaskData = ganttData.ganttProperties;
const isUnscheduledTask: boolean = ganttObj.allowUnscheduledTasks;
if (fieldNames.indexOf(tasks.startDate) !== -1) {
startDate = data[tasks.startDate];
}
if (fieldNames.indexOf(tasks.endDate) !== -1) {
endDate = data[tasks.endDate];
}
if (fieldNames.indexOf(tasks.duration) !== -1) {
duration = data[tasks.duration];
}
if (startDate && endDate || (isUnscheduledTask && (fieldNames.indexOf(tasks.startDate) !== -1) &&
(fieldNames.indexOf(tasks.endDate) !== -1))) {
ganttObj.setRecordValue('startDate', ganttObj.dataOperation.getDateFromFormat(startDate), ganttProp, true);
ganttObj.setRecordValue('endDate', ganttObj.dataOperation.getDateFromFormat(endDate), ganttProp, true);
ganttObj.dataOperation.calculateDuration(ganttData);
} else if (endDate && duration || (isUnscheduledTask &&
(fieldNames.indexOf(tasks.endDate) !== -1) && (fieldNames.indexOf(tasks.duration) !== -1))) {
ganttObj.setRecordValue('endDate', ganttObj.dataOperation.getDateFromFormat(endDate), ganttProp, true);
ganttObj.dataOperation.updateDurationValue(duration, ganttProp);
} else if (startDate && duration || (isUnscheduledTask && (fieldNames.indexOf(tasks.startDate) !== -1)
&& (fieldNames.indexOf(tasks.duration) !== -1))) {
ganttObj.setRecordValue('startDate', ganttObj.dataOperation.getDateFromFormat(startDate), ganttProp, true);
ganttObj.dataOperation.updateDurationValue(duration, ganttProp);
}
}
private isTaskbarMoved(data: IGanttData): boolean {
let isMoved: boolean = false;
const taskData: ITaskData = data.ganttProperties;
const prevData: IGanttData = this.parent.previousRecords &&
this.parent.previousRecords[data.uniqueID];
if (prevData && prevData.ganttProperties) {
const prevStart: Date = getValue('ganttProperties.startDate', prevData) as Date;
const prevEnd: Date = getValue('ganttProperties.endDate', prevData) as Date;
const prevDuration: number = getValue('ganttProperties.duration', prevData);
const prevDurationUnit: string = getValue('ganttProperties.durationUnit', prevData);
const keys: string[] = Object.keys(prevData.ganttProperties);
if (keys.indexOf('startDate') !== -1 || keys.indexOf('endDate') !== -1 ||
keys.indexOf('duration') !== -1 || keys.indexOf('durationUnit') !== -1) {
if ((isNullOrUndefined(prevStart) && !isNullOrUndefined(taskData.startDate)) ||
(isNullOrUndefined(prevEnd) && !isNullOrUndefined(taskData.endDate)) ||
(isNullOrUndefined(taskData.startDate) && !isNullOrUndefined(prevStart)) ||
(isNullOrUndefined(taskData.endDate) && !isNullOrUndefined(prevEnd)) ||
(prevStart && prevStart.getTime() !== taskData.startDate.getTime())
|| (prevEnd && prevEnd.getTime() !== taskData.endDate.getTime())
|| (!isNullOrUndefined(prevDuration) && prevDuration !== taskData.duration)
|| (!isNullOrUndefined(prevDuration) && prevDuration === taskData.duration &&
prevDurationUnit !== taskData.durationUnit)) {
isMoved = true;
}
}
}
return isMoved;
}
private isPredecessorUpdated(data: IGanttData): boolean {
let isPredecessorUpdated: boolean = false;
const prevData: IGanttData = this.parent.previousRecords[data.uniqueID];
// eslint-disable-next-line
if (prevData && prevData.ganttProperties && prevData.ganttProperties.hasOwnProperty('predecessor')) {
if (data.ganttProperties.predecessorsName !== prevData.ganttProperties.predecessorsName) {
isPredecessorUpdated = true;
} else {
this.parent.setRecordValue('predecessor', prevData.ganttProperties.predecessor, data.ganttProperties, true);
}
}
return isPredecessorUpdated;
}
/**
* Method to check need to open predecessor validate dialog
*
* @param {IGanttData} data .
* @returns {boolean} .
*/
private isCheckPredecessor(data: IGanttData): boolean {
let isValidatePredecessor: boolean = false;
const prevData: IGanttData = this.parent.previousRecords[data.uniqueID];
if (prevData && this.parent.taskFields.dependency && this.parent.isInPredecessorValidation &&
this.parent.predecessorModule.getValidPredecessor(data).length > 0) {
if (this.isTaskbarMoved(data)) {
isValidatePredecessor = true;
}
}
return isValidatePredecessor;
}
/**
* Method to copy the ganttProperties values
*
* @param {IGanttData} data .
* @param {IGanttData} updateData .
* @returns {void} .
* @private
*/
public updateGanttProperties(data: IGanttData, updateData: IGanttData): void {
const skipProperty: string[] = ['taskId', 'uniqueID', 'rowUniqueID', 'parentId'];
Object.keys(data.ganttProperties).forEach((property: string) => {
if (skipProperty.indexOf(property) === -1) {
updateData.ganttProperties[property] = data.ganttProperties[property];
}
});
}
/**
* Method to update all dependent record on edit action
*
* @param {ITaskAddedEventArgs} args .
* @returns {void} .
* @private
*/
public initiateUpdateAction(args: ITaskbarEditedEventArgs): void {
const isValidatePredecessor: boolean = this.isCheckPredecessor(args.data);
this.taskbarMoved = this.isTaskbarMoved(args.data);
this.predecessorUpdated = this.isPredecessorUpdated(args.data);
if (this.predecessorUpdated) {
this.parent.isConnectorLineUpdate = true;
this.parent.connectorLineEditModule.addRemovePredecessor(args.data);
}
let validateObject: object = {};
if (isValidatePredecessor) {
validateObject = this.parent.connectorLineEditModule.validateTypes(args.data);
this.parent.isConnectorLineUpdate = true;
if (!isNullOrUndefined(getValue('violationType', validateObject))) {
const newArgs: IValidateArgs = this.validateTaskEvent(args);
if (newArgs.validateMode.preserveLinkWithEditing === false &&
newArgs.validateMode.removeLink === false &&
newArgs.validateMode.respectLink === false) {
this.parent.connectorLineEditModule.openValidationDialog(validateObject);
} else {
this.parent.connectorLineEditModule.applyPredecessorOption();
}
} else {
this.updateEditedTask(args);
}
} else {
if (this.taskbarMoved) {
this.parent.isConnectorLineUpdate = true;
}
this.updateEditedTask(args);
}
}
/**
*
* @param {ITaskbarEditedEventArgs} editedEventArgs method to trigger validate predecessor link by dialog
* @returns {IValidateArgs} .
*/
private validateTaskEvent(editedEventArgs: ITaskbarEditedEventArgs): IValidateArgs {
const newArgs: IValidateArgs = {};
this.resetValidateArgs();
this.parent.currentEditedArgs = newArgs;
newArgs.cancel = false;
newArgs.data = editedEventArgs.data;
newArgs.requestType = 'validateLinkedTask';
newArgs.validateMode = this.parent.dialogValidateMode;
newArgs.editEventArgs = editedEventArgs;
this.parent.actionBeginTask(newArgs);
return newArgs;
}
private resetValidateArgs(): void {
this.parent.dialogValidateMode.preserveLinkWithEditing = true;
this.parent.dialogValidateMode.removeLink = false;
this.parent.dialogValidateMode.respectLink = false;
}
/**
*
* @param {ITaskAddedEventArgs} args - Edited event args like taskbar editing, dialog editing, cell editing
* @returns {void} .
* @private
*/
public updateEditedTask(args: ITaskbarEditedEventArgs): void {
const ganttRecord: IGanttData = args.data;
this.updateParentChildRecord(ganttRecord);
if (this.parent.isConnectorLineUpdate) {
/* validating predecessor for updated child items */
for (let i: number = 0; i < this.validatedChildItems.length; i++) {
const child: IGanttData = this.validatedChildItems[i];
if (child.ganttProperties.predecessor && child.ganttProperties.predecessor.length > 0) {
this.parent.editedTaskBarItem = child;
this.parent.predecessorModule.validatePredecessor(child, [], '');
}
}
/** validating predecessor for current edited records */
if (ganttRecord.ganttProperties.predecessor) {
this.parent.isMileStoneEdited = ganttRecord.ganttProperties.isMilestone;
if (this.taskbarMoved) {
this.parent.editedTaskBarItem = ganttRecord;
}
this.parent.predecessorModule.validatePredecessor(ganttRecord, [], '');
}
this.updateParentItemOnEditing();
}
/** Update parent up-to zeroth level */
if (ganttRecord.parentItem ) {
this.parent.dataOperation.updateParentItems(ganttRecord, true);
}
this.initiateSaveAction(args);
}
private updateParentItemOnEditing(): void {
const childRecord: object[] = getValue('parentRecord', this.parent.predecessorModule);
for (let i: number = 0; i < childRecord.length; i++) {
this.parent.dataOperation.updateParentItems(childRecord[i]);
}
setValue('parentRecord', [], this.parent.predecessorModule);
setValue('parentIds', [], this.parent.predecessorModule);
}
/**
* To update parent records while perform drag action.
*
* @param {IGanttData} data .
* @returns {void} .
* @private
*/
public updateParentChildRecord(data: IGanttData): void {
const ganttRecord: IGanttData = data;
if (ganttRecord.hasChildRecords && this.taskbarMoved && this.parent.taskMode === 'Auto' && (!isNullOrUndefined(this.parent.editModule.cellEditModule) && !this.parent.editModule.cellEditModule.isResourceCellEdited)) {
this.updateChildItems(ganttRecord);
}
if (!isNullOrUndefined(this.parent.editModule.cellEditModule)) {
this.parent.editModule.cellEditModule.isResourceCellEdited = false;
}
}
/**
* To update records while changing schedule mode.
*
* @param {IGanttData} data .
* @returns {void} .
* @private
*/
public updateTaskScheduleModes(data: IGanttData): void {
const currentValue: Date = data[this.parent.taskFields.startDate];
const ganttProp: ITaskData = data.ganttProperties;
if (data.hasChildRecords && ganttProp.isAutoSchedule) {
this.parent.setRecordValue('startDate', ganttProp.autoStartDate, ganttProp, true);
this.parent.setRecordValue('endDate', ganttProp.autoEndDate, ganttProp, true);
this.parent.setRecordValue('width', this.parent.dataOperation.calculateWidth(data, true), ganttProp, true);
this.parent.setRecordValue('left', this.parent.dataOperation.calculateLeft(ganttProp, true), ganttProp, true);
this.parent.setRecordValue(
'progressWidth',
this.parent.dataOperation.getProgressWidth(ganttProp.width, ganttProp.progress),
ganttProp,
true
);
this.parent.dataOperation.calculateDuration(data);
} else if (data.hasChildRecords && !ganttProp.isAutoSchedule) {
this.parent.dataOperation.updateWidthLeft(data);
this.parent.dataOperation.calculateDuration(data);
this.parent.setRecordValue('autoStartDate', ganttProp.startDate, ganttProp, true);
this.parent.setRecordValue('autoEndDate', ganttProp.endDate, ganttProp, true);
this.parent.setRecordValue('autoDuration', this.parent.dataOperation.calculateAutoDuration(data), ganttProp, true);
this.parent.dataOperation.updateAutoWidthLeft(data);
} else {
const startDate: Date = this.parent.dateValidationModule.checkStartDate(currentValue, data.ganttProperties);
this.parent.setRecordValue('startDate', startDate, data.ganttProperties, true);
this.parent.dataOperation.updateMappingData(data, 'startDate');
this.parent.dateValidationModule.calculateEndDate(data);
this.parent.setRecordValue(
'taskData.' + this.parent.taskFields.manual,
data[this.parent.taskFields.manual], data);
this.parent.dataOperation.updateWidthLeft(data);
}
}
/**
*
* @param {IGanttData} data .
* @param {Date} newStartDate .
* @returns {void} .
*/
private calculateDateByRoundOffDuration(data: IGanttData, newStartDate: Date): void {
const ganttRecord: IGanttData = data;
const taskData: ITaskData = ganttRecord.ganttProperties;
const projectStartDate: Date = new Date(newStartDate.getTime());
if (!isNullOrUndefined(taskData.endDate) && isNullOrUndefined(taskData.startDate)) {
const endDate: Date = this.parent.dateValidationModule.checkStartDate(projectStartDate, taskData, null);
this.parent.setRecordValue(
'endDate',
this.parent.dateValidationModule.checkEndDate(endDate, ganttRecord.ganttProperties),
taskData,
true);
} else {
this.parent.setRecordValue(
'startDate',
this.parent.dateValidationModule.checkStartDate(projectStartDate, taskData, false),
taskData,
true);
if (!isNullOrUndefined(taskData.duration)) {
this.parent.dateValidationModule.calculateEndDate(ganttRecord);
}
}
this.parent.dataOperation.updateWidthLeft(data);
this.parent.dataOperation.updateTaskData(ganttRecord);
}
/**
* To update progress value of parent tasks
*
* @param {IParent} cloneParent .
* @returns {void} .
* @private
*/
public updateParentProgress(cloneParent: IParent): void {
let parentProgress: number = 0;
const parent: IGanttData = this.parent.getParentTask(cloneParent);
const childRecords: IGanttData[] = parent.childRecords;
const childCount: number = childRecords ? childRecords.length : 0;
let totalProgress: number = 0;
let milesStoneCount: number = 0;
let taskCount: number = 0;
let totalDuration: number = 0;
let progressValues: Object = {};
if (childRecords) {
for (let i: number = 0; i < childCount; i++) {
if ((!childRecords[i].ganttProperties.isMilestone || childRecords[i].hasChildRecords) &&
isScheduledTask(childRecords[i].ganttProperties)) {
progressValues = this.parent.dataOperation.getParentProgress(childRecords[i]);
totalProgress += getValue('totalProgress', progressValues);
totalDuration += getValue('totalDuration', progressValues);
} else {
milesStoneCount += 1;
}
}
taskCount = childCount - milesStoneCount;
parentProgress = taskCount > 0 ? Math.round(totalProgress / totalDuration) : 0;
if (isNaN(parentProgress)) {
parentProgress = 0;
}
this.parent.setRecordValue(
'progressWidth',
this.parent.dataOperation.getProgressWidth(
parent.ganttProperties.isAutoSchedule ? parent.ganttProperties.width : parent.ganttProperties.autoWidth,
parentProgress),
parent.ganttProperties,
true);
this.parent.setRecordValue('progress', Math.floor(parentProgress), parent.ganttProperties, true);
this.parent.setRecordValue('totalProgress', totalProgress, parent.ganttProperties, true);
this.parent.setRecordValue('totalDuration', totalDuration, parent.ganttProperties, true);
}
this.parent.dataOperation.updateTaskData(parent);
if (parent.parentItem) {
this.updateParentProgress(parent.parentItem);
}
}
/**
* Method to revert cell edit action
*
* @param {object} args .
* @returns {void} .
* @private
*/
// eslint-disable-next-line
public revertCellEdit(args: object): void {
this.parent.editModule.reUpdatePreviousRecords(false, true);
this.resetEditProperties();
}
/**
* @param {boolean} isRefreshChart .
* @param {boolean} isRefreshGrid .
* @returns {void} .
* @private
*/
public reUpdatePreviousRecords(isRefreshChart?: boolean, isRefreshGrid?: boolean): void {
const collection: object = this.parent.previousRecords;
const keys: string[] = Object.keys(collection);
for (let i: number = 0; i < keys.length; i++) {
const uniqueId: string = keys[i];
const prevTask: IGanttData = collection[uniqueId] as IGanttData;
const originalData: IGanttData = this.parent.getTaskByUniqueID(uniqueId);
this.copyTaskData(originalData.taskData, prevTask.taskData);
delete prevTask.taskData;
this.copyTaskData(originalData.ganttProperties, prevTask.ganttProperties);
delete prevTask.ganttProperties;
this.copyTaskData(originalData, prevTask);
const rowIndex: number = this.parent.currentViewData.indexOf(originalData);
if (isRefreshChart) {
this.parent.chartRowsModule.refreshRow(rowIndex);
}
if (isRefreshGrid) {
const dataId: number | string = this.parent.viewType === 'ProjectView' ? originalData.ganttProperties.taskId : originalData.ganttProperties.rowUniqueID;
this.parent.treeGrid.grid.setRowData(dataId, originalData);
const row: Row<Column> = this.parent.treeGrid.grid.getRowObjectFromUID(
this.parent.treeGrid.grid.getDataRows()[rowIndex].getAttribute('data-uid'));
row.data = originalData;
}
}
}
/**
* Copy previous task data value to edited task data
*
* @param {object} existing .
* @param {object} newValue .
* @returns {void} .
*/
private copyTaskData(existing: Object, newValue: object): void {
if (!isNullOrUndefined(newValue)) {
extend(existing, newValue);
}
}
/**
* To update schedule date on editing.
*
* @param {ITaskbarEditedEventArgs} args .
* @returns {void} .
* @private
*/
// eslint-disable-next-line
private updateScheduleDatesOnEditing(args: ITaskbarEditedEventArgs): void {
//..
}
/**
*
* @param {IGanttData} ganttRecord .
* @returns {void} .
*/
private updateChildItems(ganttRecord: IGanttData): void {
const previousData: IGanttData = this.parent.previousRecords[ganttRecord.uniqueID];
let previousStartDate: Date;
if (isNullOrUndefined(previousData) ||
(isNullOrUndefined(previousData) && !isNullOrUndefined(previousData.ganttProperties))) {
previousStartDate = new Date(ganttRecord.ganttProperties.startDate.getTime());
} else {
previousStartDate = new Date(previousData.ganttProperties.startDate.getTime());
}
const currentStartDate: Date = ganttRecord.ganttProperties.startDate;
const childRecords: IGanttData[] = [];
let validStartDate: Date;
let validEndDate: Date;
let calcEndDate: Date;
let isRightMove: boolean;
let durationDiff: number;
this.getUpdatableChildRecords(ganttRecord, childRecords);
if (childRecords.length === 0) {
return;
}
if (previousStartDate.getTime() > currentStartDate.getTime()) {
validStartDate = this.parent.dateValidationModule.checkStartDate(currentStartDate);
validEndDate = this.parent.dateValidationModule.checkEndDate(previousStartDate, ganttRecord.ganttProperties);
isRightMove = false;
} else {
validStartDate = this.parent.dateValidationModule.checkStartDate(previousStartDate);
validEndDate = this.parent.dateValidationModule.checkEndDate(currentStartDate, ganttRecord.ganttProperties);
isRightMove = true;
}
//Get Duration
if (validStartDate.getTime() >= validEndDate.getTime()) {
durationDiff = 0;
} else {
durationDiff = this.parent.dateValidationModule.getDuration(validStartDate, validEndDate, 'minute', true, false);
}
for (let i: number = 0; i < childRecords.length; i++) {
if (childRecords[i].ganttProperties.isAutoSchedule) {
if (durationDiff > 0) {
const startDate: Date = isScheduledTask(childRecords[i].ganttProperties) ?
childRecords[i].ganttProperties.startDate : childRecords[i].ganttProperties.startDate ?
childRecords[i].ganttProperties.startDate : childRecords[i].ganttProperties.endDate ?
childRecords[i].ganttProperties.endDate : new Date(previousStartDate.toString());
if (isRightMove) {
calcEndDate = this.parent.dateValidationModule.getEndDate(
this.parent.dateValidationModule.checkStartDate(
startDate,
childRecords[i].ganttProperties,
childRecords[i].ganttProperties.isMilestone),
durationDiff,
'minute',
childRecords[i].ganttProperties,
false
);
} else {
calcEndDate = this.parent.dateValidationModule.getStartDate(
this.parent.dateValidationModule.checkEndDate(startDate, childRecords[i].ganttProperties),
durationDiff,
'minute',
childRecords[i].ganttProperties);
}
this.calculateDateByRoundOffDuration(childRecords[i], calcEndDate);
if (this.parent.isOnEdit && this.validatedChildItems.indexOf(childRecords[i]) === -1) {
this.validatedChildItems.push(childRecords[i]);
}
} else if (isNullOrUndefined(previousData)) {
calcEndDate = previousStartDate;
this.calculateDateByRoundOffDuration(childRecords[i], calcEndDate);
if (this.parent.isOnEdit && this.validatedChildItems.indexOf(childRecords[i]) === -1) {
this.validatedChildItems.push(childRecords[i]);
}
}
}
}
if (childRecords.length) {
this.parent.dataOperation.updateParentItems(ganttRecord, true);
}
}
/**
* To get updated child records.
*
* @param {IGanttData} parentRecord .
* @param {IGanttData} childLists .
* @returns {void} .
*/
private getUpdatableChildRecords(parentRecord: IGanttData, childLists: IGanttData[]): void {
const childRecords: IGanttData[] = parentRecord.childRecords;
for (let i: number = 0; i < childRecords.length; i++) {
if (childRecords[i].ganttProperties.isAutoSchedule) {
childLists.push(childRecords[i]);
if (childRecords[i].hasChildRecords) {
this.getUpdatableChildRecords(childRecords[i], childLists);
}
}
}
}
/**
* @param {ITaskbarEditedEventArgs} args .
* @returns {void} .
* @private
*/
public initiateSaveAction(args: ITaskbarEditedEventArgs): void {
this.parent.showSpinner();
let eventArgs: IActionBeginEventArgs = {};
eventArgs.requestType = 'beforeSave';
eventArgs.data = args.data;
eventArgs.cancel = false;
eventArgs.modifiedRecords = this.parent.editedRecords;
if (!isNullOrUndefined(args.target)) {
eventArgs.target = args.target;
}
eventArgs.modifiedTaskData = getTaskData(this.parent.editedRecords, true);
if (args.action && args.action === 'DrawConnectorLine') {
eventArgs.action = 'DrawConnectorLine';
}
this.parent.trigger('actionBegin', eventArgs, (eventArg: IActionBeginEventArgs) => {
if (eventArg.cancel) {
this.reUpdatePreviousRecords();
this.parent.chartRowsModule.refreshRecords([args.data]);
this.resetEditProperties(eventArgs);
// Trigger action complete event with save canceled request type
} else {
eventArg.modifiedTaskData = getTaskData(eventArg.modifiedRecords, null, null, this.parent);
if (isRemoteData(this.parent.dataSource)) {
const data: DataManager = this.parent.dataSource as DataManager;
const updatedData: object = {
changedRecords: eventArg.modifiedTaskData
};
const query: Query = this.parent.query instanceof Query ? this.parent.query : new Query();
let crud: Promise<Object> = null;
const dataAdaptor: AdaptorOptions = data.adaptor;
if (!(dataAdaptor instanceof WebApiAdaptor && dataAdaptor instanceof ODataAdaptor) || data.dataSource.batchUrl) {
crud = data.saveChanges(updatedData, this.parent.taskFields.id, null, query) as Promise<Object>;
} else {
const changedRecords: string = 'changedRecords';
crud = data.update(this.parent.taskFields.id, updatedData[changedRecords], null, query) as Promise<Object>;
}
crud.then((e: ReturnType) => this.dmSuccess(e, args))
.catch((e: { result: Object[] }) => this.dmFailure(e as { result: Object[] }, args));
} else {
this.saveSuccess(args);
}
}
});
}
private dmSuccess(e: ReturnType, args: ITaskbarEditedEventArgs): void {
this.saveSuccess(args);
}
private dmFailure(e: { result: Object[] }, args: ITaskbarEditedEventArgs): void {// eslint-disable-line
if (this.deletedTaskDetails.length) {
const deleteRecords: IGanttData[] = this.deletedTaskDetails;
for (let d: number = 0; d < deleteRecords.length; d++) {
deleteRecords[d].isDelete = false;
}
this.deletedTaskDetails = [];
}
this.reUpdatePreviousRecords(true, true);
this.resetEditProperties();
this.parent.trigger('actionFailure', { error: e });
}
private updateSharedTask(data: IGanttData): void {
const ids: string[] = data.ganttProperties.sharedTaskUniqueIds;
for (let i: number = 0; i < ids.length; i++) {
const editRecord: IGanttData = this.parent.flatData[this.parent.ids.indexOf(ids[i].toString())];
if (editRecord.uniqueID !== data.uniqueID) {
this.updateGanttProperties(data, editRecord);
this.parent.setRecordValue('taskData', data.taskData, editRecord, true);
this.parent.dataOperation.updateTaskData(editRecord);
this.parent.dataOperation.updateResourceName(editRecord);
if (!isNullOrUndefined(editRecord.parentItem)) {
this.parent.dataOperation.updateParentItems(editRecord.parentItem);
}
}
}
}
/**
* Method for save action success for local and remote data
*
* @param {ITaskAddedEventArgs} args .
* @returns {void} .
*/
private saveSuccess(args: ITaskbarEditedEventArgs): void {
const eventArgs: IActionBeginEventArgs = {};
if (this.parent.timelineSettings.updateTimescaleView) {
const tempArray: IGanttData[] = this.parent.editedRecords;
this.parent.timelineModule.updateTimeLineOnEditing([tempArray], args.action);
}
if (this.parent.viewType === 'ResourceView') {
if (args.action === 'TaskbarEditing') {
this.updateSharedTask(args.data);
} else if (args.action === 'DialogEditing' || args.action === 'CellEditing' || args.action === 'methodUpdate') {
if (this.parent.editModule.dialogModule.isResourceUpdate) {
/* eslint-disable-next-line */
this.updateResoures(this.parent.editModule.dialogModule.previousResource, args.data.ganttProperties.resourceInfo, args.data);
this.updateSharedTask(args.data);
this.isTreeGridRefresh = true;
} else {
this.updateSharedTask(args.data);
}
}
// method to update the edited parent records
for (let k: number = 0; k < this.updateParentRecords.length; k++) {
this.parent.dataOperation.updateParentItems(this.updateParentRecords[k]);
}
this.updateParentRecords = [];
this.parent.editModule.dialogModule.isResourceUpdate = false;
this.parent.editModule.dialogModule.previousResource = [];
}
if (!this.isTreeGridRefresh) {
this.parent.chartRowsModule.refreshRecords(this.parent.editedRecords);
if (this.parent.isConnectorLineUpdate && !isNullOrUndefined(this.parent.connectorLineEditModule)) {
this.parent.updatedConnectorLineCollection = [];
this.parent.connectorLineIds = [];
this.parent.connectorLineEditModule.refreshEditedRecordConnectorLine(this.parent.editedRecords);
this.updateScheduleDatesOnEditing(args);
}
}
if (!this.parent.editSettings.allowTaskbarEditing || (this.parent.editSettings.allowTaskbarEditing &&
!this.taskbarEditModule.dependencyCancel)) {
eventArgs.requestType = 'save';
eventArgs.data = args.data;
eventArgs.modifiedRecords = this.parent.editedRecords;
eventArgs.modifiedTaskData = getTaskData(this.parent.editedRecords, null, null, this.parent);
if (!isNullOrUndefined(args.action)) {
setValue('action', args.action, eventArgs);
}
if (args.action === 'TaskbarEditing') {
eventArgs.taskBarEditAction = args.taskBarEditAction;
}
this.endEditAction(args);
this.parent.trigger('actionComplete', eventArgs);
} else {
this.taskbarEditModule.dependencyCancel = false;
this.resetEditProperties();
}
if (this.parent.viewType === 'ResourceView' && this.isTreeGridRefresh) {
this.parent.treeGrid.parentData = [];
this.parent.treeGrid.refresh();
this.isTreeGridRefresh = false;
}
}
private updateResoures(prevResource: Object[], currentResource: Object[], updateRecord: IGanttData): void {
const flatRecords: IGanttData[] = this.parent.flatData;
const currentLength: number = currentResource ? currentResource.length : 0;
const previousLength: number = prevResource ? prevResource.length : 0;
if (currentLength === 0 && previousLength === 0) {
return;
}
for (let index: number = 0; index < currentLength; index++) {
const recordIndex: number[] = [];
const resourceID: number = parseInt(currentResource[index][this.parent.resourceFields.id], 10);
for (let i: number = 0; i < prevResource.length; i++) {
if (parseInt(prevResource[i][this.parent.resourceFields.id], 10) === resourceID) {
recordIndex.push(i);
break;
}
}
if (recordIndex.length === 0) {
const parentRecord: IGanttData = flatRecords[this.parent.getTaskIds().indexOf('R' + resourceID)];
if (parentRecord) {
this.addNewRecord(updateRecord, parentRecord);
}
} else {
prevResource.splice(parseInt(recordIndex[0].toString(), 10), 1);
}
}
const prevLength: number = prevResource ? prevResource.length : 0;
for (let index: number = 0; index < prevLength; index++) {
const taskID: string = updateRecord.ganttProperties.taskId;
const resourceID: string = prevResource[index][this.parent.resourceFields.id];
const record: IGanttData = flatRecords[this.parent.getTaskIds().indexOf('R' + resourceID)];
for (let j: number = 0; j < record.childRecords.length; j++) {
if (record.childRecords[j].ganttProperties.taskId === taskID) {
this.removeChildRecord(record.childRecords[j]);
}
}
}
if (currentLength > 0) {
const parentTask: IGanttData = this.parent.getParentTask(updateRecord.parentItem);
if (parentTask) {
if (parentTask.ganttProperties.taskName === this.parent.localeObj.getConstant('unassignedTask')) {
this.removeChildRecord(updateRecord);
}
}
}
//Assign resource to unassigned task
if (currentLength === 0) {
this.checkWithUnassignedTask(updateRecord);
}
}
/**
* @param {IGanttData} updateRecord .
* @returns {void} .
* @private
*/
public checkWithUnassignedTask(updateRecord: IGanttData): void {
let unassignedTasks: IGanttData = null;
// Block for check the unassigned task.
for (let i: number = 0; i < this.parent.flatData.length; i++) {
if (this.parent.flatData[i].ganttProperties.taskName === this.parent.localeObj.getConstant('unassignedTask')) {
unassignedTasks = this.parent.flatData[i];
}
}
if (!isNullOrUndefined(unassignedTasks)) {
this.addNewRecord(updateRecord, unassignedTasks);
} else {
// Block for create the unassigned task.
const unassignTaskObj: Object = {};
unassignTaskObj[this.parent.taskFields.id] = 0;
unassignTaskObj[this.parent.taskFields.name] = this.parent.localeObj.getConstant('unassignedTask');
const beforeEditStatus: boolean = this.parent.isOnEdit;
this.parent.isOnEdit = false;
const cAddedRecord: IGanttData = this.parent.dataOperation.createRecord(unassignTaskObj, 0);
this.parent.isOnEdit = beforeEditStatus;
this.addRecordAsBottom(cAddedRecord);
const parentRecord: IGanttData = this.parent.flatData[this.parent.flatData.length - 1];
this.addNewRecord(updateRecord, parentRecord);
}
}
private addRecordAsBottom(cAddedRecord: IGanttData): void {
const recordIndex1: number = this.parent.flatData.length;
this.parent.currentViewData.splice(recordIndex1 + 1, 0, cAddedRecord);
this.parent.flatData.splice(recordIndex1 + 1, 0, cAddedRecord);
this.parent.ids.splice(recordIndex1 + 1, 0, cAddedRecord.ganttProperties.rowUniqueID.toString());
const taskId: string = cAddedRecord.level === 0 ? 'R' + cAddedRecord.ganttProperties.taskId : 'T' + cAddedRecord.ganttProperties.taskId;
this.parent.getTaskIds().splice(recordIndex1 + 1, 0, taskId);
this.updateTreeGridUniqueID(cAddedRecord, 'add');
}
private addNewRecord(updateRecord: IGanttData, parentRecord: IGanttData): void {
let cAddedRecord: IGanttData = null;
cAddedRecord = extend({}, {}, updateRecord, true);
this.parent.setRecordValue('uniqueID', getUid(this.parent.element.id + '_data_'), cAddedRecord);
this.parent.setRecordValue('uniqueID', cAddedRecord.uniqueID, cAddedRecord.ganttProperties, true);
const uniqueId: string = cAddedRecord.uniqueID.replace(this.parent.element.id + '_data_', '');
this.parent.setRecordValue('rowUniqueID', uniqueId, cAddedRecord);
this.parent.setRecordValue('rowUniqueID', uniqueId, cAddedRecord.ganttProperties, true);
this.parent.setRecordValue('level', 1, cAddedRecord);
if (this.parent.taskFields.parentID) {
this.parent.setRecordValue('parentId', parentRecord.ganttProperties.taskId, cAddedRecord.ganttProperties, true);
}
this.parent.setRecordValue('parentItem', this.parent.dataOperation.getCloneParent(parentRecord), cAddedRecord);
const parentUniqId: string = cAddedRecord.parentItem ? cAddedRecord.parentItem.uniqueID : null;
this.parent.setRecordValue('parentUniqueID', parentUniqId, cAddedRecord);
updateRecord.ganttProperties.sharedTaskUniqueIds.push(uniqueId);
cAddedRecord.ganttProperties.sharedTaskUniqueIds = updateRecord.ganttProperties.sharedTaskUniqueIds;
this.addRecordAsChild(parentRecord, cAddedRecord);
}
private removeChildRecord(record: IGanttData): void {
const gObj: Gantt = this.parent;
let data: IGanttData[] = [];
if (this.parent.dataSource instanceof DataManager && this.parent.dataSource.dataSource.json.length > 0) {
data = this.parent.dataSource.dataSource.json;
} else {
data = this.parent.currentViewData;
}
const dataSource: Object = this.parent.dataSource;
const deletedRow: IGanttData = record;
const flatParentData: IGanttData = this.parent.getParentTask(deletedRow.parentItem);
if (deletedRow) {
if (deletedRow.parentItem) {
const deleteChildRecords: IGanttData[] = flatParentData ? flatParentData.childRecords : [];
let childIndex: number = 0;
if (deleteChildRecords && deleteChildRecords.length > 0) {
if (deleteChildRecords.length === 1) {
//For updating the parent record which has no child reords.
this.parent.isOnDelete = true;
deleteChildRecords[0].isDelete = true;
this.parent.dataOperation.updateParentItems(flatParentData);
this.parent.isOnDelete = false;
deleteChildRecords[0].isDelete = false;
}
childIndex = deleteChildRecords.indexOf(deletedRow);
flatParentData.childRecords.splice(childIndex, 1);
// collection for updating parent record
this.updateParentRecords.push(flatParentData);
}
}
if (deletedRow.ganttProperties.sharedTaskUniqueIds.length) {
const uniqueIDIndex: number =
deletedRow.ganttProperties.sharedTaskUniqueIds.indexOf(deletedRow.ganttProperties.rowUniqueID);
deletedRow.ganttProperties.sharedTaskUniqueIds.splice(uniqueIDIndex, 1);
}
this.updateTreeGridUniqueID(deletedRow, 'delete');
//method to delete the record from datasource collection
if (!this.parent.taskFields.parentID) {
const deleteRecordIDs: string[] = [];
deleteRecordIDs.push(deletedRow.ganttProperties.rowUniqueID.toString());
this.parent.editModule.removeFromDataSource(deleteRecordIDs);
}
const flatRecordIndex: number = this.parent.flatData.indexOf(deletedRow);
if (gObj.taskFields.parentID) {
let idx: number;
const ganttData: IGanttData[] = this.parent.currentViewData;
for (let i: number = 0; i < ganttData.length; i++) {
if (ganttData[i].ganttProperties.rowUniqueID === deletedRow.ganttProperties.rowUniqueID) {
idx = i;
}
}
if (idx !== -1) {
if ((dataSource as IGanttData[]).length > 0) {
(dataSource as IGanttData[]).splice(idx, 1);
}
data.splice(idx, 1);
this.parent.flatData.splice(flatRecordIndex, 1);
this.parent.ids.splice(flatRecordIndex, 1);
this.parent.getTaskIds().splice(flatRecordIndex, 1);
}
}
const recordIndex: number = data.indexOf(deletedRow);
if (!gObj.taskFields.parentID) {
const deletedRecordCount: number = this.parent.editModule.getChildCount(deletedRow, 0);
data.splice(recordIndex, deletedRecordCount + 1);
this.parent.flatData.splice(flatRecordIndex, deletedRecordCount + 1);
this.parent.ids.splice(flatRecordIndex, deletedRecordCount + 1);
this.parent.getTaskIds().splice(flatRecordIndex, deletedRecordCount + 1);
}
if (deletedRow.parentItem && flatParentData && flatParentData.childRecords && !flatParentData.childRecords.length) {
this.parent.setRecordValue('expanded', false, flatParentData);
this.parent.setRecordValue('hasChildRecords', false, flatParentData);
}
}
}
// Method to add new record after resource edit
private addRecordAsChild(droppedRecord: IGanttData, draggedRecord: IGanttData): void {
const gObj: Gantt = this.parent;
const recordIndex1: number = this.parent.flatData.indexOf(droppedRecord);
const childRecords: number = this.parent.editModule.getChildCount(droppedRecord, 0);
let childRecordsLength: number;
if (!isNullOrUndefined(this.addRowIndex) && this.addRowPosition && droppedRecord.childRecords && this.addRowPosition !== 'Child') {
const dropChildRecord: IGanttData = droppedRecord.childRecords[this.addRowIndex];
const position: RowPosition = this.addRowPosition === 'Above' || this.addRowPosition === 'Below' ? this.addRowPosition :
'Child';
childRecordsLength = dropChildRecord ? this.addRowIndex + recordIndex1 + 1 :
childRecords + recordIndex1 + 1;
childRecordsLength = position === 'Above' ? childRecordsLength : childRecordsLength + 1;
} else {
childRecordsLength = (isNullOrUndefined(childRecords) ||
childRecords === 0) ? recordIndex1 + 1 :
childRecords + recordIndex1 + 1;
}
//this.ganttData.splice(childRecordsLength, 0, this.draggedRecord);
this.parent.currentViewData.splice(childRecordsLength, 0, draggedRecord);
this.parent.flatData.splice(childRecordsLength, 0, draggedRecord);
this.parent.ids.splice(childRecordsLength, 0, draggedRecord.ganttProperties.rowUniqueID.toString());
this.updateTreeGridUniqueID(draggedRecord, 'add');
const recordId: string = draggedRecord.level === 0 ? 'R' + draggedRecord.ganttProperties.taskId : 'T' + draggedRecord.ganttProperties.taskId;
this.parent.getTaskIds().splice(childRecordsLength, 0, recordId);
if (!droppedRecord.hasChildRecords) {
this.parent.setRecordValue('hasChildRecords', true, droppedRecord);
this.parent.setRecordValue('expanded', true, droppedRecord);
if (!droppedRecord.childRecords.length) {
droppedRecord.childRecords = [];
if (!gObj.taskFields.parentID && isNullOrUndefined(droppedRecord.taskData[this.parent.taskFields.child])) {
droppedRecord.taskData[this.parent.taskFields.child] = [];
}
}
}
droppedRecord.childRecords.splice(droppedRecord.childRecords.length, 0, draggedRecord);
if (!isNullOrUndefined(draggedRecord) && !this.parent.taskFields.parentID
&& !isNullOrUndefined(droppedRecord.taskData[this.parent.taskFields.child])) {
droppedRecord.taskData[this.parent.taskFields.child].splice(droppedRecord.childRecords.length, 0, draggedRecord.taskData);
}
if (!isNullOrUndefined(draggedRecord.parentItem)) {
//collection to update the parent records
this.updateParentRecords.push(droppedRecord);
}
}
private resetEditProperties(args?: object): void {
this.parent.currentEditedArgs = {};
this.resetValidateArgs();
this.parent.editedTaskBarItem = null;
this.parent.isOnEdit = false;
this.validatedChildItems = [];
this.parent.isConnectorLineUpdate = false;
this.parent.editedTaskBarItem = null;
this.taskbarMoved = false;
this.predecessorUpdated = false;
if (!isNullOrUndefined(this.dialogModule) && (isNullOrUndefined(args) ||
(!isNullOrUndefined(args) && args['requestType'] === 'beforeSave' && !args['cancel']))) {
if (this.dialogModule.dialog && !this.dialogModule.dialogObj.isDestroyed) {
this.dialogModule.dialogObj.hide();
}
this.dialogModule.dialogClose();
}
this.parent.hideSpinner();
this.parent.initiateEditAction(false);
}
/**
* @param {ITaskAddedEventArgs} args .
* @returns {void} .
* @private
*/
public endEditAction(args: ITaskbarEditedEventArgs): void {
this.resetEditProperties();
if (args.action === 'TaskbarEditing') {
this.parent.trigger('taskbarEdited', args);
} else if (args.action === 'CellEditing') {
this.parent.trigger('endEdit', args);
} else if (args.action === 'DialogEditing') {
if (this.dialogModule.dialog && !this.dialogModule.dialogObj.isDestroyed) {
this.dialogModule.dialogObj.hide();
}
this.dialogModule.dialogClose();
}
}
// eslint-disable-next-line
private saveFailed(args: ITaskbarEditedEventArgs): void {
this.reUpdatePreviousRecords();
this.parent.hideSpinner();
//action failure event trigger
}
/**
* To render delete confirmation dialog
*
* @returns {void} .
*/
private renderDeleteConfirmDialog(): void {
const dialogObj: Dialog = new Dialog({
width: '320px',
isModal: true,
visible: false,
content: this.parent.localeObj.getConstant('confirmDelete'),
buttons: [
{
click: this.confirmDeleteOkButton.bind(this),
buttonModel: { content: this.parent.localeObj.getConstant('okText'), isPrimary: true }
},
{
click: this.closeConfirmDialog.bind(this),
buttonModel: { content: this.parent.localeObj.getConstant('cancel') }
}],
target: this.parent.element,
animationSettings: { effect: 'None' }
});
dialogObj.appendTo('#' + this.parent.element.id + '_deleteConfirmDialog');
this.confirmDialog = dialogObj;
}
private closeConfirmDialog(): void {
this.confirmDialog.hide();
}
private confirmDeleteOkButton(): void {
this.deleteSelectedItems();
this.confirmDialog.hide();
const focussedElement: HTMLElement = this.parent.element.querySelector('.e-treegrid');
focussedElement.focus();
}
/**
* @returns {void} .
* @private
*/
public startDeleteAction(): void {
if (this.parent.editSettings.allowDeleting && !this.parent.readOnly) {
if (this.parent.editSettings.showDeleteConfirmDialog) {
this.confirmDialog.show();
} else {
this.deleteSelectedItems();
}
}
}
/**
*
* @param {IGanttData[]} selectedRecords - Defines the deleted records
* @returns {void} .
* Method to delete the records from resource view Gantt.
*/
private deleteResourceRecords(selectedRecords: IGanttData[]): void {
const deleteRecords: IGanttData[] = [];
for (let i: number = 0; i < selectedRecords.length; i++) {
if (selectedRecords[i].parentItem) {
const data: IGanttData = selectedRecords[i];
const ids: string[] = data.ganttProperties.sharedTaskUniqueIds;
for (let j: number = 0; j < ids.length; j++) {
deleteRecords.push(this.parent.flatData[this.parent.ids.indexOf(ids[j].toString())]);
}
}
}
this.deleteRow(deleteRecords);
}
private deleteSelectedItems(): void {
if (!this.isFromDeleteMethod) {
let selectedRecords: IGanttData[] = [];
if (this.parent.selectionSettings.mode !== 'Cell') {
selectedRecords = this.parent.selectionModule.getSelectedRecords();
} else if (this.parent.selectionSettings.mode === 'Cell') {
selectedRecords = this.parent.selectionModule.getCellSelectedRecords();
}
if (this.parent.viewType === 'ResourceView') {
this.deleteResourceRecords(selectedRecords);
} else {
this.deleteRow(selectedRecords);
}
} else {
if (this.targetedRecords.length) {
if (this.parent.viewType === 'ResourceView') {
this.deleteResourceRecords(this.targetedRecords);
} else {
this.deleteRow(this.targetedRecords);
}
}
this.isFromDeleteMethod = false;
}
}
/**
* Method to delete record.
*
* @param {number | string | number[] | string[] | IGanttData | IGanttData[]} taskDetail - Defines the details of data to delete.
* @returns {void} .
* @public
*/
public deleteRecord(taskDetail: number | string | number[] | string[] | IGanttData | IGanttData[]): void {
this.isFromDeleteMethod = true;
const variableType: string = typeof (taskDetail);
this.targetedRecords = [];
switch (variableType) {
case 'number':
case 'string':
{
const taskId: string = taskDetail.toString();
if (this.parent.viewType === 'ResourceView') {
if (!isNullOrUndefined(taskId) && this.parent.getTaskIds().indexOf('T' + taskId) !== -1) {
this.targetedRecords.push(this.parent.flatData[this.parent.getTaskIds().indexOf('T' + taskId)]);
}
} else {
if (!isNullOrUndefined(taskId) && this.parent.ids.indexOf(taskId) !== -1) {
this.targetedRecords.push(this.parent.getRecordByID(taskId));
}
}
break;
}
case 'object':
if (!Array.isArray(taskDetail)) {
this.targetedRecords.push(taskDetail.valueOf());
} else {
this.updateTargetedRecords(taskDetail as object[]);
}
break;
default:
}
this.startDeleteAction();
}
/**
* To update 'targetedRecords collection' from given array collection
*
* @param {object[]} taskDetailArray .
* @returns {void} .
*/
private updateTargetedRecords(taskDetailArray: object[]): void {
if (taskDetailArray.length) {
const variableType: string = typeof (taskDetailArray[0]);
if (variableType === 'object') {
this.targetedRecords = taskDetailArray;
} else {
// Get record from array of task ids
for (let i: number = 0; i < taskDetailArray.length; i++) {
const id: string = taskDetailArray[i].toString();
if (this.parent.viewType === 'ResourceView') {
if (!isNullOrUndefined(id) && this.parent.getTaskIds().indexOf('T' + id) !== -1) {
this.targetedRecords.push(this.parent.flatData[this.parent.getTaskIds().indexOf('T' + id)]);
}
} else if (!isNullOrUndefined(id) && this.parent.ids.indexOf(id) !== -1) {
this.targetedRecords.push(this.parent.getRecordByID(id));
}
}
}
}
}
private deleteRow(tasks: IGanttData[]): void {
let rowItems: IGanttData[] = tasks && tasks.length ? tasks :
this.parent.selectionModule.getSelectedRecords();
this.parent.addDeleteRecord = true;
if (rowItems.length) {
this.parent.isOnDelete = true;
rowItems.forEach((item: IGanttData): void => {
item.isDelete = true;
});
if (this.parent.viewType === 'ResourceView' && !tasks.length) {
rowItems = [];
}
for (let i: number = 0; i < rowItems.length; i++) {
const deleteRecord: IGanttData = rowItems[i];
if (this.deletedTaskDetails.indexOf(deleteRecord) !== -1) {
continue;
}
if (deleteRecord.parentItem) {
const childRecord: IGanttData[] = this.parent.getParentTask(deleteRecord.parentItem).childRecords;
const filteredRecord: IGanttData[] = childRecord.length === 1 ?
childRecord : childRecord.filter((data: IGanttData): boolean => {
return !data.isDelete;
});
if (filteredRecord.length > 0) {
this.parent.dataOperation.updateParentItems(deleteRecord.parentItem);
}
}
const predecessor: IPredecessor[] = deleteRecord.ganttProperties.predecessor;
if (predecessor && predecessor.length) {
this.removePredecessorOnDelete(deleteRecord);
}
this.deletedTaskDetails.push(deleteRecord);
if (deleteRecord.hasChildRecords) {
this.deleteChildRecords(deleteRecord);
}
}
if (this.parent.selectionModule && this.parent.allowSelection) {
// clear selection
this.parent.selectionModule.clearSelection();
}
const delereArgs: ITaskDeletedEventArgs = {};
delereArgs.deletedRecordCollection = this.deletedTaskDetails;
delereArgs.updatedRecordCollection = this.parent.editedRecords;
delereArgs.cancel = false;
delereArgs.action = 'delete';
this.initiateDeleteAction(delereArgs);
this.parent.isOnDelete = false;
}
if (!isNullOrUndefined(this.parent.toolbarModule)) {
this.parent.toolbarModule.refreshToolbarItems();
}
}
public removePredecessorOnDelete(record: IGanttData): void {
const predecessors: IPredecessor[] = record.ganttProperties.predecessor;
for (let i: number = 0; i < predecessors.length; i++) {
const predecessor: IPredecessor = predecessors[i];
const recordId: string = this.parent.viewType === 'ResourceView' ? record.ganttProperties.taskId :
record.ganttProperties.rowUniqueID;
if (predecessor.from.toString() === recordId.toString()) {
const toRecord: IGanttData = this.parent.connectorLineModule.getRecordByID(predecessor.to.toString());
if (!isNullOrUndefined(toRecord)) {
const toRecordPredcessor: IPredecessor[] = extend([], [], toRecord.ganttProperties.predecessor, true) as IPredecessor[];
let index: number;
for (let t: number = 0; t < toRecordPredcessor.length; t++) {
const toId: string = this.parent.viewType === 'ResourceView' ? toRecord.ganttProperties.taskId :
toRecord.ganttProperties.rowUniqueID;
if (toRecordPredcessor[t].to.toString() === toId.toString()
&& toRecordPredcessor[t].from.toString() === recordId.toString()) {
index = t;
break;
}
}
toRecordPredcessor.splice(index, 1);
this.updatePredecessorValues(toRecord, toRecordPredcessor);
}
} else if (predecessor.to.toString() === recordId.toString()) {
const fromRecord: IGanttData = this.parent.connectorLineModule.getRecordByID(predecessor.from.toString());
if (!isNullOrUndefined(fromRecord)) {
const fromRecordPredcessor: IPredecessor[] = extend(
[], [], fromRecord.ganttProperties.predecessor, true) as IPredecessor[];
let index: number;
for (let t: number = 0; t < fromRecordPredcessor.length; t++) {
const fromId: string = this.parent.viewType === 'ResourceView' ? fromRecord.ganttProperties.taskId :
fromRecord.ganttProperties.rowUniqueID;
if (fromRecordPredcessor[t].from.toString() === fromId.toString()
&& fromRecordPredcessor[t].to.toString() === recordId.toString()) {
index = t;
break;
}
}
fromRecordPredcessor.splice(index, 1);
this.updatePredecessorValues(fromRecord, fromRecordPredcessor);
}
}
}
}
private updatePredecessorValues(record: IGanttData, predcessorArray: IPredecessor[]): void {
this.parent.setRecordValue('predecessor', predcessorArray, record.ganttProperties, true);
const predecessorString: string = this.parent.predecessorModule.getPredecessorStringValue(record);
this.parent.setRecordValue('predecessorsName', predecessorString, record.ganttProperties, true);
this.parent.setRecordValue('taskData.' + this.parent.taskFields.dependency, predecessorString, record);
this.parent.setRecordValue(this.parent.taskFields.dependency, predecessorString, record);
}
/**
* Method to update TaskID of a gantt record
*
* @param {string | number} currentId .
* @param {number | string} newId .
* @returns {void} .
*/
public updateTaskId(currentId: string | number, newId: number | string): void {
if (!this.parent.readOnly) {
const cId: string = typeof currentId === 'number' ? currentId.toString() : currentId;
const nId: string = typeof newId === 'number' ? newId.toString() : newId;
const ids: string[] = this.parent.ids;
if (!isNullOrUndefined(cId) && !isNullOrUndefined(nId)) {
const cIndex: number = ids.indexOf(cId);
const nIndex: number = ids.indexOf(nId);
// return false for invalid taskID
if (cIndex === -1 || nIndex > -1) {
return;
}
const thisRecord: IGanttData = this.parent.flatData[cIndex];
thisRecord.ganttProperties.taskId = thisRecord.ganttProperties.rowUniqueID = nId;
thisRecord.taskData[this.parent.taskFields.id] = nId;
thisRecord[this.parent.taskFields.id] = nId;
ids[cIndex] = nId;
if (thisRecord.hasChildRecords && this.parent.taskFields.parentID) {
const childRecords: IGanttData[] = thisRecord.childRecords;
for (let count: number = 0; count < childRecords.length; count++) {
const childRecord: IGanttData = childRecords[count];
childRecord[this.parent.taskFields.parentID] = newId;
this.parent.chartRowsModule.refreshRecords([childRecord]);
}
}
if (this.parent.taskFields.dependency && !isNullOrUndefined(thisRecord.ganttProperties.predecessor)) {
const predecessors: IPredecessor[] = thisRecord.ganttProperties.predecessor;
let currentGanttRecord: IGanttData;
for (let i: number = 0; i < predecessors.length; i++) {
const predecessor: IPredecessor = predecessors[i];
if (predecessor.to === cId) {
currentGanttRecord = this.parent.flatData[ids.indexOf(predecessor.from)];
} else if (predecessor.from === cId) {
currentGanttRecord = this.parent.flatData[ids.indexOf(predecessor.to)];
}
this.updatePredecessorOnUpdateId(currentGanttRecord, cId, nId);
}
}
this.parent.treeGrid.parentData = [];
this.parent.treeGrid.refresh();
}
}
}
private updatePredecessorOnUpdateId(currentGanttRecord: IGanttData, cId: string, nId: string): void {
if (this.parent.flatData.indexOf(currentGanttRecord) > -1) {
const pred: IPredecessor[] = currentGanttRecord.ganttProperties.predecessor;
for (let j: number = 0; j < pred.length; j++) {
const pre: IPredecessor = pred[j];
if (pre.to === cId) {
pre.to = nId;
} else if (pre.from === cId) {
pre.from = nId;
}
}
}
this.updatePredecessorValues(currentGanttRecord, currentGanttRecord.ganttProperties.predecessor);
}
private deleteChildRecords(record: IGanttData): void {
const childRecords: IGanttData[] = record.childRecords;
for (let c: number = 0; c < childRecords.length; c++) {
const childRecord: IGanttData = childRecords[c];
if (this.deletedTaskDetails.indexOf(childRecord) !== -1) {
continue;
}
const predecessor: IPredecessor[] = childRecord.ganttProperties.predecessor;
if (predecessor && predecessor.length) {
this.removePredecessorOnDelete(childRecord);
}
this.deletedTaskDetails.push(childRecord);
if (childRecord.hasChildRecords) {
this.deleteChildRecords(childRecord);
}
}
}
public removeFromDataSource(deleteRecordIDs: string[]): void {
let dataSource: Object[];
if (this.parent.dataSource instanceof DataManager) {
dataSource = this.parent.dataSource.dataSource.json;
} else {
dataSource = this.parent.dataSource as Object[];
}
this.removeData(dataSource, deleteRecordIDs);
this.isBreakLoop = false;
}
private removeData(dataCollection: Object[], record: string[]): boolean | void {
for (let i: number = 0; i < dataCollection.length; i++) {
if (this.isBreakLoop) {
break;
}
if (record.indexOf(getValue(this.parent.taskFields.id, dataCollection[i]).toString()) !== -1) {
if (dataCollection[i][this.parent.taskFields.child]) {
const childRecords: ITaskData[] = dataCollection[i][this.parent.taskFields.child];
this.removeData(childRecords, record);
}
record.splice(record.indexOf(getValue(this.parent.taskFields.id, dataCollection[i]).toString()), 1);
dataCollection.splice(i, 1);
if (record.length === 0) {
this.isBreakLoop = true;
break;
}
} else if (dataCollection[i][this.parent.taskFields.child]) {
const childRecords: ITaskData[] = dataCollection[i][this.parent.taskFields.child];
this.removeData(childRecords, record);
}
}
}
private initiateDeleteAction(args: ITaskDeletedEventArgs): void {
this.parent.showSpinner();
let eventArgs: IActionBeginEventArgs = {};
eventArgs.requestType = 'beforeDelete';
eventArgs.data = args.deletedRecordCollection;
eventArgs.modifiedRecords = args.updatedRecordCollection;
eventArgs.modifiedTaskData = getTaskData(args.updatedRecordCollection, null, null, this.parent);
this.parent.trigger('actionBegin', eventArgs, (eventArg: IActionBeginEventArgs) => {
if (eventArg.cancel) {
const deleteRecords: IGanttData[] = this.deletedTaskDetails;
for (let d: number = 0; d < deleteRecords.length; d++) {
deleteRecords[d].isDelete = false;
}
this.deletedTaskDetails = [];
this.reUpdatePreviousRecords();
this.parent.initiateEditAction(false);
this.parent.hideSpinner();
} else {
if (isRemoteData(this.parent.dataSource)) {
const data: DataManager = this.parent.dataSource as DataManager;
if (this.parent.timezone) {
updateDates(eventArg.modifiedTaskData as IGanttData, this.parent);
}
const updatedData: object = {
deletedRecords: getTaskData(eventArg.data as IGanttData[], null, null, this.parent), // to check
changedRecords: eventArg.modifiedTaskData
};
const adaptor: AdaptorOptions = data.adaptor;
const query: Query = this.parent.query instanceof Query ? this.parent.query : new Query();
if (!(adaptor instanceof WebApiAdaptor && adaptor instanceof ODataAdaptor) || data.dataSource.batchUrl) {
const crud: Promise<Object> = data.saveChanges(updatedData, this.parent.taskFields.id, null, query) as Promise<Object>;
crud.then(() => this.deleteSuccess(args))
.catch((e: { result: Object[] }) => this.dmFailure(e as { result: Object[] }, args));
} else {
const deletedRecords: string = 'deletedRecords';
let deleteCrud: Promise<Object> = null;
for (let i: number = 0; i < updatedData[deletedRecords].length; i++) {
deleteCrud = data.remove(this.parent.taskFields.id, updatedData[deletedRecords][i],
null, query) as Promise<Object>;
}
deleteCrud.then(() => {
const changedRecords: string = 'changedRecords';
const updateCrud: Promise<Object> =
data.update(this.parent.taskFields.id, updatedData[changedRecords], null, query) as Promise<Object>;
updateCrud.then(() => this.deleteSuccess(args))
.catch((e: { result: Object[] }) => this.dmFailure(e as { result: Object[] }, args));
}).catch((e: { result: Object[] }) => this.dmFailure(e as { result: Object[] }, args));
}
} else {
this.deleteSuccess(args);
}
}
});
}
private deleteSuccess(args: ITaskDeletedEventArgs): void {
const flatData: IGanttData[] = this.parent.flatData;
const currentData: IGanttData[] = this.parent.currentViewData;
const deletedRecords: IGanttData[] = this.parent.getRecordFromFlatdata(args.deletedRecordCollection);
const deleteRecordIDs: string[] = [];
if (deletedRecords.length > 0) {
this.parent.selectedRowIndex = deletedRecords[deletedRecords.length - 1].index;
}
for (let i: number = 0; i < deletedRecords.length; i++) {
const deleteRecord: IGanttData = deletedRecords[i];
const currentIndex: number = currentData.indexOf(deleteRecord);
const flatIndex: number = flatData.indexOf(deleteRecord);
const treeGridParentIndex: number = this.parent.treeGrid.parentData.indexOf(deleteRecord);
const tempData: ITaskData[] = getValue('dataOperation.dataArray', this.parent);
const dataIndex: number = tempData.indexOf(deleteRecord.taskData);
let childIndex: number;
if (currentIndex !== -1) { currentData.splice(currentIndex, 1); }
if (flatIndex !== -1) { flatData.splice(flatIndex, 1); }
if (dataIndex !== -1) { tempData.splice(dataIndex, 1); }
if (!isNullOrUndefined(deleteRecord)) {
deleteRecordIDs.push(deleteRecord.ganttProperties.taskId.toString());
if (flatIndex !== -1) {
this.parent.ids.splice(flatIndex, 1);
if (this.parent.viewType === 'ResourceView') {
this.parent.getTaskIds().splice(flatIndex, 1);
}
}
if (deleteRecord.level === 0 && treeGridParentIndex !== -1) {
this.parent.treeGrid.parentData.splice(treeGridParentIndex, 1);
}
if (deleteRecord.parentItem) {
const parentItem: IGanttData = this.parent.getParentTask(deleteRecord.parentItem);
if (parentItem) {
const childRecords: IGanttData[] = parentItem.childRecords;
childIndex = childRecords.indexOf(deleteRecord);
if (childIndex !== -1) { childRecords.splice(childIndex, 1); }
if (!childRecords.length) {
this.parent.setRecordValue('hasChildRecords', false, parentItem);
}
}
}
this.updateTreeGridUniqueID(deleteRecord, 'delete');
}
}
if (deleteRecordIDs.length > 0) {
this.removeFromDataSource(deleteRecordIDs);
}
const eventArgs: IActionBeginEventArgs = {};
this.parent.updatedConnectorLineCollection = [];
this.parent.connectorLineIds = [];
this.parent.predecessorModule.createConnectorLinesCollection(this.parent.flatData);
this.parent.treeGrid.parentData = [];
this.parent.treeGrid.refresh();
if (this.parent.enableImmutableMode) {
this.refreshRecordInImmutableMode();
}
// Trigger actioncomplete event for delete action
eventArgs.requestType = 'delete';
eventArgs.data = args.deletedRecordCollection;
eventArgs.modifiedRecords = args.updatedRecordCollection;
eventArgs.modifiedTaskData = getTaskData(args.updatedRecordCollection, null, null, this.parent);
setValue('action', args.action, eventArgs);
this.parent.trigger('actionComplete', eventArgs);
this.deletedTaskDetails = [];
this.parent.initiateEditAction(false);
this.parent.hideSpinner();
}
/**
*
* @returns {number | string} .
* @private
*/
public getNewTaskId(): number | string {
const maxId: number = DataUtil.aggregates.max(this.parent.flatData, this.parent.taskFields.id);
if (!isNullOrUndefined(maxId)) {
return parseInt(maxId.toString(), 10) + 1;
} else {
return 1;
}
}
/**
* @param {object} obj .
* @param {RowPosition} rowPosition .
* @returns {void} .
* @private
*/
// eslint-disable-next-line
private prepareNewlyAddedData(obj: Object, rowPosition: RowPosition): void {
const taskModel: TaskFieldsModel = this.parent.taskFields;
let id: string | number;
const ids: string[] = this.parent.ids;
/*Validate Task Id of data*/
if (obj[taskModel.id]) {
if (ids.indexOf(obj[taskModel.id].toString()) !== -1) {
obj[taskModel.id] = null;
} else {
obj[taskModel.id] = isNullOrUndefined(obj[taskModel.id]) ? null : parseInt(obj[taskModel.id], 10);
}
}
if (!obj[taskModel.id]) {
id = this.getNewTaskId();
obj[taskModel.id] = id;
}
if (!this.parent.allowUnscheduledTasks && !obj[taskModel.startDate]) {
obj[taskModel.startDate] = this.parent.projectStartDate;
}
if (!this.parent.allowUnscheduledTasks && taskModel.duration && isNullOrUndefined(obj[taskModel.duration])) {
if (!obj[taskModel.endDate]) {
obj[taskModel.duration] = '5';
}
}
if (taskModel.progress) {
obj[taskModel.progress] = obj[taskModel.progress] ? (obj[taskModel.progress] > 100 ? 100 : obj[taskModel.progress]) : 0;
}
if (!this.parent.allowUnscheduledTasks && !obj[taskModel.endDate] && taskModel.endDate) {
if (!obj[taskModel.duration]) {
const startDate: Date = this.parent.dataOperation.getDateFromFormat(this.parent.projectStartDate);
startDate.setDate(startDate.getDate() + 4);
obj[taskModel.endDate] = this.parent.getFormatedDate(startDate, this.parent.getDateFormat());
}
}
}
/**
* @param {object} obj .
* @param {number} level .
* @param {RowPosition} rowPosition .
* @param {IGanttData} parentItem .
* @returns {IGanttData} .
* @private
*/
private updateNewlyAddedDataBeforeAjax(
obj: Object, level: number, rowPosition: RowPosition, parentItem?: IGanttData): IGanttData {
const cAddedRecord: IGanttData = this.parent.dataOperation.createRecord(obj, level);
cAddedRecord.index = parseInt(cAddedRecord.ganttProperties.rowUniqueID.toString(), 10) - 1;
if (!isNullOrUndefined(parentItem)) {
this.parent.setRecordValue('parentItem', this.parent.dataOperation.getCloneParent(parentItem), cAddedRecord);
const pIndex: number = cAddedRecord.parentItem ? cAddedRecord.parentItem.index : null;
this.parent.setRecordValue('parentIndex', pIndex, cAddedRecord);
const parentUniqId: string = cAddedRecord.parentItem ? cAddedRecord.parentItem.uniqueID : null;
this.parent.setRecordValue('parentUniqueID', parentUniqId, cAddedRecord);
if (!isNullOrUndefined(this.parent.taskFields.id) &&
!isNullOrUndefined(this.parent.taskFields.parentID) && cAddedRecord.parentItem) {
if (this.parent.viewType === 'ProjectView') {
this.parent.setRecordValue(
this.parent.taskFields.parentID, cAddedRecord.parentItem.taskId, cAddedRecord.taskData, true);
}
this.parent.setRecordValue('parentId', cAddedRecord.parentItem.taskId, cAddedRecord.ganttProperties, true);
this.parent.setRecordValue(this.parent.taskFields.parentID, cAddedRecord.parentItem.taskId, cAddedRecord, true);
}
}
this.parent.isOnEdit = true;
this.backUpAndPushNewlyAddedRecord(cAddedRecord, rowPosition, parentItem);
// need to push in dataSource also.
if (this.parent.taskFields.dependency && cAddedRecord.ganttProperties.predecessorsName) {
this.parent.predecessorModule.ensurePredecessorCollectionHelper(cAddedRecord, cAddedRecord.ganttProperties);
this.parent.predecessorModule.updatePredecessorHelper(cAddedRecord);
this.parent.predecessorModule.validatePredecessorDates(cAddedRecord);
}
if (cAddedRecord.parentItem && this.parent.getParentTask(cAddedRecord.parentItem).ganttProperties.isAutoSchedule) {
this.parent.dataOperation.updateParentItems(cAddedRecord.parentItem);
}
this.parent.isOnEdit = false;
return cAddedRecord;
}
/**
* @param {IGanttData} record .
* @param {number} count .
* @returns {number} .
* @private
*/
public getChildCount(record: IGanttData, count: number): number {
let currentRecord: IGanttData;
if (!record.hasChildRecords) {
return 0;
}
for (let i: number = 0; i < record.childRecords.length; i++) {
currentRecord = record.childRecords[i];
count++;
if (currentRecord.hasChildRecords) {
count = this.getChildCount(currentRecord, count);
}
}
return count;
}
/**
* @param {IGanttData} data .
* @param {number} count .
* @param {IGanttData[]} collection .
* @returns {number} .
* @private
*/
private getVisibleChildRecordCount(data: IGanttData, count: number, collection: IGanttData[]): number {
let childRecords: IGanttData[];
let length: number;
if (data.hasChildRecords) {
childRecords = data.childRecords;
length = childRecords.length;
for (let i: number = 0; i < length; i++) {
if (collection.indexOf(childRecords[i]) !== -1) {
count++;
}
if (childRecords[i].hasChildRecords) {
count = this.getVisibleChildRecordCount(childRecords[i], count, collection);
}
}
} else {
if (collection.indexOf(data) !== -1) {
count++;
}
}
return count;
}
/**
* @param {IGanttData} parentRecord .
* @returns {void} .
* @private
*/
public updatePredecessorOnIndentOutdent(parentRecord: IGanttData): void {
const len: number = parentRecord.ganttProperties.predecessor.length;
const parentRecordTaskData: ITaskData = parentRecord.ganttProperties;
const predecessorCollection: IPredecessor[] = parentRecordTaskData.predecessor;
let childRecord: IGanttData;
let predecessorIndex: number;
const updatedPredecessor: IPredecessor[] = [];
for (let count: number = 0; count < len; count++) {
if (predecessorCollection[count].to === parentRecordTaskData.rowUniqueID.toString()) {
childRecord = this.parent.getRecordByID(predecessorCollection[count].from);
predecessorIndex = getIndex(predecessorCollection[count], 'from', childRecord.ganttProperties.predecessor, 'to');
// eslint-disable-next-line
let predecessorCollections: IPredecessor[] = (extend([], childRecord.ganttProperties.predecessor, [], true)) as IPredecessor[];
predecessorCollections.splice(predecessorIndex, 1);
this.parent.setRecordValue('predecessor', predecessorCollections, childRecord.ganttProperties, true);
} else if (predecessorCollection[count].from === parentRecordTaskData.rowUniqueID.toString()) {
childRecord = this.parent.getRecordByID(predecessorCollection[count].to);
const prdcList: string[] = (childRecord.ganttProperties.predecessorsName.toString()).split(',');
const str: string = predecessorCollection[count].from + predecessorCollection[count].type;
const ind: number = prdcList.indexOf(str);
prdcList.splice(ind, 1);
this.parent.setRecordValue('predecessorsName', prdcList.join(','), childRecord.ganttProperties, true);
this.parent.setRecordValue(this.parent.taskFields.dependency, prdcList.join(','), childRecord);
predecessorIndex = getIndex(predecessorCollection[count], 'from', childRecord.ganttProperties.predecessor, 'to');
// eslint-disable-next-line
const temppredecessorCollection: IPredecessor[] = (extend([], childRecord.ganttProperties.predecessor, [], true)) as IPredecessor[];
temppredecessorCollection.splice(predecessorIndex, 1);
this.parent.setRecordValue('predecessor', temppredecessorCollection, childRecord.ganttProperties, true);
this.parent.predecessorModule.validatePredecessorDates(childRecord);
}
}
this.parent.setRecordValue('predecessor', updatedPredecessor, parentRecord.ganttProperties, true);
this.parent.setRecordValue('predecessorsName', '', parentRecord.ganttProperties, true);
}
/**
* @param {IPredecessor[]} predecessorCollection .
* @param {IGanttData} record .
* @returns {string} .
* @private
*/
private predecessorToString(predecessorCollection: IPredecessor[], record: IGanttData): string {
const predecessorString: string[] = [];
let count: number = 0;
const length: number = predecessorCollection.length;
for (count; count < length; count++) {
if (record.ganttProperties.rowUniqueID.toString() !== predecessorCollection[count].from) {
let tem: string = predecessorCollection[count].from + predecessorCollection[count].type;
predecessorCollection[count].offset =
isNaN(predecessorCollection[count].offset) ? 0 : predecessorCollection[count].offset;
if (predecessorCollection[count].offset !== 0) {
if (predecessorCollection[count].offset < 0) {
tem += predecessorCollection[count].offset.toString() + 'd';
} else if (predecessorCollection[count].offset > 0) {
tem += '+' + predecessorCollection[count].offset.toString() + 'd';
}
}
predecessorString.push(tem);
}
}
return predecessorString.join(',');
}
/**
* @param {IGanttData} record .
* @param {RowPosition} rowPosition .
* @param {IGanttData} parentItem .
* @returns {void} .
* @private
*/
private backUpAndPushNewlyAddedRecord(
record: IGanttData, rowPosition: RowPosition, parentItem?: IGanttData): void {
const flatRecords: IGanttData[] = this.parent.flatData;
const currentViewData: IGanttData[] = this.parent.currentViewData;
const ids: string[] = this.parent.ids;
let currentItemIndex: number;
let recordIndex: number;
let updatedCollectionIndex: number;
let childIndex: number;
switch (rowPosition) {
case 'Top':
flatRecords.splice(0, 0, record);
currentViewData.splice(0, 0, record);
ids.splice(0, 0, record.ganttProperties.rowUniqueID.toString()); // need to check NAN
break;
case 'Bottom':
flatRecords.push(record);
currentViewData.push(record);
ids.push(record.ganttProperties.rowUniqueID.toString()); // need to check NAN
if (this.parent.viewType === 'ResourceView') {
const taskId: string = record.level === 0 ? 'R' + record.ganttProperties.taskId : 'T' + record.ganttProperties.taskId;
this.parent.getTaskIds().push(taskId);
}
break;
case 'Above':
/*Record Updates*/
recordIndex = flatRecords.indexOf(this.addRowSelectedItem);
updatedCollectionIndex = currentViewData.indexOf(this.addRowSelectedItem);
this.recordCollectionUpdate(childIndex, recordIndex, updatedCollectionIndex, record, parentItem, rowPosition);
break;
case 'Below':
currentItemIndex = flatRecords.indexOf(this.addRowSelectedItem);
if (this.addRowSelectedItem.hasChildRecords) {
const dataChildCount: number = this.getChildCount(this.addRowSelectedItem, 0);
recordIndex = currentItemIndex + dataChildCount + 1;
updatedCollectionIndex = currentViewData.indexOf(this.addRowSelectedItem) +
this.getVisibleChildRecordCount(this.addRowSelectedItem, 0, currentViewData) + 1;
} else {
recordIndex = currentItemIndex + 1;
updatedCollectionIndex = currentViewData.indexOf(this.addRowSelectedItem) + 1;
}
this.recordCollectionUpdate(childIndex + 1, recordIndex, updatedCollectionIndex, record, parentItem, rowPosition);
break;
case 'Child':
currentItemIndex = flatRecords.indexOf(this.addRowSelectedItem);
if (this.addRowSelectedItem.hasChildRecords) {
const dataChildCount: number = this.getChildCount(this.addRowSelectedItem, 0);
recordIndex = currentItemIndex + dataChildCount + 1;
//Expand Add record's parent item for project view
if (!this.addRowSelectedItem.expanded && !this.parent.enableMultiTaskbar) {
this.parent.expandByID(Number(this.addRowSelectedItem.ganttProperties.rowUniqueID));
}
updatedCollectionIndex = currentViewData.indexOf(this.addRowSelectedItem) +
this.getVisibleChildRecordCount(this.addRowSelectedItem, 0, currentViewData) + 1;
} else {
this.parent.setRecordValue('hasChildRecords', true, this.addRowSelectedItem);
this.parent.setRecordValue('isMilestone', false, this.addRowSelectedItem.ganttProperties, true);
this.parent.setRecordValue('expanded', true, this.addRowSelectedItem);
this.parent.setRecordValue('childRecords', [], this.addRowSelectedItem);
recordIndex = currentItemIndex + 1;
updatedCollectionIndex = currentViewData.indexOf(this.addRowSelectedItem) + 1;
if (this.addRowSelectedItem.ganttProperties.predecessor) {
this.updatePredecessorOnIndentOutdent(this.addRowSelectedItem);
}
if (!isNullOrUndefined(this.addRowSelectedItem.ganttProperties.segments)) {
this.addRowSelectedItem.ganttProperties.segments = null;
}
}
this.recordCollectionUpdate(childIndex + 1, recordIndex, updatedCollectionIndex, record, parentItem, rowPosition);
break;
}
this.newlyAddedRecordBackup = record;
}
/**
* @param {number} childIndex .
* @param {number} recordIndex .
* @param {number} updatedCollectionIndex .
* @param {IGanttData} record .
* @param {IGanttData} parentItem .
* @returns {void} .
* @private
*/
private recordCollectionUpdate(
childIndex: number, recordIndex: number, updatedCollectionIndex: number, record: IGanttData, parentItem: IGanttData, rowPosition: RowPosition): void {
const flatRecords: IGanttData[] = this.parent.flatData;
const currentViewData: IGanttData[] = this.parent.currentViewData;
const ids: string[] = this.parent.ids;
/* Record collection update */
flatRecords.splice(recordIndex, 0, record);
currentViewData.splice(updatedCollectionIndex, 0, record);
ids.splice(recordIndex, 0, record.ganttProperties.rowUniqueID.toString());
if (this.parent.viewType === 'ResourceView') {
const taskId: string = record.level === 0 ? 'R' + record.ganttProperties.taskId : 'T' + record.ganttProperties.taskId;
this.parent.getTaskIds().splice(recordIndex, 0, taskId);
}
/* data Source update */
if (!isNullOrUndefined(parentItem)) {
if (rowPosition == 'Above') {
childIndex = parentItem.childRecords.indexOf(this.addRowSelectedItem);
} else if(rowPosition == 'Below') {
childIndex = parentItem.childRecords.indexOf(this.addRowSelectedItem) + 1;
} else {
childIndex = parentItem.childRecords.length;
}
/*Child collection update*/
parentItem.childRecords.splice(childIndex, 0, record);
if ((this.parent.dataSource instanceof DataManager &&
isNullOrUndefined(parentItem.taskData[this.parent.taskFields.parentID])) ||
!isNullOrUndefined(this.parent.dataSource)) {
const child: string = this.parent.taskFields.child;
if (parentItem.taskData[child] && parentItem.taskData[child].length > 0) {
if (rowPosition === 'Above' || rowPosition === 'Below') {
parentItem.taskData[child].splice(childIndex, 0, record.taskData);
}
else {
parentItem.taskData[child].push(record.taskData);
}
} else {
parentItem.taskData[child] = [];
parentItem.taskData[child].push(record.taskData);
}
}
}
}
/**
* @param {IGanttData} cAddedRecord .
* @param {IGanttData} modifiedRecords .
* @param {string} event .
* @returns {ITaskAddedEventArgs} .
* @private
*/
private constructTaskAddedEventArgs(
cAddedRecord: IGanttData[], modifiedRecords: IGanttData[], event: string): ITaskAddedEventArgs {
const eventArgs: ITaskAddedEventArgs = {};
eventArgs.action = eventArgs.requestType = event;
if (cAddedRecord.length > 1) {
eventArgs.data = [];
eventArgs.newTaskData = [];
eventArgs.recordIndex = [];
for (let i: number = 0; i < cAddedRecord.length; i++) {
(eventArgs.data[i] as IGanttData[]) = (cAddedRecord[i] as IGanttData[]);
(eventArgs.newTaskData[i]) = (getTaskData([cAddedRecord[i]], eventArgs.data[i] as boolean, eventArgs, this.parent));
eventArgs.recordIndex[i] = cAddedRecord[i].index;
}
}
else if (cAddedRecord.length === 1) {
for (let i: number = 0; i < cAddedRecord.length; i++) {
(eventArgs.data) = (cAddedRecord[i]);
(eventArgs.newTaskData) = (getTaskData([cAddedRecord[i]], eventArgs.data as boolean, eventArgs, this.parent));
eventArgs.recordIndex = cAddedRecord[i].index;
}
}
eventArgs.modifiedRecords = modifiedRecords;
eventArgs.modifiedTaskData = getTaskData(modifiedRecords, null, null, this.parent);
return eventArgs;
}
/**
* @param {ITaskAddedEventArgs} args .
* @returns {void} .
* @private
*/
// eslint-disable-next-line
private addSuccess(args: ITaskAddedEventArgs): void {
// let addedRecords: IGanttData = args.addedRecord;
// let eventArgs: IActionBeginEventArgs = {};
// this.parent.updatedConnectorLineCollection = [];
// this.parent.connectorLineIds = [];
// this.parent.predecessorModule.createConnectorLinesCollection(this.parent.flatData);
this.parent.treeGrid.parentData = [];
this.parent.addDeleteRecord = true;
this.parent.selectedRowIndex = 0;
this.parent.treeGrid.refresh();
if (this.parent.enableImmutableMode) {
this.parent.modifiedRecords = args.modifiedRecords;
this.parent.modifiedRecords.push(args.data as IGanttData);
this.refreshRecordInImmutableMode();
}
}
private refreshRecordInImmutableMode(): void {
for (let i: number = 0; i < this.parent.modifiedRecords.length; i++) {
const originalData: IGanttData = this.parent.modifiedRecords[i];
let treeIndex: number = this.parent.allowRowDragAndDrop ? 1 : 0;
let uniqueTaskID: string = this.parent.taskFields.id;
var originalIndex: number = this.parent.currentViewData.findIndex((data: IGanttData) => {
return (data[uniqueTaskID] == originalData[uniqueTaskID]);
});
if (this.parent.treeGrid.getRows()[originalIndex]) {
this.parent.treeGrid.renderModule.cellRender({
data: originalData, cell: this.parent.treeGrid.getRows()[originalIndex].cells[this.parent.treeColumnIndex + treeIndex],
column: this.parent.treeGrid.grid.getColumns()[this.parent.treeColumnIndex],
requestType: 'rowDragAndDrop'
});
this.parent.treeGrid.renderModule.RowModifier({
data: originalData, row: this.parent.treeGrid.getRows()[originalIndex], rowHeight: this.parent.rowHeight
});
}
}
}
/**
* @param {IGanttData} addedRecord .
* @param {RowPosition} rowPosition .
* @returns {void} .
* @private
*/
public updateRealDataSource(addedRecord: IGanttData | IGanttData[], rowPosition: RowPosition): void {
const taskFields: TaskFieldsModel = this.parent.taskFields;
let dataSource: Object[] = isCountRequired(this.parent) ? getValue('result', this.parent.dataSource) :
this.parent.dataSource as Object[];
if (this.parent.dataSource instanceof DataManager) {
dataSource = this.parent.dataSource.dataSource.json;
}
for (let i: number = 0; i < (addedRecord as IGanttData[]).length; i++) {
if (isNullOrUndefined(rowPosition) || isNullOrUndefined(this.addRowSelectedItem)) {
rowPosition = rowPosition === 'Bottom' ? 'Bottom' : 'Top';
}
if (rowPosition === 'Top') {
dataSource.splice(0, 0, addedRecord[i].taskData);
} else if (rowPosition === 'Bottom') {
dataSource.push(addedRecord[i].taskData);
} else {
if (!isNullOrUndefined(taskFields.id) && !isNullOrUndefined(taskFields.parentID)) {
dataSource.push(addedRecord[i].taskData);
} else {
this.addDataInRealDataSource(dataSource, addedRecord[i].taskData, rowPosition);
}
}
this.isBreakLoop = false;
}
}
/**
* @param {object[]} dataCollection .
* @param {IGanttData} record .
* @param {RowPosition} rowPosition .
* @returns {void} .
* @private
*/
private addDataInRealDataSource(
dataCollection: Object[], record: IGanttData, rowPosition?: RowPosition): boolean | void {
for (let i: number = 0; i < dataCollection.length; i++) {
const child: string = this.parent.taskFields.child;
if (this.isBreakLoop) {
break;
}
if (getValue(
this.parent.taskFields.id, dataCollection[i]).toString() ===
this.addRowSelectedItem.ganttProperties.rowUniqueID.toString()) {
if (rowPosition === 'Above') {
dataCollection.splice(i, 0, record);
} else if (rowPosition === 'Below') {
dataCollection.splice(i + 1, 0, record);
} else if (rowPosition === 'Child') {
if (dataCollection[i][child] && dataCollection[i][child].length > 0) {
dataCollection[i][child].push(record);
} else {
dataCollection[i][child] = [];
dataCollection[i][child].push(record);
}
}
this.isBreakLoop = true;
break;
} else if (dataCollection[i][child]) {
const childRecords: ITaskData[] = dataCollection[i][child];
this.addDataInRealDataSource(childRecords, record, rowPosition);
}
}
}
/**
* Method to add new record.
*
* @param {Object[] | Object} data - Defines the new data to add.
* @param {RowPosition} rowPosition - Defines the position of row.
* @param {number} rowIndex - Defines the row index.
* @returns {void} .
* @private
*/
public addRecord(data?: Object[] | Object, rowPosition?: RowPosition, rowIndex?: number): void {
if (this.parent.editModule && this.parent.editSettings.allowAdding) {
this.parent.isDynamicData = true;
const cAddedRecord: IGanttData[] = [];
if (isNullOrUndefined(data)) {
this.validateTaskPosition(data, rowPosition, rowIndex, cAddedRecord);
}
else if (data instanceof Array) {
for (let i: number = 0; i < data.length; i++) {
this.validateTaskPosition(data[i], rowPosition, rowIndex, cAddedRecord);
}
}
else if (typeof (data) == 'object') {
this.validateTaskPosition(data, rowPosition, rowIndex, cAddedRecord);
}
else {
return;
}
let args: ITaskAddedEventArgs = {};
args = this.constructTaskAddedEventArgs(cAddedRecord, this.parent.editedRecords, 'beforeAdd');
this.parent.showSpinner();
this.parent.trigger('actionBegin', args, (args: ITaskAddedEventArgs) => {
if (!args.cancel) {
if (isRemoteData(this.parent.dataSource)) {
const data: DataManager = this.parent.dataSource as DataManager;
const updatedData: object = {
addedRecords: [args.newTaskData], // to check
changedRecords: args.modifiedTaskData
};
const prevID: string = (args.data as IGanttData).ganttProperties.taskId.toString();
/* tslint:disable-next-line */
const query: Query = this.parent.query instanceof Query ? this.parent.query : new Query();
const adaptor: AdaptorOptions = data.adaptor;
if (!(adaptor instanceof WebApiAdaptor && adaptor instanceof ODataAdaptor) || data.dataSource.batchUrl) {
/* tslint:disable-next-line */
const crud: Promise<Object> =
data.saveChanges(updatedData, this.parent.taskFields.id, null, query) as Promise<Object>;
crud.then((e: { addedRecords: Object[], changedRecords: Object[] }) => {
if (this.parent.taskFields.id && !isNullOrUndefined(e.addedRecords[0][this.parent.taskFields.id]) &&
e.addedRecords[0][this.parent.taskFields.id].toString() !== prevID) {
this.parent.setRecordValue(
'taskId', e.addedRecords[0][this.parent.taskFields.id], (args.data as IGanttData).ganttProperties, true);
this.parent.setRecordValue(
'taskData.' + this.parent.taskFields.id, e.addedRecords[0][this.parent.taskFields.id], args.data as IGanttData);
this.parent.setRecordValue(
this.parent.taskFields.id, e.addedRecords[0][this.parent.taskFields.id], args.data as IGanttData);
this.parent.setRecordValue(
'rowUniqueID', e.addedRecords[0][this.parent.taskFields.id].toString(),
(args.data as IGanttData).ganttProperties, true);
const idsIndex: number = this.parent.ids.indexOf(prevID);
if (idsIndex !== -1) {
this.parent.ids[idsIndex] = e.addedRecords[0][this.parent.taskFields.id].toString();
}
}
this.updateNewRecord(cAddedRecord, args);
}).catch((e: { result: Object[] }) => {
this.removeAddedRecord();
this.dmFailure(e as { result: Object[] }, args as ITaskbarEditedEventArgs);
this._resetProperties();
});
} else {
const addedRecords: string = 'addedRecords';
const insertCrud: Promise<Object> = data.insert(updatedData[addedRecords], null, query) as Promise<Object>;
insertCrud.then((e: ReturnType) => {
const changedRecords: string = 'changedRecords';
const addedRecords: Object = e[0];
/* tslint:disable-next-line */
const updateCrud: Promise<Object> =
data.update(this.parent.taskFields.id, updatedData[changedRecords], null, query) as Promise<Object>;
updateCrud.then(() => {
if (this.parent.taskFields.id && !isNullOrUndefined(addedRecords[this.parent.taskFields.id]) &&
addedRecords[this.parent.taskFields.id].toString() !== prevID) {
this.parent.setRecordValue(
'taskId', addedRecords[this.parent.taskFields.id], (args.data as IGanttData).ganttProperties, true);
this.parent.setRecordValue(
'taskData.' + this.parent.taskFields.id, addedRecords[this.parent.taskFields.id],
(args.data as IGanttData));
this.parent.setRecordValue(
this.parent.taskFields.id, addedRecords[this.parent.taskFields.id], (args.data as IGanttData));
this.parent.setRecordValue(
'rowUniqueID', addedRecords[this.parent.taskFields.id].toString(),
(args.data as IGanttData).ganttProperties, true);
const idIndex: number = this.parent.ids.indexOf(prevID);
if (idIndex !== -1) {
this.parent.ids[idIndex] = addedRecords[this.parent.taskFields.id].toString();
}
}
this.updateNewRecord(cAddedRecord, args);
}).catch((e: { result: Object[] }) => {
this.removeAddedRecord();
this.dmFailure(e as { result: Object[] }, args as ITaskbarEditedEventArgs);
this._resetProperties();
});
}).catch((e: { result: Object[] }) => {
this.removeAddedRecord();
this.dmFailure(e as { result: Object[] }, args as ITaskbarEditedEventArgs);
this._resetProperties();
});
}
} else {
if (this.parent.viewType === 'ProjectView') {
if ((rowPosition === 'Top' || rowPosition === 'Bottom') ||
((rowPosition === 'Above' || rowPosition === 'Below' || rowPosition === 'Child') && !(args.data as IGanttData).parentItem)) {
if (args.data instanceof Array) {
this.updateRealDataSource(args.data as IGanttData, rowPosition);
} else {
let data: Object[] = [];
data.push(args.data);
this.updateRealDataSource(data as IGanttData, rowPosition);
}
}
} else {
const dataSource: Object[] = isCountRequired(this.parent) ? getValue('result', this.parent.dataSource) :
this.parent.dataSource as Object[]; // eslint-disable-line
dataSource.push((args.data as IGanttData).taskData);
}
if ((cAddedRecord as IGanttData).level === 0) {
this.parent.treeGrid.parentData.splice(0, 0, cAddedRecord);
}
this.updateTreeGridUniqueID(cAddedRecord as IGanttData, 'add');
this.refreshNewlyAddedRecord(args, cAddedRecord);
this._resetProperties();
}
} else {
args = args;
this.removeAddedRecord();
this.reUpdatePreviousRecords();
this._resetProperties();
}
});
}
}
/**
* Method to validateTaskPosition.
*
* @param {Object | object[] } data - Defines the new data to add.
* @param {RowPosition} rowPosition - Defines the position of row.
* @param {number} rowIndex - Defines the row index.
* @param {IGanttData} cAddedRecord - Defines the single data to validate.
* @returns {void} .
* @private
*/
public createNewRecord(): IGanttData {
const tempRecord: IGanttData = {};
const ganttColumns: GanttColumnModel[] = this.parent.ganttColumns;
const taskSettingsFields: TaskFieldsModel = this.parent.taskFields;
const taskId: number | string = this.parent.editModule.getNewTaskId();
for (let i: number = 0; i < ganttColumns.length; i++) {
const fieldName: string = ganttColumns[i].field;
if (fieldName === taskSettingsFields.id) {
tempRecord[fieldName] = taskId;
} else if (ganttColumns[i].field === taskSettingsFields.startDate) {
if (isNullOrUndefined(tempRecord[taskSettingsFields.endDate])) {
tempRecord[fieldName] = this.parent.editModule.dialogModule.getMinimumStartDate();
} else {
tempRecord[fieldName] = new Date(tempRecord[taskSettingsFields.endDate]);
}
if (this.parent.timezone) {
tempRecord[fieldName] = this.parent.dateValidationModule.remove(tempRecord[fieldName], this.parent.timezone);
}
} else if (ganttColumns[i].field === taskSettingsFields.endDate) {
if (isNullOrUndefined(tempRecord[taskSettingsFields.startDate])) {
tempRecord[fieldName] = this.parent.editModule.dialogModule.getMinimumStartDate();
} else {
tempRecord[fieldName] = new Date(tempRecord[taskSettingsFields.startDate]);
}
if (this.parent.timezone) {
tempRecord[fieldName] = this.parent.dateValidationModule.remove(tempRecord[fieldName], this.parent.timezone);
}
} else if (ganttColumns[i].field === taskSettingsFields.duration) {
tempRecord[fieldName] = 1;
} else if (ganttColumns[i].field === taskSettingsFields.name) {
tempRecord[fieldName] = this.parent.editModule.dialogModule['localeObj'].getConstant('addDialogTitle')+' '+ taskId;
} else if (ganttColumns[i].field === taskSettingsFields.progress) {
tempRecord[fieldName] = 0;
} else if (ganttColumns[i].field === taskSettingsFields.work) {
tempRecord[fieldName] = 0;
} else if (ganttColumns[i].field === 'taskType') {
tempRecord[fieldName] = this.parent.taskType;
} else {
tempRecord[this.parent.ganttColumns[i].field] = '';
}
}
return tempRecord;
}
public validateTaskPosition(data?: Object | object[], rowPosition?: RowPosition, rowIndex?: number, cAddedRecord?: IGanttData[]): void {
const selectedRowIndex: number = isNullOrUndefined(rowIndex) || isNaN(parseInt(rowIndex.toString(), 10)) ?
this.parent.selectionModule ?
(this.parent.selectionSettings.mode === 'Row' || this.parent.selectionSettings.mode === 'Both') &&
this.parent.selectionModule.selectedRowIndexes.length === 1 ?
this.parent.selectionModule.selectedRowIndexes[0] :
this.parent.selectionSettings.mode === 'Cell' &&
this.parent.selectionModule.getSelectedRowCellIndexes().length === 1 ?
this.parent.selectionModule.getSelectedRowCellIndexes()[0].rowIndex : null : null : rowIndex;
this.addRowSelectedItem = isNullOrUndefined(selectedRowIndex) ? null : this.parent.updatedRecords[selectedRowIndex];
rowPosition = isNullOrUndefined(rowPosition) ? this.parent.editSettings.newRowPosition : rowPosition;
data = isNullOrUndefined(data) ? this.createNewRecord() : data;
if (((isNullOrUndefined(selectedRowIndex) || selectedRowIndex < 0 ||
isNullOrUndefined(this.addRowSelectedItem)) && (rowPosition === 'Above'
|| rowPosition === 'Below'
|| rowPosition === 'Child')) || !rowPosition || (rowPosition !== 'Above'
&& rowPosition !== 'Below'
&& rowPosition !== 'Child' && rowPosition !== 'Top' &&
rowPosition !== 'Bottom')) {
rowPosition = 'Top';
}
let level: number = 0;
let parentItem: IGanttData;
switch (rowPosition) {
case 'Top':
case 'Bottom':
if (this.parent.viewType === "ResourceView") {
level = 1;
} else {
level = 0;
}
break;
case 'Above':
case 'Below':
level = this.addRowSelectedItem.level;
parentItem = this.parent.getParentTask(this.addRowSelectedItem.parentItem);
break;
case 'Child':
level = this.addRowSelectedItem.level + 1;
parentItem = this.addRowSelectedItem;
break;
}
this.prepareNewlyAddedData(data, rowPosition);
const AddRecord: IGanttData = (this.updateNewlyAddedDataBeforeAjax(data, level, rowPosition, parentItem));
cAddedRecord.push(AddRecord);
}
private updateNewRecord(cAddedRecord: IGanttData[], args: ITaskAddedEventArgs): void {
if ((cAddedRecord as IGanttData).level === 0) {
this.parent.treeGrid.parentData.splice(0, 0, cAddedRecord);
const tempData: ITaskData[] = getValue('dataOperation.dataArray', this.parent);
tempData.splice(0, 0, (cAddedRecord as IGanttData).taskData);
}
this.updateTreeGridUniqueID(cAddedRecord as IGanttData, 'add');
this.refreshNewlyAddedRecord(args, cAddedRecord);
this._resetProperties();
}
/**
* Method to reset the flag after adding new record
*
* @returns {void} .
*/
private _resetProperties(): void {
this.parent.isOnEdit = false;
this.parent.hideSpinner();
this.addRowSelectedItem = null;
this.newlyAddedRecordBackup = null;
this.isBreakLoop = false;
this.parent.element.tabIndex = 0;
this.parent.initiateEditAction(false);
}
/**
* Method to update unique id collection in TreeGrid
*
* @param {IGanttData} data .
* @param {string} action .
* @returns {void} .
*/
private updateTreeGridUniqueID(data: IGanttData, action: string): void {
if (action === 'add') {
setValue('uniqueIDCollection.' + data.uniqueID, data, this.parent.treeGrid);
} else if (action === 'delete') {
deleteObject(getValue('uniqueIDCollection', this.parent.treeGrid), data.uniqueID);
}
}
private refreshNewlyAddedRecord(args: ITaskAddedEventArgs, cAddedRecord: IGanttData[]): void {
if (this.parent.selectionModule && this.parent.allowSelection &&
(this.parent.selectionSettings.mode === 'Row' || this.parent.selectionSettings.mode === 'Both')) {
this.parent.staticSelectedRowIndex = this.parent.currentViewData.indexOf(args.data as IGanttData);
}
if (this.parent.timelineSettings.updateTimescaleView) {
let tempArray: IGanttData[] = [];
if (args.modifiedRecords.length > 0) {
tempArray = (args.data as IGanttData[]).length > 0 ? args.data as IGanttData[] : [args.data as IGanttData];
// eslint-disable-next-line
tempArray.push.apply(tempArray, args.modifiedRecords);
} else {
tempArray = (args.data as IGanttData[]).length > 0 ? args.data as IGanttData[] : [args.data as IGanttData];
}
this.parent.timelineModule.updateTimeLineOnEditing([tempArray], args.action);
}
this.addSuccess(args);
args = this.constructTaskAddedEventArgs(cAddedRecord, args.modifiedRecords, 'add');
if (this.dialogModule.isAddNewResource && !this.parent.isEdit && this.parent.taskFields.work){
this.parent.dataOperation.updateWorkWithDuration(cAddedRecord[0]);
}
this.parent.trigger('actionComplete', args);
if (this.dialogModule.dialog && !this.dialogModule.dialogObj.isDestroyed) {
this.dialogModule.dialogObj.hide();
}
this.dialogModule.dialogClose();
if (this.parent.viewType === 'ResourceView') {
if (cAddedRecord.length > 1) {
for (let i: number = 0; i < cAddedRecord.length; i++) {
(args.data[i] as IGanttData).ganttProperties.sharedTaskUniqueIds.push((args.data[i] as IGanttData)
.ganttProperties.rowUniqueID);
if ((args.data[i] as IGanttData).ganttProperties.resourceInfo) {
// if ((args.data[i] as IGanttData).ganttProperties.resourceInfo.length > 1) {
const resources: Object[] =
extend([], [], (args.data[i] as IGanttData).ganttProperties.resourceInfo, true) as Object[];
resources.splice(0, 1);
this.updateResoures([], resources, args.data[i] as IGanttData);
// }
}
else {
this.removeChildRecord(args.data[i] as IGanttData);
this.parent.editModule.checkWithUnassignedTask(args.data[i] as IGanttData);
}
for (let k: number = 0; k < this.updateParentRecords.length; k++) {
this.parent.dataOperation.updateParentItems(this.updateParentRecords[k]);
}
this.updateParentRecords = [];
}
}
else {
(args.data as IGanttData).ganttProperties.sharedTaskUniqueIds.push((args.data as IGanttData).ganttProperties.rowUniqueID);
// eslint-disable-next-line
if ((args.data as IGanttData).ganttProperties.resourceInfo && (args.data as IGanttData).ganttProperties.resourceInfo.length) {
if ((args.data as IGanttData).ganttProperties.resourceInfo.length > 1) {
// eslint-disable-next-line
const resources: Object[] = extend([], [], (args.data as IGanttData).ganttProperties.resourceInfo, true) as Object[];
resources.splice(0, 1);
this.updateResoures([], resources, args.data as IGanttData);
}
}
else {
this.removeChildRecord(args.data as IGanttData);
this.parent.editModule.checkWithUnassignedTask(args.data as IGanttData);
}
for (let k: number = 0; k < this.updateParentRecords.length; k++) {
this.parent.dataOperation.updateParentItems(this.updateParentRecords[k]);
}
this.updateParentRecords = [];
}
}
}
/**
*
* @returns {void} .
* @private
*/
private removeAddedRecord(): void {
const flatRecords: IGanttData[] = this.parent.flatData;
const currentViewData: IGanttData[] = this.parent.currentViewData;
const ids: string[] = this.parent.ids;
const flatRecordsIndex: number = flatRecords.indexOf(this.newlyAddedRecordBackup);
const currentViewDataIndex: number = currentViewData.indexOf(this.newlyAddedRecordBackup);
const idsIndex: number = ids.indexOf(this.newlyAddedRecordBackup.ganttProperties.rowUniqueID.toString());
deleteObject(this.parent.previousRecords, flatRecords[flatRecordsIndex].uniqueID);
if (this.newlyAddedRecordBackup.parentItem) {
const parentItem: IGanttData = this.parent.getParentTask(this.newlyAddedRecordBackup.parentItem);
const parentIndex: number = parentItem.childRecords.indexOf(this.newlyAddedRecordBackup);
parentItem.childRecords.splice(parentIndex, 1);
}
flatRecords.splice(flatRecordsIndex, 1);
currentViewData.splice(currentViewDataIndex, 1);
ids.splice(idsIndex, 1);
}
private getPrevRecordIndex(): number {
const prevRecord: IGanttData = this.parent.updatedRecords[this.parent.selectionModule.getSelectedRowIndexes()[0] - 1];
const selectedRecord: IGanttData = this.parent.selectionModule.getSelectedRecords()[0];
const parent: IGanttData = this.parent.getRootParent(prevRecord, selectedRecord.level);
const prevIndex: number = this.parent.updatedRecords.indexOf(parent);
return prevIndex;
}
/**
* indent a selected record
*
* @returns {void} .
*/
public indent(): void {
const index: number = this.parent.selectedRowIndex;
const isSelected: boolean = this.parent.selectionModule ? this.parent.selectionModule.selectedRowIndexes.length === 1 ||
this.parent.selectionModule.getSelectedRowCellIndexes().length === 1 ? true : false : false;
let dropIndex: number;
const prevRecord: IGanttData = this.parent.updatedRecords[this.parent.selectionModule.getSelectedRowIndexes()[0] - 1];
const selectedRecord: IGanttData = this.parent.selectionModule.getSelectedRecords()[0];
if (!this.parent.editSettings.allowEditing || index === 0 || index === -1 || !isSelected ||
this.parent.viewType === 'ResourceView' || this.parent.updatedRecords[index].level - prevRecord.level === 1) {
return;
} else {
if (prevRecord.level - selectedRecord.level === 0) {
dropIndex = this.parent.selectionModule.getSelectedRowIndexes()[0] - 1;
} else {
dropIndex = this.getPrevRecordIndex();
}
this.indentOutdentRow([this.parent.selectionModule.getSelectedRowIndexes()[0]], dropIndex, 'child');
}
}
/**
* To perform outdent operation for selected row
*
* @returns {void} .
*/
public outdent(): void {
const index: number = this.parent.selectionModule.getSelectedRowIndexes()[0];
let dropIndex: number;
const isSelected: boolean = this.parent.selectionModule ? this.parent.selectionModule.selectedRowIndexes.length === 1 ||
this.parent.selectionModule.getSelectedRowCellIndexes().length === 1 ? true : false : false;
if (!this.parent.editSettings.allowEditing || index === -1 || index === 0 || !isSelected ||
this.parent.viewType === 'ResourceView' || this.parent.updatedRecords[index].level === 0) {
return;
} else {
const thisParent: IGanttData = this.parent.getTaskByUniqueID((this.parent.selectionModule.getSelectedRecords()[0] as
IGanttData).parentItem.uniqueID);
dropIndex = this.parent.updatedRecords.indexOf(thisParent);
this.indentOutdentRow([index], dropIndex, 'below');
}
}
private indentOutdentRow(fromIndexes: number[], toIndex: number, pos: string): void {
// eslint-disable-next-line
if (fromIndexes[0] !== toIndex && pos === 'above' || 'below' || 'child') {
if (pos === 'above') {
this.dropPosition = 'topSegment';
}
if (pos === 'below') {
this.dropPosition = 'bottomSegment';
}
if (pos === 'child') {
this.dropPosition = 'middleSegment';
}
let action: string;
const record: IGanttData[] = [];
for (let i: number = 0; i < fromIndexes.length; i++) {
record[i] = this.parent.updatedRecords[fromIndexes[i]];
}
const isByMethod: boolean = true;
const args: RowDropEventArgs = {
data: record,
dropIndex: toIndex,
dropPosition: this.dropPosition
};
if (this.dropPosition === 'middleSegment') {
action = 'indenting';
} else if (this.dropPosition === 'bottomSegment') {
action = 'outdenting';
}
const actionArgs: IActionBeginEventArgs = {
action : action,
data: record[0],
cancel: false
};
this.parent.trigger('actionBegin', actionArgs, (actionArg: IActionBeginEventArgs) => {
if (!actionArg.cancel) {
this.reArrangeRows(args, isByMethod);
} else {
return;
}
});
} else {
return;
}
}
private reArrangeRows(args: RowDropEventArgs, isByMethod?: boolean): void {
this.dropPosition = args.dropPosition;
if (args.dropPosition !== 'Invalid' && this.parent.editModule) {
const obj: Gantt = this.parent; let draggedRec: IGanttData;
this.droppedRecord = obj.updatedRecords[args.dropIndex];
let dragRecords: IGanttData[] = [];
const droppedRec: IGanttData = this.droppedRecord;
if (!args.data[0]) {
dragRecords.push(args.data as IGanttData);
} else {
dragRecords = args.data;
}
let c: number = 0;
const dLength: number = dragRecords.length;
for (let i: number = 0; i < dLength; i++) {
this.parent.isOnEdit = true;
draggedRec = dragRecords[i];
this.draggedRecord = draggedRec;
if (this.dropPosition !== 'Invalid') {
if (isByMethod) {
this.deleteDragRow();
}
const recordIndex1: number = this.treeGridData.indexOf(droppedRec);
if (this.dropPosition === 'bottomSegment') {
if (!droppedRec.hasChildRecords) {
if (this.parent.taskFields.parentID && (this.ganttData as IGanttData[]).length > 0) {
(this.ganttData as IGanttData[]).splice(recordIndex1 + 1, 0, this.draggedRecord.taskData);
}
this.treeGridData.splice(recordIndex1 + 1, 0, this.draggedRecord);
this.parent.ids.splice(recordIndex1 + 1, 0, this.draggedRecord.ganttProperties.rowUniqueID.toString());
} else {
c = this.parent.editModule.getChildCount(droppedRec, 0);
if (this.parent.taskFields.parentID && (this.ganttData as IGanttData[]).length > 0) {
(this.ganttData as IGanttData[]).splice(recordIndex1 + c + 1, 0, this.draggedRecord.taskData);
}
this.treeGridData.splice(recordIndex1 + c + 1, 0, this.draggedRecord);
this.parent.ids.splice(recordIndex1 + c + 1, 0, this.draggedRecord.ganttProperties.rowUniqueID.toString());
const idIndex: number = this.parent.ids.indexOf(this.draggedRecord[this.parent.taskFields.id].toString());
if (idIndex !== recordIndex1 + c + 1) {
this.parent.ids.splice(idIndex, 1);
this.parent.ids.splice(recordIndex1 + c + 1, 0, this.draggedRecord[this.parent.taskFields.id].toString());
}
}
this.parent.setRecordValue('parentItem', this.treeGridData[recordIndex1].parentItem, draggedRec);
this.parent.setRecordValue('parentUniqueID', this.treeGridData[recordIndex1].parentUniqueID, draggedRec);
this.parent.setRecordValue('level', this.treeGridData[recordIndex1].level, draggedRec);
if (draggedRec.hasChildRecords) {
const level: number = 1;
this.updateChildRecordLevel(draggedRec, level);
this.updateChildRecord(draggedRec, recordIndex1 + c + 1);
}
if (droppedRec.parentItem) {
const record: IGanttData[] = this.parent.getParentTask(droppedRec.parentItem).childRecords;
const childRecords: IGanttData[] = record;
const droppedRecordIndex: number = childRecords.indexOf(droppedRec) + 1;
childRecords.splice(droppedRecordIndex, 0, draggedRec);
}
}
if (this.dropPosition === 'middleSegment') {
this.dropMiddle(recordIndex1);
}
if (!isNullOrUndefined(draggedRec.parentItem && this.updateParentRecords.indexOf(draggedRec.parentItem) !== -1)) {
this.updateParentRecords.push(draggedRec.parentItem);
}
}
if (isNullOrUndefined(draggedRec.parentItem)) {
const parentRecords: ITreeData[] = this.parent.treeGrid.parentData;
const newParentIndex: number = parentRecords.indexOf(this.droppedRecord);
if (this.dropPosition === 'bottomSegment') {
parentRecords.splice(newParentIndex + 1, 0, draggedRec);
}
}
this.refreshDataSource();
}
if (this.dropPosition === 'middleSegment') {
if (droppedRec.ganttProperties.predecessor) {
this.parent.editModule.removePredecessorOnDelete(droppedRec);
droppedRec.ganttProperties.predecessor = null;
droppedRec.ganttProperties.predecessorsName = null;
droppedRec[this.parent.taskFields.dependency] = null;
droppedRec.taskData[this.parent.taskFields.dependency] = null;
}
if (droppedRec.ganttProperties.isMilestone) {
this.parent.setRecordValue('isMilestone', false, droppedRec.ganttProperties, true);
if (!isNullOrUndefined(droppedRec.taskData[this.parent.taskFields.milestone])) {
if (droppedRec.taskData[this.parent.taskFields.milestone] === true) {
droppedRec.taskData[this.parent.taskFields.milestone] = false;
}
}
}
}
for (let k: number = 0; k < this.updateParentRecords.length; k++) {
this.parent.dataOperation.updateParentItems(this.updateParentRecords[k]);
}
this.updateParentRecords = [];
this.parent.isOnEdit = false;
}
this.refreshRecord(args);
}
/**
* @returns {void} .
* @private
*/
public refreshRecord(args: RowDropEventArgs, isDrag?: boolean): void {
if (isRemoteData(this.parent.dataSource)) {
const data: DataManager = this.parent.dataSource as DataManager;
const updatedData: object = {
changedRecords: getTaskData(this.parent.editedRecords, null, null, this.parent)
};
const queryValue: Query = this.parent.query instanceof Query ? this.parent.query : new Query();
let crud: Promise<Object> = null;
const adaptor: AdaptorOptions = data.adaptor;
if (!(adaptor instanceof WebApiAdaptor && adaptor instanceof ODataAdaptor) || data.dataSource.batchUrl) {
crud = data.saveChanges(updatedData, this.parent.taskFields.id, null, queryValue) as Promise<Object>;
} else {
const changedRecords: string = 'changedRecords';
crud = data.update(this.parent.taskFields.id, updatedData[changedRecords], null, queryValue) as Promise<Object>;
}
crud.then((e: ReturnType) => this.indentSuccess(e, args, isDrag))
.catch((e: { result: Object[] }) => this.indentFailure(e as { result: Object[] }));
} else {
this.indentOutdentSuccess(args, isDrag);
}
}
private indentSuccess(e: ReturnType, args: RowDropEventArgs, isDrag: boolean): void {
this.indentOutdentSuccess(args, isDrag);
}
private indentFailure(e: { result: Object[] }): void {
this.parent.trigger('actionFailure', { error: e });
}
private indentOutdentSuccess(args: RowDropEventArgs, isDrag: boolean): void {
this.parent.treeGrid.parentData = [];
this.parent.treeGrid.refresh();
if (this.parent.enableImmutableMode) {
this.refreshRecordInImmutableMode();
}
if (isDrag) {
args.requestType = 'rowDropped';
} else {
if (this.dropPosition === 'middleSegment') {
args.requestType = 'indented';
} else if (this.dropPosition === 'bottomSegment') {
args.requestType = 'outdented';
}
}
args.modifiedRecords = this.parent.editedRecords;
if (this.parent.timezone) {
for (let i: number = 0; i < args.modifiedRecords.length; i++) {
updateDates(args.modifiedRecords[i], this.parent);
}
}
this.parent.trigger('actionComplete', args);
this.parent.editedRecords = [];
}
private refreshDataSource(): void {
const draggedRec: IGanttData = this.draggedRecord;
const droppedRec: IGanttData = this.droppedRecord;
const proxy: Gantt = this.parent;
let tempData: Object;
let indx: number;
if (this.parent.dataSource instanceof DataManager) {
tempData = getValue('dataOperation.dataArray', this.parent);
} else {
tempData = proxy.dataSource;
}
if ((tempData as IGanttData[]).length > 0 && (!isNullOrUndefined(droppedRec) && !droppedRec.parentItem)) {
for (let i: number = 0; i < Object.keys(tempData).length; i++) {
if (tempData[i][this.parent.taskFields.child] === droppedRec.taskData[this.parent.taskFields.child]) {
indx = i;
}
}
if (this.dropPosition === 'topSegment') {
if (!this.parent.taskFields.parentID) {
(tempData as IGanttData[]).splice(indx, 0, draggedRec.taskData);
}
} else if (this.dropPosition === 'bottomSegment') {
if (!this.parent.taskFields.parentID) {
(tempData as IGanttData[]).splice(indx + 1, 0, draggedRec.taskData);
}
}
} else if (!this.parent.taskFields.parentID && (!isNullOrUndefined(droppedRec) && droppedRec.parentItem)) {
if (this.dropPosition === 'topSegment' || this.dropPosition === 'bottomSegment') {
const rowPos: RowPosition = this.dropPosition === 'topSegment' ? 'Above' : 'Below';
this.parent.editModule.addRowSelectedItem = droppedRec;
this.parent.editModule.updateRealDataSource(draggedRec, rowPos);
delete this.parent.editModule.addRowSelectedItem;
}
}
if (this.parent.taskFields.parentID) {
if (draggedRec.parentItem) {
if (this.dropPosition === 'topSegment' || this.dropPosition === 'bottomSegment') {
draggedRec[this.parent.taskFields.parentID] = droppedRec[this.parent.taskFields.parentID];
draggedRec.taskData[this.parent.taskFields.parentID] = droppedRec[this.parent.taskFields.parentID];
draggedRec.ganttProperties['parentId'] = droppedRec[this.parent.taskFields.parentID];
} else {
draggedRec[this.parent.taskFields.parentID] = droppedRec[this.parent.taskFields.id];
draggedRec.taskData[this.parent.taskFields.parentID] = droppedRec[this.parent.taskFields.id];
draggedRec.ganttProperties['parentId'] = droppedRec[this.parent.taskFields.id];
}
} else {
draggedRec[this.parent.taskFields.parentID] = null;
draggedRec.taskData[this.parent.taskFields.parentID] = null;
draggedRec.ganttProperties['parentId'] = null;
}
}
}
private deleteDragRow(): void {
if (this.parent.dataSource instanceof DataManager) {
this.ganttData = getValue('dataOperation.dataArray', this.parent);
} else {
this.ganttData = isCountRequired(this.parent) ? getValue('result', this.parent.dataSource) :
this.parent.dataSource;
}
this.treeGridData = isCountRequired(this.parent) ?
getValue('result', this.parent.treeGrid.dataSource) : this.parent.treeGrid.dataSource;
const delRow: IGanttData = this.parent.getTaskByUniqueID(this.draggedRecord.uniqueID);
this.removeRecords(delRow);
}
private updateIndentedChildRecords(indentedRecord: IGanttData) {
let createParentItem: IParent = {
uniqueID: indentedRecord.uniqueID,
expanded: indentedRecord.expanded,
level: indentedRecord.level,
index: indentedRecord.index,
taskId: indentedRecord.ganttProperties.rowUniqueID
};
for (let i: number = 0; i < indentedRecord.childRecords.length; i++) {
this.parent.setRecordValue('parentItem', createParentItem, indentedRecord.childRecords[i]);
this.parent.setRecordValue('parentUniqueID', indentedRecord.uniqueID, indentedRecord.childRecords[i]);
}
if (indentedRecord.hasChildRecords) {
(indentedRecord as IGanttData[]) = indentedRecord.childRecords;
for (let j = 0; j < indentedRecord['length']; j++) {
this.updateIndentedChildRecords(indentedRecord[j]);
}
}
}
private dropMiddle(recordIndex1: number): void {
const obj: Gantt = this.parent;
const childRec: number = this.parent.editModule.getChildCount(this.droppedRecord, 0);
const childRecordsLength: number = (isNullOrUndefined(childRec) ||
childRec === 0) ? recordIndex1 + 1 :
childRec + recordIndex1 + 1;
if (this.dropPosition === 'middleSegment') {
if (obj.taskFields.parentID && (this.ganttData as IGanttData[]).length > 0) {
(this.ganttData as IGanttData[]).splice(childRecordsLength, 0, this.draggedRecord.taskData);
}
this.treeGridData.splice(childRecordsLength, 0, this.draggedRecord);
this.parent.ids.splice(childRecordsLength, 0, this.draggedRecord[this.parent.taskFields.id].toString());
this.recordLevel();
if (this.draggedRecord.hasChildRecords) {
this.updateChildRecord(this.draggedRecord, childRecordsLength, this.droppedRecord.expanded);
if (this.parent.enableImmutableMode) {
let indentedRecord = this.draggedRecord;
this.updateIndentedChildRecords(indentedRecord);
}
}
if (isNullOrUndefined(this.draggedRecord.parentItem &&
this.updateParentRecords.indexOf(this.draggedRecord.parentItem) !== -1)) {
this.updateParentRecords.push(this.draggedRecord.parentItem);
}
}
}
private updateChildRecordLevel(record: IGanttData, levl: number): number {
let length: number = 0;
let currentRec: IGanttData;
levl++;
if (!record.hasChildRecords) {
return 0;
}
length = record.childRecords.length;
for (let j: number = 0; j < length; j++) {
currentRec = record.childRecords[j];
let parentData: IGanttData;
if (record.parentItem) {
const id: string = 'uniqueIDCollection';
parentData = this.parent.treeGrid[id][record.parentItem.uniqueID];
}
currentRec.level = record.parentItem ? parentData.level + levl : record.level + 1;
if (currentRec.hasChildRecords) {
levl--;
levl = this.updateChildRecordLevel(currentRec, levl);
}
}
return levl;
}
/* eslint-disable-next-line */
private updateChildRecord(record: IGanttData, count: number, expanded?: boolean): number {
let currentRec: IGanttData;
const obj: Gantt = this.parent;
let length: number = 0;
if (!record.hasChildRecords) {
return 0;
}
length = record.childRecords.length;
for (let i: number = 0; i < length; i++) {
currentRec = record.childRecords[i];
count++;
obj.flatData.splice(count, 0, currentRec);
this.parent.ids.splice(count, 0, currentRec.ganttProperties.rowUniqueID.toString());
if (obj.taskFields.parentID && (this.ganttData as IGanttData[]).length > 0) {
(this.ganttData as IGanttData[]).splice(count, 0, currentRec.taskData);
}
if (currentRec.hasChildRecords) {
count = this.updateChildRecord(currentRec, count);
}
}
return count;
}
private removeRecords(record: IGanttData): void {
const obj: Gantt = this.parent;
let dataSource: Object;
if (this.parent.dataSource instanceof DataManager) {
dataSource = getValue('dataOperation.dataArray', this.parent);
} else {
dataSource = this.parent.dataSource;
}
const delRow: IGanttData = record;
const flatParent: IGanttData = this.parent.getParentTask(delRow.parentItem);
if (delRow) {
if (delRow.parentItem) {
const childRecords: IGanttData[] = flatParent ? flatParent.childRecords : [];
let childIndex: number = 0;
if (childRecords && childRecords.length > 0) {
childIndex = childRecords.indexOf(delRow);
flatParent.childRecords.splice(childIndex, 1);
if (!this.parent.taskFields.parentID) {
flatParent.taskData[this.parent.taskFields.child].splice(childIndex, 1);
}
// collection for updating parent record
this.updateParentRecords.push(flatParent);
}
}
if (obj.taskFields.parentID) {
if (delRow.hasChildRecords && delRow.childRecords.length > 0) {
this.removeChildItem(delRow);
}
let indx: number;
const ganttData: IGanttData[] = (dataSource as IGanttData[]).length > 0 ?
dataSource as IGanttData[] : this.parent.currentViewData;
for (let i: number = 0; i < ganttData.length; i++) {
if (ganttData[i][this.parent.taskFields.id] === delRow.taskData[this.parent.taskFields.id]) {
indx = i;
}
}
if (indx !== -1) {
if ((dataSource as IGanttData[]).length > 0) {
(dataSource as IGanttData[]).splice(indx, 1);
}
let gridIndx: number;
for (let i: number = 0; i < this.treeGridData.length; i++) {
if (this.treeGridData[i][this.parent.taskFields.id] === delRow.taskData[this.parent.taskFields.id]) {
gridIndx = i;
}
}
this.treeGridData.splice(gridIndx, 1);
this.parent.ids.splice(gridIndx, 1);
if (this.parent.treeGrid.parentData.indexOf(delRow) !== -1) {
this.parent.treeGrid.parentData.splice(this.parent.treeGrid.parentData.indexOf(delRow), 1);
}
}
}
const recordIdx: number = this.treeGridData.indexOf(delRow);
if (!obj.taskFields.parentID) {
const deletedRecordCount: number = this.getChildCount(delRow, 0);
this.treeGridData.splice(recordIdx, deletedRecordCount + 1);
this.parent.ids.splice(recordIdx, deletedRecordCount + 1);
const parentIndex: number = (this.ganttData as IGanttData[]).indexOf(delRow.taskData);
if (parentIndex !== -1) {
(this.ganttData as IGanttData[]).splice(parentIndex, 1);
this.parent.treeGrid.parentData.splice(parentIndex, 1);
}
}
if (delRow.parentItem && flatParent && flatParent.childRecords && !flatParent.childRecords.length) {
this.parent.setRecordValue('expanded', false, flatParent);
this.parent.setRecordValue('hasChildRecords', false, flatParent);
}
}
}
private removeChildItem(record: IGanttData): void {
let currentRec: IGanttData;
let indx: number;
for (let i: number = 0; i < record.childRecords.length; i++) {
currentRec = record.childRecords[i];
let data: Object;
if (this.parent.dataSource instanceof DataManager) {
data = getValue('dataOperation.dataArray', this.parent);
} else {
data = this.parent.dataSource;
}
for (let j: number = 0; j < (<IGanttData[]>data).length; j++) {
if (data[j][this.parent.taskFields.id] === currentRec.taskData[this.parent.taskFields.id]) {
indx = j;
}
}
if (indx !== -1) {
if ((data as IGanttData[]).length > 0) {
(data as IGanttData[]).splice(indx, 1);
}
let gridIndx: number;
for (let i: number = 0; i < this.treeGridData.length; i++) {
if (this.treeGridData[i][this.parent.taskFields.id] === currentRec.taskData[this.parent.taskFields.id]) {
gridIndx = i;
}
}
this.treeGridData.splice(gridIndx, 1);
this.parent.ids.splice(gridIndx, 1);
}
if (currentRec.hasChildRecords) {
this.removeChildItem(currentRec);
}
}
}
private recordLevel(): void {
const obj: Gantt = this.parent;
const draggedRec: IGanttData = this.draggedRecord;
const droppedRec: IGanttData = this.droppedRecord;
const childItem: string = obj.taskFields.child;
if (!droppedRec.hasChildRecords) {
droppedRec.hasChildRecords = true;
if (!droppedRec.childRecords.length) {
droppedRec.childRecords = [];
if (!obj.taskFields.parentID && isNullOrUndefined(droppedRec.taskData[childItem])) {
droppedRec.taskData[childItem] = [];
}
}
}
if (this.dropPosition === 'middleSegment') {
const parentItem: IGanttData = extend({}, droppedRec);
delete parentItem.childRecords;
const createParentItem: IParent = {
uniqueID: parentItem.uniqueID,
expanded: parentItem.expanded,
level: parentItem.level,
index: parentItem.index,
taskId: parentItem.ganttProperties.rowUniqueID
};
this.parent.setRecordValue('parentItem', createParentItem, draggedRec);
this.parent.setRecordValue('parentUniqueID', droppedRec.uniqueID, draggedRec);
droppedRec.childRecords.splice(droppedRec.childRecords.length, 0, draggedRec);
if (!isNullOrUndefined(draggedRec) && !obj.taskFields.parentID && !isNullOrUndefined(droppedRec.taskData[childItem])) {
droppedRec.taskData[obj.taskFields.child].splice(droppedRec.childRecords.length, 0, draggedRec.taskData);
}
if (!isNullOrUndefined(droppedRec.ganttProperties.segments) && droppedRec.ganttProperties.segments.length > 0) {
droppedRec.ganttProperties.segments = null;
droppedRec.taskData[obj.taskFields.segments] = null;
}
if (!draggedRec.hasChildRecords) {
draggedRec.level = droppedRec.level + 1;
} else {
const level: number = 1;
draggedRec.level = droppedRec.level + 1;
this.updateChildRecordLevel(draggedRec, level);
}
droppedRec.expanded = true;
}
}
} | the_stack |
import uuid from "uuid/v4";
import { ChangeFeedIterator } from "../../ChangeFeedIterator";
import { ChangeFeedOptions } from "../../ChangeFeedOptions";
import { ClientContext } from "../../ClientContext";
import { getIdFromLink, getPathFromLink, isResourceValid, ResourceType } from "../../common";
import { extractPartitionKey } from "../../extractPartitionKey";
import { FetchFunctionCallback, SqlQuerySpec } from "../../queryExecutionContext";
import { QueryIterator } from "../../queryIterator";
import { FeedOptions, RequestOptions } from "../../request";
import { Container } from "../Container";
import { Item } from "./Item";
import { ItemDefinition } from "./ItemDefinition";
import { ItemResponse } from "./ItemResponse";
/**
* @ignore
* @param options
*/
function isChangeFeedOptions(options: unknown): options is ChangeFeedOptions {
const optionsType = typeof options;
return options && !(optionsType === "string" || optionsType === "boolean" || optionsType === "number");
}
/**
* Operations for creating new items, and reading/querying all items
*
* @see {@link Item} for reading, replacing, or deleting an existing container; use `.item(id)`.
*/
export class Items {
/**
* Create an instance of {@link Items} linked to the parent {@link Container}.
* @param container The parent container.
* @hidden
*/
constructor(public readonly container: Container, private readonly clientContext: ClientContext) {}
/**
* Queries all items.
* @param query Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const querySpec: SqlQuerySpec = {
* query: "SELECT * FROM Families f WHERE f.lastName = @lastName",
* parameters: [
* {name: "@lastName", value: "Hendricks"}
* ]
* };
* const {result: items} = await items.query(querySpec).fetchAll();
* ```
*/
public query(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>;
/**
* Queries all items.
* @param query Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const querySpec: SqlQuerySpec = {
* query: "SELECT firstname FROM Families f WHERE f.lastName = @lastName",
* parameters: [
* {name: "@lastName", value: "Hendricks"}
* ]
* };
* const {result: items} = await items.query<{firstName: string}>(querySpec).fetchAll();
* ```
*/
public query<T>(query: string | SqlQuerySpec, options: FeedOptions): QueryIterator<T>;
public query<T>(query: string | SqlQuerySpec, options: FeedOptions = {}): QueryIterator<T> {
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
const fetchFunction: FetchFunctionCallback = (innerOptions: FeedOptions) => {
return this.clientContext.queryFeed({
path,
resourceType: ResourceType.item,
resourceId: id,
resultFn: result => (result ? result.Documents : []),
query,
options: innerOptions
});
};
return new QueryIterator(this.clientContext, query, options, fetchFunction, this.container.url, ResourceType.item);
}
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param partitionKey
* @param changeFeedOptions
*
* @example Read from the beginning of the change feed.
* ```javascript
* const iterator = items.readChangeFeed({ startFromBeginning: true });
* const firstPage = await iterator.fetchNext();
* const firstPageResults = firstPage.result
* const secondPage = await iterator.fetchNext();
* ```
*/
public readChangeFeed(
partitionKey: string | number | boolean,
changeFeedOptions: ChangeFeedOptions
): ChangeFeedIterator<any>;
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param changeFeedOptions
*/
public readChangeFeed(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>;
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param partitionKey
* @param changeFeedOptions
*/
public readChangeFeed<T>(
partitionKey: string | number | boolean,
changeFeedOptions: ChangeFeedOptions
): ChangeFeedIterator<T>;
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param changeFeedOptions
*/
public readChangeFeed<T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;
public readChangeFeed<T>(
partitionKeyOrChangeFeedOptions?: string | number | boolean | ChangeFeedOptions,
changeFeedOptions?: ChangeFeedOptions
): ChangeFeedIterator<T> {
let partitionKey: string | number | boolean;
if (!changeFeedOptions && isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {
partitionKey = undefined;
changeFeedOptions = partitionKeyOrChangeFeedOptions;
} else if (partitionKeyOrChangeFeedOptions !== undefined && !isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {
partitionKey = partitionKeyOrChangeFeedOptions;
}
if (!changeFeedOptions) {
throw new Error("changeFeedOptions must be a valid object");
}
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
return new ChangeFeedIterator<T>(this.clientContext, id, path, partitionKey, changeFeedOptions);
}
/**
* Read all items.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const {body: containerList} = await items.readAll().fetchAll();
* ```
*/
public readAll(options?: FeedOptions): QueryIterator<ItemDefinition>;
/**
* Read all items.
*
* Any provided type, T, is not necessarily enforced by the SDK.
* You may get more or less properties and it's up to your logic to enforce it.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const {body: containerList} = await items.readAll().fetchAll();
* ```
*/
public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T>;
public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T> {
return this.query<T>("SELECT * from c", options);
}
/**
* Create a item.
*
* Any provided type, T, is not necessarily enforced by the SDK.
* You may get more or less properties and it's up to your logic to enforce it.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param body Represents the body of the item. Can contain any number of user defined properties.
* @param options Used for modifying the request (for instance, specifying the partition key).
*/
public async create<T extends ItemDefinition = any>(body: T, options: RequestOptions = {}): Promise<ItemResponse<T>> {
const { resource: partitionKeyDefinition } = await this.container.getPartitionKeyDefinition();
const partitionKey = extractPartitionKey(body, partitionKeyDefinition);
// Generate random document id if the id is missing in the payload and
// options.disableAutomaticIdGeneration != true
if ((body.id === undefined || body.id === "") && !options.disableAutomaticIdGeneration) {
body.id = uuid();
}
const err = {};
if (!isResourceValid(body, err)) {
throw err;
}
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
const response = await this.clientContext.create<T>({
body,
path,
resourceType: ResourceType.item,
resourceId: id,
options,
partitionKey
});
const ref = new Item(this.container, (response.result as any).id, partitionKey, this.clientContext);
return new ItemResponse(response.result, response.headers, response.code, response.substatus, ref);
}
/**
* Upsert an item.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param body Represents the body of the item. Can contain any number of user defined properties.
* @param options Used for modifying the request (for instance, specifying the partition key).
*/
public async upsert(body: any, options?: RequestOptions): Promise<ItemResponse<ItemDefinition>>;
/**
* Upsert an item.
*
* Any provided type, T, is not necessarily enforced by the SDK.
* You may get more or less properties and it's up to your logic to enforce it.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param body Represents the body of the item. Can contain any number of user defined properties.
* @param options Used for modifying the request (for instance, specifying the partition key).
*/
public async upsert<T extends ItemDefinition>(body: T, options?: RequestOptions): Promise<ItemResponse<T>>;
public async upsert<T extends ItemDefinition>(body: T, options: RequestOptions = {}): Promise<ItemResponse<T>> {
const { resource: partitionKeyDefinition } = await this.container.getPartitionKeyDefinition();
const partitionKey = extractPartitionKey(body, partitionKeyDefinition);
// Generate random document id if the id is missing in the payload and
// options.disableAutomaticIdGeneration != true
if ((body.id === undefined || body.id === "") && !options.disableAutomaticIdGeneration) {
body.id = uuid();
}
const err = {};
if (!isResourceValid(body, err)) {
throw err;
}
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
const response = await this.clientContext.upsert<T>({
body,
path,
resourceType: ResourceType.item,
resourceId: id,
options,
partitionKey
});
const ref = new Item(this.container, (response.result as any).id, partitionKey, this.clientContext);
return new ItemResponse(response.result, response.headers, response.code, response.substatus, ref);
}
} | the_stack |
import {Align, AxisOrient, Orient, SignalRef} from 'vega';
import {isArray, isObject} from 'vega-util';
import {AxisInternal} from '../../axis';
import {isBinned, isBinning} from '../../bin';
import {PositionScaleChannel, X} from '../../channel';
import {
DatumDef,
isDiscrete,
isFieldDef,
PositionDatumDef,
PositionFieldDef,
toFieldDefBase,
TypedFieldDef,
valueArray
} from '../../channeldef';
import {Config, StyleConfigIndex} from '../../config';
import {Mark} from '../../mark';
import {hasDiscreteDomain} from '../../scale';
import {Sort} from '../../sort';
import {normalizeTimeUnit} from '../../timeunit';
import {NOMINAL, ORDINAL, Type} from '../../type';
import {contains, normalizeAngle} from '../../util';
import {isSignalRef} from '../../vega.schema';
import {mergeTitle, mergeTitleFieldDefs} from '../common';
import {guideFormat, guideFormatType} from '../format';
import {UnitModel} from '../unit';
import {ScaleType} from './../../scale';
import {AxisComponentProps} from './component';
import {AxisConfigs, getAxisConfig} from './config';
export interface AxisRuleParams {
fieldOrDatumDef: PositionFieldDef<string> | PositionDatumDef<string>;
axis: AxisInternal;
channel: PositionScaleChannel;
model: UnitModel;
mark: Mark;
scaleType: ScaleType;
orient: Orient | SignalRef;
labelAngle: number | SignalRef;
config: Config;
}
export const axisRules: {
[k in keyof AxisComponentProps]?: (params: AxisRuleParams) => AxisComponentProps[k];
} = {
scale: ({model, channel}) => model.scaleName(channel),
format: ({fieldOrDatumDef, config, axis}) => {
const {format, formatType} = axis;
return guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format, formatType, config, true);
},
formatType: ({axis, fieldOrDatumDef, scaleType}) => {
const {formatType} = axis;
return guideFormatType(formatType, fieldOrDatumDef, scaleType);
},
grid: ({fieldOrDatumDef, axis, scaleType}) => axis.grid ?? defaultGrid(scaleType, fieldOrDatumDef),
gridScale: ({model, channel}) => gridScale(model, channel),
labelAlign: ({axis, labelAngle, orient, channel}) =>
axis.labelAlign || defaultLabelAlign(labelAngle, orient, channel),
labelAngle: ({labelAngle}) => labelAngle, // we already calculate this in parse
labelBaseline: ({axis, labelAngle, orient, channel}) =>
axis.labelBaseline || defaultLabelBaseline(labelAngle, orient, channel),
labelFlush: ({axis, fieldOrDatumDef, channel}) => axis.labelFlush ?? defaultLabelFlush(fieldOrDatumDef.type, channel),
labelOverlap: ({axis, fieldOrDatumDef, scaleType}) =>
axis.labelOverlap ??
defaultLabelOverlap(
fieldOrDatumDef.type,
scaleType,
isFieldDef(fieldOrDatumDef) && !!fieldOrDatumDef.timeUnit,
isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined
),
// we already calculate orient in parse
orient: ({orient}) => orient as AxisOrient, // Need to cast until Vega supports signal
tickCount: ({channel, model, axis, fieldOrDatumDef, scaleType}) => {
const sizeType = channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;
const size = sizeType ? model.getSizeSignalRef(sizeType) : undefined;
return axis.tickCount ?? defaultTickCount({fieldOrDatumDef, scaleType, size, values: axis.values});
},
title: ({axis, model, channel}) => {
if (axis.title !== undefined) {
return axis.title;
}
const fieldDefTitle = getFieldDefTitle(model, channel);
if (fieldDefTitle !== undefined) {
return fieldDefTitle;
}
const fieldDef = model.typedFieldDef(channel);
const channel2 = channel === 'x' ? 'x2' : 'y2';
const fieldDef2 = model.fieldDef(channel2);
// If title not specified, store base parts of fieldDef (and fieldDef2 if exists)
return mergeTitleFieldDefs(
fieldDef ? [toFieldDefBase(fieldDef)] : [],
isFieldDef(fieldDef2) ? [toFieldDefBase(fieldDef2)] : []
);
},
values: ({axis, fieldOrDatumDef}) => values(axis, fieldOrDatumDef),
zindex: ({axis, fieldOrDatumDef, mark}) => axis.zindex ?? defaultZindex(mark, fieldOrDatumDef)
};
// TODO: we need to refactor this method after we take care of config refactoring
/**
* Default rules for whether to show a grid should be shown for a channel.
* If `grid` is unspecified, the default value is `true` for ordinal scales that are not binned
*/
export function defaultGrid(scaleType: ScaleType, fieldDef: TypedFieldDef<string> | DatumDef) {
return !hasDiscreteDomain(scaleType) && isFieldDef(fieldDef) && !isBinning(fieldDef?.bin) && !isBinned(fieldDef?.bin);
}
export function gridScale(model: UnitModel, channel: PositionScaleChannel) {
const gridChannel: PositionScaleChannel = channel === 'x' ? 'y' : 'x';
if (model.getScaleComponent(gridChannel)) {
return model.scaleName(gridChannel);
}
return undefined;
}
export function getLabelAngle(
fieldOrDatumDef: PositionFieldDef<string> | PositionDatumDef<string>,
axis: AxisInternal,
channel: PositionScaleChannel,
styleConfig: StyleConfigIndex<SignalRef>,
axisConfigs?: AxisConfigs
) {
const labelAngle = axis?.labelAngle;
// try axis value
if (labelAngle !== undefined) {
return isSignalRef(labelAngle) ? labelAngle : normalizeAngle(labelAngle);
} else {
// try axis config value
const {configValue: angle} = getAxisConfig('labelAngle', styleConfig, axis?.style, axisConfigs);
if (angle !== undefined) {
return normalizeAngle(angle);
} else {
// get default value
if (
channel === X &&
contains([NOMINAL, ORDINAL], fieldOrDatumDef.type) &&
!(isFieldDef(fieldOrDatumDef) && fieldOrDatumDef.timeUnit)
) {
return 270;
}
// no default
return undefined;
}
}
}
export function normalizeAngleExpr(angle: SignalRef) {
return `(((${angle.signal} % 360) + 360) % 360)`;
}
export function defaultLabelBaseline(
angle: number | SignalRef,
orient: AxisOrient | SignalRef,
channel: 'x' | 'y',
alwaysIncludeMiddle?: boolean
) {
if (angle !== undefined) {
if (channel === 'x') {
if (isSignalRef(angle)) {
const a = normalizeAngleExpr(angle);
const orientIsTop = isSignalRef(orient) ? `(${orient.signal} === "top")` : orient === 'top';
return {
signal:
`(45 < ${a} && ${a} < 135) || (225 < ${a} && ${a} < 315) ? "middle" :` +
`(${a} <= 45 || 315 <= ${a}) === ${orientIsTop} ? "bottom" : "top"`
};
}
if ((45 < angle && angle < 135) || (225 < angle && angle < 315)) {
return 'middle';
}
if (isSignalRef(orient)) {
const op = angle <= 45 || 315 <= angle ? '===' : '!==';
return {signal: `${orient.signal} ${op} "top" ? "bottom" : "top"`};
}
return (angle <= 45 || 315 <= angle) === (orient === 'top') ? 'bottom' : 'top';
} else {
if (isSignalRef(angle)) {
const a = normalizeAngleExpr(angle);
const orientIsLeft = isSignalRef(orient) ? `(${orient.signal} === "left")` : orient === 'left';
const middle = alwaysIncludeMiddle ? '"middle"' : 'null';
return {
signal: `${a} <= 45 || 315 <= ${a} || (135 <= ${a} && ${a} <= 225) ? ${middle} : (45 <= ${a} && ${a} <= 135) === ${orientIsLeft} ? "top" : "bottom"`
};
}
if (angle <= 45 || 315 <= angle || (135 <= angle && angle <= 225)) {
return alwaysIncludeMiddle ? 'middle' : null;
}
if (isSignalRef(orient)) {
const op = 45 <= angle && angle <= 135 ? '===' : '!==';
return {signal: `${orient.signal} ${op} "left" ? "top" : "bottom"`};
}
return (45 <= angle && angle <= 135) === (orient === 'left') ? 'top' : 'bottom';
}
}
return undefined;
}
export function defaultLabelAlign(
angle: number | SignalRef,
orient: AxisOrient | SignalRef,
channel: 'x' | 'y'
): Align | SignalRef {
if (angle === undefined) {
return undefined;
}
const isX = channel === 'x';
const startAngle = isX ? 0 : 90;
const mainOrient = isX ? 'bottom' : 'left';
if (isSignalRef(angle)) {
const a = normalizeAngleExpr(angle);
const orientIsMain = isSignalRef(orient) ? `(${orient.signal} === "${mainOrient}")` : orient === mainOrient;
return {
signal:
`(${startAngle ? `(${a} + 90)` : a} % 180 === 0) ? ${isX ? null : '"center"'} :` +
`(${startAngle} < ${a} && ${a} < ${180 + startAngle}) === ${orientIsMain} ? "left" : "right"`
};
}
if ((angle + startAngle) % 180 === 0) {
// For bottom, use default label align so label flush still works
return isX ? null : 'center';
}
if (isSignalRef(orient)) {
const op = startAngle < angle && angle < 180 + startAngle ? '===' : '!==';
const orientIsMain = `${orient.signal} ${op} "${mainOrient}"`;
return {
signal: `${orientIsMain} ? "left" : "right"`
};
}
if ((startAngle < angle && angle < 180 + startAngle) === (orient === mainOrient)) {
return 'left';
}
return 'right';
}
export function defaultLabelFlush(type: Type, channel: PositionScaleChannel) {
if (channel === 'x' && contains(['quantitative', 'temporal'], type)) {
return true;
}
return undefined;
}
export function defaultLabelOverlap(type: Type, scaleType: ScaleType, hasTimeUnit: boolean, sort?: Sort<string>) {
// do not prevent overlap for nominal data because there is no way to infer what the missing labels are
if ((hasTimeUnit && !isObject(sort)) || (type !== 'nominal' && type !== 'ordinal')) {
if (scaleType === 'log' || scaleType === 'symlog') {
return 'greedy';
}
return true;
}
return undefined;
}
export function defaultOrient(channel: PositionScaleChannel) {
return channel === 'x' ? 'bottom' : 'left';
}
export function defaultTickCount({
fieldOrDatumDef,
scaleType,
size,
values: vals
}: {
fieldOrDatumDef: TypedFieldDef<string> | DatumDef;
scaleType: ScaleType;
size?: SignalRef;
values?: AxisInternal['values'];
}) {
if (!vals && !hasDiscreteDomain(scaleType) && scaleType !== 'log') {
if (isFieldDef(fieldOrDatumDef)) {
if (isBinning(fieldOrDatumDef.bin)) {
// for binned data, we don't want more ticks than maxbins
return {signal: `ceil(${size.signal}/10)`};
}
if (
fieldOrDatumDef.timeUnit &&
contains(['month', 'hours', 'day', 'quarter'], normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit)
) {
return undefined;
}
}
return {signal: `ceil(${size.signal}/40)`};
}
return undefined;
}
export function getFieldDefTitle(model: UnitModel, channel: 'x' | 'y') {
const channel2 = channel === 'x' ? 'x2' : 'y2';
const fieldDef = model.fieldDef(channel);
const fieldDef2 = model.fieldDef(channel2);
const title1 = fieldDef ? fieldDef.title : undefined;
const title2 = fieldDef2 ? fieldDef2.title : undefined;
if (title1 && title2) {
return mergeTitle(title1, title2);
} else if (title1) {
return title1;
} else if (title2) {
return title2;
} else if (title1 !== undefined) {
// falsy value to disable config
return title1;
} else if (title2 !== undefined) {
// falsy value to disable config
return title2;
}
return undefined;
}
export function values(axis: AxisInternal, fieldOrDatumDef: TypedFieldDef<string> | DatumDef) {
const vals = axis.values;
if (isArray(vals)) {
return valueArray(fieldOrDatumDef, vals);
} else if (isSignalRef(vals)) {
return vals;
}
return undefined;
}
export function defaultZindex(mark: Mark, fieldDef: TypedFieldDef<string> | DatumDef) {
if (mark === 'rect' && isDiscrete(fieldDef)) {
return 1;
}
return 0;
} | the_stack |
import {
AnimationClip,
AnimationMixer,
Euler,
Matrix4,
Quaternion,
QuaternionKeyframeTrack,
SkeletonHelper,
Vector2,
Vector3,
VectorKeyframeTrack
} from 'three'
interface ShortOptions {
names?: any
hip?: string
}
interface RetargetOptions {
useFirstFramePosition?: boolean
fps?: number
names?: any
hip?: string
}
interface Options {
preserveMatrix?: boolean
preservePosition?: boolean
preserveHipPosition?: boolean
useTargetMatrix?: boolean
hip?: string
names?: any
offsets?: any
}
class SkeletonUtils {
static retarget(target, source, options: Options) {
if (!options)
options = {
preserveMatrix: true,
preservePosition: true,
preserveHipPosition: false,
useTargetMatrix: false,
hip: 'hip',
names: {}
}
const pos = new Vector3(),
quat = new Quaternion(),
scale = new Vector3(),
bindBoneMatrix = new Matrix4(),
relativeMatrix = new Matrix4(),
globalMatrix = new Matrix4()
options.preserveMatrix = options.preserveMatrix !== undefined ? options.preserveMatrix : true
options.preservePosition = options.preservePosition !== undefined ? options.preservePosition : true
options.preserveHipPosition = options.preserveHipPosition !== undefined ? options.preserveHipPosition : false
options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false
options.hip = options.hip !== undefined ? options.hip : 'hip'
options.names = options.names || {}
const sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones(source),
bones = target.isObject3D ? target.skeleton.bones : this.getBones(target)
let bindBones, bone, name, boneTo, bonesPosition
// reset bones
if (target.isObject3D) {
target.skeleton.pose()
} else {
options.useTargetMatrix = true
options.preserveMatrix = false
}
if (options.preservePosition) {
bonesPosition = []
for (let i = 0; i < bones.length; i++) {
bonesPosition.push(bones[i].position.clone())
}
}
if (options.preserveMatrix) {
// reset matrix
target.updateMatrixWorld()
target.matrixWorld.identity()
// reset children matrix
for (let i = 0; i < target.children.length; ++i) {
target.children[i].updateMatrixWorld(true)
}
}
if (options.offsets) {
bindBones = []
for (let i = 0; i < bones.length; ++i) {
bone = bones[i]
name = options.names[bone.name] || bone.name
if (options.offsets && options.offsets[name]) {
bone.matrix.multiply(options.offsets[name])
bone.matrix.decompose(bone.position, bone.quaternion, bone.scale)
bone.updateMatrixWorld()
}
bindBones.push(bone.matrixWorld.clone())
}
}
for (let i = 0; i < bones.length; ++i) {
bone = bones[i]
name = options.names[bone.name] || bone.name
boneTo = this.getBoneByName(name, sourceBones)
globalMatrix.copy(bone.matrixWorld)
if (boneTo) {
boneTo.updateMatrixWorld()
if (options.useTargetMatrix) {
relativeMatrix.copy(boneTo.matrixWorld)
} else {
relativeMatrix.copy(target.matrixWorld).invert()
relativeMatrix.multiply(boneTo.matrixWorld)
}
// ignore scale to extract rotation
scale.setFromMatrixScale(relativeMatrix)
relativeMatrix.scale(scale.set(1 / scale.x, 1 / scale.y, 1 / scale.z))
// apply to global matrix
globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix))
if (target.isObject3D) {
const boneIndex = bones.indexOf(bone),
wBindMatrix = bindBones
? bindBones[boneIndex]
: bindBoneMatrix.copy(target.skeleton.boneInverses[boneIndex]).invert()
globalMatrix.multiply(wBindMatrix)
}
globalMatrix.copyPosition(relativeMatrix)
}
if (bone.parent && bone.parent.isBone) {
bone.matrix.copy(bone.parent.matrixWorld).invert()
bone.matrix.multiply(globalMatrix)
} else {
bone.matrix.copy(globalMatrix)
}
if (options.preserveHipPosition && name === options.hip) {
bone.matrix.setPosition(pos.set(0, bone.position.y, 0))
}
bone.matrix.decompose(bone.position, bone.quaternion, bone.scale)
bone.updateMatrixWorld()
}
if (options.preservePosition) {
for (let i = 0; i < bones.length; ++i) {
bone = bones[i]
name = options.names[bone.name] || bone.name
if (name !== options.hip) {
bone.position.copy(bonesPosition[i])
}
}
}
if (options.preserveMatrix) {
// restore matrix
target.updateMatrixWorld(true)
}
}
static retargetClip(target, source, clip, options: RetargetOptions = {}) {
options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false
options.fps = options.fps !== undefined ? options.fps : 30
options.names = options.names || []
if (!source.isObject3D) {
source = this.getHelperFromSkeleton(source)
}
const numFrames = Math.round(clip.duration * (options.fps / 1000) * 1000),
delta = 1 / options.fps,
convertedTracks: (VectorKeyframeTrack | QuaternionKeyframeTrack)[] = [],
mixer = new AnimationMixer(source),
bones = this.getBones(target.skeleton),
boneDatas = []
let positionOffset, bone, boneTo, boneData, name
mixer.clipAction(clip).play()
mixer.update(0)
source.updateMatrixWorld()
for (let i = 0; i < numFrames; ++i) {
const time = i * delta
this.retarget(target, source, options)
for (let j = 0; j < bones.length; ++j) {
name = options.names[bones[j].name] || bones[j].name
boneTo = this.getBoneByName(name, source.skeleton)
if (boneTo) {
bone = bones[j]
boneData = boneDatas[j] = boneDatas[j] || { bone: bone }
if (options.hip === name) {
if (!boneData.pos) {
boneData.pos = {
times: new Float32Array(numFrames),
values: new Float32Array(numFrames * 3)
}
}
if (options.useFirstFramePosition) {
if (i === 0) {
positionOffset = bone.position.clone()
}
bone.position.sub(positionOffset)
}
boneData.pos.times[i] = time
bone.position.toArray(boneData.pos.values, i * 3)
}
if (!boneData.quat) {
boneData.quat = {
times: new Float32Array(numFrames),
values: new Float32Array(numFrames * 4)
}
}
boneData.quat.times[i] = time
bone.quaternion.toArray(boneData.quat.values, i * 4)
}
}
mixer.update(delta)
source.updateMatrixWorld()
}
for (let i = 0; i < boneDatas.length; ++i) {
boneData = boneDatas[i]
if (boneData) {
if (boneData.pos) {
convertedTracks.push(
new VectorKeyframeTrack(
'.bones[' + boneData.bone.name + '].position',
boneData.pos.times,
boneData.pos.values
)
)
}
convertedTracks.push(
new QuaternionKeyframeTrack(
'.bones[' + boneData.bone.name + '].quaternion',
boneData.quat.times,
boneData.quat.values
)
)
}
}
mixer.uncacheAction(clip)
return new AnimationClip(clip.name, -1, convertedTracks)
}
static getHelperFromSkeleton(skeleton) {
const source = new SkeletonHelper(skeleton.bones[0])
;(source as any).skeleton = skeleton
return source
}
static getSkeletonOffsets(target, source, options: ShortOptions = {}) {
const targetParentPos = new Vector3(),
targetPos = new Vector3(),
sourceParentPos = new Vector3(),
sourcePos = new Vector3(),
targetDir = new Vector2(),
sourceDir = new Vector2()
options.hip = options.hip !== undefined ? options.hip : 'hip'
options.names = options.names || {}
if (!source.isObject3D) {
source = this.getHelperFromSkeleton(source)
}
const nameKeys = Object.keys(options.names),
nameValues = Object.values(options.names),
sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones(source),
bones = target.isObject3D ? target.skeleton.bones : this.getBones(target),
offsets: Matrix4[] = []
let bone, boneTo, name, i
target.skeleton.pose()
for (i = 0; i < bones.length; ++i) {
bone = bones[i]
name = options.names[bone.name] || bone.name
boneTo = this.getBoneByName(name, sourceBones)
if (boneTo && name !== options.hip) {
const boneParent = this.getNearestBone(bone.parent, nameKeys),
boneToParent = this.getNearestBone(boneTo.parent, nameValues)
boneParent.updateMatrixWorld()
boneToParent.updateMatrixWorld()
targetParentPos.setFromMatrixPosition(boneParent.matrixWorld)
targetPos.setFromMatrixPosition(bone.matrixWorld)
sourceParentPos.setFromMatrixPosition(boneToParent.matrixWorld)
sourcePos.setFromMatrixPosition(boneTo.matrixWorld)
targetDir
.subVectors(new Vector2(targetPos.x, targetPos.y), new Vector2(targetParentPos.x, targetParentPos.y))
.normalize()
sourceDir
.subVectors(new Vector2(sourcePos.x, sourcePos.y), new Vector2(sourceParentPos.x, sourceParentPos.y))
.normalize()
const laterialAngle = targetDir.angle() - sourceDir.angle()
const offset = new Matrix4().makeRotationFromEuler(new Euler(0, 0, laterialAngle))
bone.matrix.multiply(offset)
bone.matrix.decompose(bone.position, bone.quaternion, bone.scale)
bone.updateMatrixWorld()
offsets[name] = offset
}
}
return offsets
}
static renameBones(skeleton, names) {
const bones = this.getBones(skeleton)
for (let i = 0; i < bones.length; ++i) {
const bone = bones[i]
if (names[bone.name]) {
bone.name = names[bone.name]
}
}
return this
}
static getBones(skeleton) {
return Array.isArray(skeleton) ? skeleton : skeleton.bones
}
static getBoneByName(name, skeleton) {
for (let i = 0, bones = this.getBones(skeleton); i < bones.length; i++) {
if (name === bones[i].name) return bones[i]
}
}
static getNearestBone(bone, names) {
while (bone.isBone) {
if (names.indexOf(bone.name) !== -1) {
return bone
}
bone = bone.parent
}
}
static findBoneTrackData(name, tracks) {
const regexp = /\[(.*)\]\.(.*)/,
result = { name: name }
for (let i = 0; i < tracks.length; ++i) {
// 1 is track name
// 2 is track type
const trackData = regexp.exec(tracks[i].name)
if (trackData && name === trackData[1]) {
result[trackData[2]] = i
}
}
return result
}
static getEqualsBonesNames(skeleton, targetSkeleton) {
const sourceBones = this.getBones(skeleton),
targetBones = this.getBones(targetSkeleton),
bones: any = []
search: for (let i = 0; i < sourceBones.length; i++) {
const boneName = sourceBones[i].name
for (let j = 0; j < targetBones.length; j++) {
if (boneName === targetBones[j].name) {
bones.push(boneName)
continue search
}
}
}
return bones
}
static clone(source) {
const sourceLookup = new Map()
const cloneLookup = new Map()
const clone = source.clone()
parallelTraverse(source, clone, (sourceNode, clonedNode) => {
sourceLookup.set(clonedNode, sourceNode)
cloneLookup.set(sourceNode, clonedNode)
})
clone.traverse((node) => {
if (!node.isSkinnedMesh) return
const clonedMesh = node
const sourceMesh = sourceLookup.get(node)
const sourceBones = sourceMesh.skeleton.bones
clonedMesh.skeleton = sourceMesh.skeleton.clone()
clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix)
clonedMesh.skeleton.bones = sourceBones.map((bone) => {
if (!cloneLookup.has(bone)) {
console.warn(
'Bone was not cloned',
bone,
'. Common reason is that bones parent is out of clone source',
source
)
}
return cloneLookup.get(bone)
})
clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix)
})
return clone
}
}
function parallelTraverse(a, b, callback) {
callback(a, b)
for (let i = 0; i < a.children.length; i++) {
parallelTraverse(a.children[i], b.children[i], callback)
}
}
export { SkeletonUtils } | the_stack |
import {
ancestorsOf,
catchError,
classOf,
deepClone,
deepMerge,
isClass,
isFunction,
isInheritedFrom,
Metadata,
nameOf,
prototypeOf,
Store
} from "@tsed/core";
import {DI_PARAM_OPTIONS, INJECTABLE_PROP} from "../constants/constants";
import {Configuration} from "../decorators/configuration";
import {Injectable} from "../decorators/injectable";
import {Container} from "../domain/Container";
import {LocalsContainer} from "../domain/LocalsContainer";
import {Provider} from "../domain/Provider";
import {InjectionError} from "../errors/InjectionError";
import {UndefinedTokenError} from "../errors/UndefinedTokenError";
import {GlobalProviders} from "../registries/GlobalProviders";
import {createContainer} from "../utils/createContainer";
import {DIConfiguration} from "./DIConfiguration";
import {ResolvedInvokeOptions} from "../interfaces/ResolvedInvokeOptions";
import {ProviderScope} from "../domain/ProviderScope";
import {DILogger} from "../interfaces/DILogger";
import {TokenProvider} from "../interfaces/TokenProvider";
import {ProviderOpts} from "../interfaces/ProviderOpts";
import {InvokeOptions} from "../interfaces/InvokeOptions";
import {InjectableProperties, InjectablePropertyOptions, InjectablePropertyValue} from "../interfaces/InjectableProperties";
import {InjectablePropertyType} from "../domain/InjectablePropertyType";
import {InterceptorContext} from "../interfaces/InterceptorContext";
import {InterceptorMethods} from "../interfaces/InterceptorMethods";
import {runInContext} from "../utils/runInContext";
import {resolveControllers} from "../utils/resolveControllers";
/**
* This service contain all services collected by `@Service` or services declared manually with `InjectorService.factory()` or `InjectorService.service()`.
*
* ### Example:
*
* ```typescript
* import {InjectorService} from "@tsed/di";
*
* // Import the services (all services are decorated with @Service()";
* import MyService1 from "./services/service1";
* import MyService2 from "./services/service2";
* import MyService3 from "./services/service3";
*
* // When all services is imported you can load InjectorService.
* const injector = new InjectorService()
*
* await injector.load();
*
* const myService1 = injector.get<MyService1>(MyServcice1);
* ```
*/
@Injectable({
scope: ProviderScope.SINGLETON,
global: true
})
export class InjectorService extends Container {
public settings: DIConfiguration = new DIConfiguration();
public logger: DILogger = console;
public runInContext = runInContext;
private resolvedConfiguration: boolean = false;
#cache = new LocalsContainer();
constructor() {
super();
this.#cache.set(InjectorService, this);
}
get resolvers() {
return this.settings.resolvers!;
}
get scopes() {
return this.settings.scopes || {};
}
/**
* Retrieve default scope for a given provider.
* @param provider
*/
public scopeOf(provider: Provider) {
return provider.scope || this.scopes[provider.type] || ProviderScope.SINGLETON;
}
/**
* Clone a provider from GlobalProviders and the given token. forkProvider method build automatically the provider if the instance parameter ins't given.
* @param token
* @param settings
* @deprecated
*/
public forkProvider(token: TokenProvider, settings: Partial<ProviderOpts<any>> = {}): Provider {
if (!this.hasProvider(token)) {
this.addProvider(token);
}
const provider = this.getProvider(token)!;
Object.assign(provider, settings);
this.#cache.set(token, this.invoke(token));
return provider;
}
/**
* Return a list of instance build by the injector.
*/
public toArray(): any[] {
return this.#cache.toArray();
}
/**
* Get a service or factory already constructed from his symbol or class.
*
* #### Example
*
* ```typescript
* import {InjectorService} from "@tsed/di";
* import MyService from "./services";
*
* class OtherService {
* constructor(injectorService: InjectorService) {
* const myService = injectorService.get<MyService>(MyService);
* }
* }
* ```
*
* @param token The class or symbol registered in InjectorService.
* @param options
* @returns {boolean}
*/
get<T = any>(token: TokenProvider, options: any = {}): T | undefined {
const instance = this.getInstance(token);
if (instance !== undefined) {
return instance;
}
if (!this.hasProvider(token)) {
for (const resolver of this.resolvers) {
const result = resolver.get(token, options);
if (result !== undefined) {
return result;
}
}
}
}
/**
* Return all instance of the same provider type
* @param type
*/
getAll(type: string) {
return this.getProviders(type).map((provider) => {
return this.get(provider.token);
});
}
/**
* The has() method returns a boolean indicating whether an element with the specified key exists or not.
* @returns {boolean}
* @param token
*/
has(token: TokenProvider): boolean {
return this.#cache.get(token) !== undefined;
}
/**
* Invoke the class and inject all services that required by the class constructor.
*
* #### Example
*
* ```typescript
* import {InjectorService} from "@tsed/di";
* import MyService from "./services";
*
* class OtherService {
* constructor(injectorService: InjectorService) {
* const myService = injectorService.invoke<MyService>(MyService);
* }
* }
* ```
*
* @param token The injectable class to invoke. Class parameters are injected according constructor signature.
* @param locals Optional object. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
* @param options
* @returns {T} The class constructed.
*/
public invoke<T>(
token: TokenProvider,
locals: Map<TokenProvider, any> = new LocalsContainer(),
options: Partial<InvokeOptions<T>> = {}
): T {
const provider = this.ensureProvider(token);
let instance: any;
!locals.has(Configuration) && locals.set(Configuration, this.settings);
if (locals.has(token)) {
return locals.get(token);
}
if (token === DI_PARAM_OPTIONS) {
return {} as T;
}
if (!provider || options.rebuild) {
instance = this.resolve(token, locals, options);
if (this.hasProvider(token)) {
this.#cache.set(token, instance);
}
return instance;
}
switch (this.scopeOf(provider)) {
case ProviderScope.SINGLETON:
if (!this.has(token)) {
this.#cache.set(token, this.resolve(token, locals, options));
if (provider.isAsync()) {
this.#cache.get(token).then((instance: any) => {
this.#cache.set(token, instance);
});
}
}
instance = this.get<T>(token)!;
break;
case ProviderScope.REQUEST:
instance = this.resolve(token, locals, options);
locals.set(token, instance);
break;
case ProviderScope.INSTANCE:
instance = this.resolve(provider.provide, locals, options);
break;
}
return instance;
}
/**
* Build only providers which are asynchronous.
*/
async loadAsync(locals: LocalsContainer = new LocalsContainer()) {
for (const [, provider] of this) {
if (!locals.has(provider.token)) {
if (provider.isAsync()) {
await this.invoke(provider.token, locals);
}
const instance = this.#cache.get(provider.token);
if (instance !== undefined) {
locals.set(provider.token, instance);
}
}
}
return locals;
}
loadSync(locals: LocalsContainer = new LocalsContainer()) {
for (const [, provider] of this) {
if (!locals.has(provider.token) && this.scopeOf(provider) === ProviderScope.SINGLETON) {
this.invoke(provider.token, locals);
}
const instance = this.#cache.get(provider.token);
if (instance !== undefined) {
locals.set(provider.token, instance);
}
}
return locals;
}
/**
* Boostrap injector from container and resolve configuration.
*
* @param container
*/
bootstrap(container: Container = createContainer()) {
// Clone all providers in the container
this.addProviders(container);
// Resolve all configuration
this.resolveConfiguration();
return this;
}
/**
* Load injector from a given module
* @param rootModule
*/
loadModule(rootModule: TokenProvider) {
this.settings.routes = this.settings.routes.concat(resolveControllers(this.settings));
const container = createContainer();
container.delete(rootModule);
container.addProvider(rootModule, {
type: "server:module",
scope: ProviderScope.SINGLETON
});
return this.load(container);
}
/**
* Build all providers from given container (or GlobalProviders) and emit `$onInit` event.
*
* @param container
* @param rootModule
*/
async load(container: Container = createContainer(), rootModule?: TokenProvider): Promise<LocalsContainer<any>> {
this.bootstrap(container);
// build async and sync provider
let locals = await this.loadAsync();
if (rootModule) {
await this.invoke(rootModule);
}
// load sync provider
locals = this.loadSync(locals);
await locals.emit("$beforeInit");
await locals.emit("$onInit");
return locals;
}
/**
* Load all configurations registered on providers
*/
resolveConfiguration() {
if (this.resolvedConfiguration) {
return;
}
const mergedConfiguration = new Map();
super.forEach((provider) => {
if (provider.configuration && provider.type !== "server:module") {
Object.entries(provider.configuration).forEach(([key, value]) => {
if (!["resolvers", "mount", "imports"].includes(key)) {
value = mergedConfiguration.has(key) ? deepMerge(mergedConfiguration.get(key), value) : deepClone(value);
mergedConfiguration.set(key, value);
}
});
}
if (provider.resolvers) {
this.settings.resolvers = this.settings.resolvers.concat(provider.resolvers);
}
});
mergedConfiguration.forEach((value, key) => {
this.settings.set(key, deepMerge(value, this.settings.get(key)));
});
this.resolvedConfiguration = true;
}
/**
*
* @param instance
* @param locals
* @param options
*/
public bindInjectableProperties(instance: any, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions>) {
const properties: InjectableProperties = ancestorsOf(classOf(instance)).reduce((properties: any, target: any) => {
const store = Store.from(target);
return {
...properties,
...(store.get(INJECTABLE_PROP) || {})
};
}, {});
Object.values(properties).forEach((definition) => {
switch (definition.bindingType) {
case InjectablePropertyType.METHOD:
this.bindMethod(instance, definition);
break;
case InjectablePropertyType.PROPERTY:
this.bindProperty(instance, definition, locals, options);
break;
case InjectablePropertyType.CONSTANT:
this.bindConstant(instance, definition);
break;
case InjectablePropertyType.VALUE:
this.bindValue(instance, definition);
break;
case InjectablePropertyType.INTERCEPTOR:
this.bindInterceptor(instance, definition);
break;
}
});
}
/**
*
* @param instance
* @param {string} propertyKey
*/
public bindMethod(instance: any, {propertyKey}: InjectablePropertyOptions) {
const target = classOf(instance);
const originalMethod = instance[propertyKey];
const deps = Metadata.getParamTypes(prototypeOf(target), propertyKey);
instance[propertyKey] = () => {
const services = deps.map((dependency: any) => this.get(dependency));
return originalMethod.call(instance, ...services);
};
}
/**
* Create an injectable property.
*
* @param instance
* @param {string} propertyKey
* @param {any} useType
* @param resolver
* @param options
* @param locals
* @param invokeOptions
*/
public bindProperty(
instance: any,
{propertyKey, resolver, options = {}}: InjectablePropertyOptions,
locals: Map<TokenProvider, any>,
invokeOptions: Partial<InvokeOptions>
) {
let get: () => any;
get = resolver(this, locals, {...invokeOptions, options});
catchError(() =>
Object.defineProperty(instance, propertyKey, {
get
})
);
}
/**
*
* @param instance
* @param {string} propertyKey
* @param {any} useType
*/
public bindValue(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {
const descriptor = {
get: () => this.settings.get(expression) || defaultValue,
set: (value: any) => this.settings.set(expression, value),
enumerable: true,
configurable: true
};
catchError(() => Object.defineProperty(instance, propertyKey, descriptor));
}
/**
*
* @param instance
* @param {string} propertyKey
* @param {any} useType
*/
public bindConstant(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {
let bean: any;
const get = () => {
if (bean !== undefined) {
return bean;
}
const value = this.settings.get(expression, defaultValue);
bean = Object.freeze(deepClone(value));
return bean;
};
const descriptor = {
get,
enumerable: true,
configurable: true
};
catchError(() => Object.defineProperty(instance, propertyKey, descriptor));
}
/**
*
* @param instance
* @param propertyKey
* @param useType
* @param options
*/
public bindInterceptor(instance: any, {propertyKey, useType, options}: InjectablePropertyOptions) {
const target = classOf(instance);
const originalMethod = instance[propertyKey];
instance[propertyKey] = (...args: any[]) => {
const next = (err?: Error) => {
if (!err) {
return originalMethod.apply(instance, args);
}
throw err;
};
const context: InterceptorContext<any> = {
target,
propertyKey,
args,
options,
next
};
const interceptor = this.get<InterceptorMethods>(useType)!;
return interceptor.intercept!(
{
...context,
options
},
next
);
};
}
async lazyInvoke<T = any>(token: TokenProvider) {
let instance = this.getInstance(token);
if (!instance) {
instance = await this.invoke<T>(token);
if (isFunction(instance?.$onInit)) {
await instance.$onInit();
}
}
return instance;
}
/**
* Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).
* @param eventName The event name to emit at all services.
* @param args List of the parameters to give to each services.
* @returns {Promise<any[]>} A list of promises.
*/
public async emit(eventName: string, ...args: any[]) {
return this.#cache.emit(eventName, ...args);
}
/**
* @param eventName
* @param value
* @param args
*/
public alter<T = any>(eventName: string, value: any, ...args: any[]): T {
return this.#cache.alter(eventName, value, ...args);
}
/**
* @param eventName
* @param value
* @param args
*/
public async alterAsync<T = any>(eventName: string, value: any, ...args: any[]): Promise<T> {
return this.#cache.alterAsync(eventName, value, ...args);
}
async destroy() {
await this.#cache.destroy();
}
protected ensureProvider(token: TokenProvider): Provider | undefined {
if (!this.hasProvider(token) && GlobalProviders.has(token)) {
this.addProvider(token);
}
return this.getProvider(token)!;
}
protected getInstance(token: any) {
return this.#cache.get(token);
}
/**
* Invoke a class method and inject service.
*
* #### IInjectableMethod options
*
* * **target**: Optional. The class instance.
* * **methodName**: `string` Optional. The method name.
* * **designParamTypes**: `any[]` Optional. List of injectable types.
* * **locals**: `Map<Function, any>` Optional. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
*
* #### Example
*
* @param target
* @param locals
* @param options
* @private
*/
private resolve<T>(target: TokenProvider, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions<T>> = {}): Promise<T> {
const resolvedOpts = this.mapInvokeOptions(target, locals, options);
const {token, deps, construct, imports, provider} = resolvedOpts;
if (provider) {
GlobalProviders.onInvoke(provider, locals, {...resolvedOpts, injector: this});
}
let instance: any;
let currentDependency: any = false;
try {
const invokeDependency =
(parent?: any) =>
(token: any, index: number): any => {
currentDependency = {token, index, deps};
if (token !== DI_PARAM_OPTIONS) {
const options = provider?.store?.get(`${DI_PARAM_OPTIONS}:${index}`);
locals.set(DI_PARAM_OPTIONS, options || {});
}
return isInheritedFrom(token, Provider, 1) ? provider : this.invoke(token, locals, {parent});
};
// Invoke manually imported providers
imports.forEach(invokeDependency());
// Inject dependencies
const services = deps.map(invokeDependency(token));
currentDependency = false;
instance = construct(services);
} catch (error) {
InjectionError.throwInjectorError(token, currentDependency, error);
}
if (instance === undefined) {
throw new InjectionError(
token,
`Unable to create new instance from undefined value. Check your provider declaration for ${nameOf(token)}`
);
}
if (instance && isClass(classOf(instance))) {
this.bindInjectableProperties(instance, locals, options);
}
if (instance && provider.hooks) {
Object.entries(provider.hooks).forEach(([key, cb]) => {
instance[key] = (...args: any[]) => cb(instance, ...args);
});
}
return instance;
}
/**
* Create options to invoke a provider or class.
* @param token
* @param locals
* @param options
*/
private mapInvokeOptions(token: TokenProvider, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions>): ResolvedInvokeOptions {
let imports: TokenProvider[] | undefined = options.imports;
let deps: TokenProvider[] | undefined = options.deps;
let scope = options.scope;
let construct;
if (!token) {
throw new UndefinedTokenError();
}
let provider: Provider;
if (!this.hasProvider(token)) {
provider = new Provider(token);
this.resolvers.forEach((resolver) => {
const result = resolver.get(token, locals.get(DI_PARAM_OPTIONS));
if (result !== undefined) {
provider.useFactory = () => result;
}
});
} else {
provider = this.getProvider(token)!;
}
scope = scope || this.scopeOf(provider);
deps = deps || provider.deps;
imports = imports || provider.imports;
if (provider.useValue !== undefined) {
construct = () => (isFunction(provider.useValue) ? provider.useValue() : provider.useValue);
} else if (provider.useFactory) {
construct = (deps: TokenProvider[]) => provider.useFactory(...deps);
} else if (provider.useAsyncFactory) {
construct = async (deps: TokenProvider[]) => {
deps = await Promise.all(deps);
return provider.useAsyncFactory(...deps);
};
} else {
// useClass
deps = deps || Metadata.getParamTypes(provider.useClass);
construct = (deps: TokenProvider[]) => new provider.useClass(...deps);
}
return {
token,
scope: scope || Store.from(token).get("scope") || ProviderScope.SINGLETON,
deps: deps! || [],
imports: imports || [],
construct,
provider
};
}
} | the_stack |
import * as go from "../../release/go";
import * as gcs from "./GoCloudStorage";
import {Promise} from "es6-promise";
/**
* <p>Class for saving / loading GoJS <a href="https://gojs.net/latest/api/symbols/Diagram.html">Diagram</a> <a href="https://gojs.net/latest/api/symbols/Model.html">models</a>
* to / from Dropbox. As with all {@link GoCloudStorage} subclasses (with the exception of {@link GoLocalStorage}, any page using GoDropBox must be served on a web server.</p>
* <p><b>Note</b>: Any page using GoDropBox must include a script tag with a reference to the <a href="https://cdnjs.com/libraries/dropbox.js/">Dropbox JS SDK</a>.</p>
* @category Storage
*/
export class GoDropBox extends gcs.GoCloudStorage {
private _dropbox: any;
private _menuPath: string;
private _options: any;
/**
* The number of files to display in {@link ui} before loading more
*/
private static _MIN_FILES_IN_UI = 100;
/**
* @constructor
* @param {go.Diagram|go.Diagram[]} managedDiagrams An array of GoJS <a href="https://gojs.net/latest/api/symbols/Diagram.html">Diagrams</a> whose model(s) will be saved to
* / loaded from Dropbox. Can also be a single Diagram.
* @param {string} clientId The client ID of the application in use (given in Dropbox Developer's Console)
* @param {string} defaultModel String representation of the default model data for new diagrams. If this is null,
* default new diagrams will be empty. Usually a value given by calling <a href="https://gojs.net/latest/api/symbols/Model.html#toJson">.toJson()</a>
* on a GoJS Diagram's Model.
* @param {string} iconsRelativeDirectory The directory path relative to the page in which this instance of GoDropBox exists, in which
* the storage service brand icons can be found. The default value is "../goCloudStorageIcons/".
*/
constructor(managedDiagrams: go.Diagram|go.Diagram[], clientId: string, defaultModel?: string, iconsRelativeDirectory?: string) {
super(managedDiagrams, defaultModel, clientId);
if (window['Dropbox']) {
let Dropbox = window['Dropbox'];
this._dropbox = new Dropbox({clientId: clientId});
}
this.menuPath = "";
this.ui.id = "goDropBoxCustomFilepicker";
this._serviceName = "Dropbox";
this._className = "GoDropBox";
this._options = {
// Required. Called when a user selects an item in the Chooser.
success: function(files) {
alert("Here's the file link: " + files[0].link)
},
// Optional. Called when the user closes the dialog without selecting a file
// and does not include any parameters.
cancel: function() {
},
// Optional. "preview" (default) is a preview link to the document for sharing,
// "direct" is an expiring link to download the contents of the file. For more
// information about link types, see Link types below.
linkType: "direct", // or "direct"
// Optional. A value of false (default) limits selection to a single file, while
// true enables multiple file selection.
multiselect: false, // or true
// Optional. This is a list of file extensions. If specified, the user will
// only be able to select files with these extensions. You may also specify
// file types, such as "video" or "images" in the list. For more information,
// see File types below. By default, all extensions are allowed.
extensions: ['.pdf', '.doc', '.docx', '.diagram'],
// Optional. A value of false (default) limits selection to files,
// while true allows the user to select both folders and files.
// You cannot specify `linkType: "direct"` when using `folderselect: true`.
folderselect: false, // or true
};
}
/**
* Get the <a href="https://github.com/dropbox/dropbox-sdk-js">Dropbox client</a> instance associated with this instance of GoDropBox
* (via {@link clientId}). Set during {@link authorize}.
* @function.
* @return {any}
*/
get dropbox(): any { return this._dropbox }
/**
* Get / set currently open Dropnpx path in custom filepicker {@link ui}. Default value is the empty string, which corresponds to the
* currently signed in user's Drobox account's root path. Set when a user clicks on a folder in the custom ui menu by invoking anchor onclick values.
* These onclick values are set when the Dropbox directory at the current menuPath is displayed with {@link showUI}.
* @function.
* @return {string}
*/
get menuPath(): string { return this._menuPath }
set menuPath(value: string) { this._menuPath = value }
/**
* Check if there is a signed in Dropbox user who has authorized the application linked to this instance of GoDropBox (via {@link clientId}).
* If not, prompt user to sign in / authenticate their Dropbox account.
* @param {boolean} refreshToken Whether to get a new acess token (triggers a page redirect) (true) or try to find / use the
* one in the browser window URI (no redirect) (false)
* @return {Promise<boolean>} Returns a Promise that resolves with a boolean stating whether authorization was succesful (true) or failed (false)
*/
public authorize(refreshToken: boolean = false) {
const storage = this;
return new Promise(function (resolve: Function, reject: Function){
// First, check if we're explicitly being told to refresh token (redirect to login screen)
if (refreshToken) {
try {
let item: string = storage.makeSaveFile();
window.localStorage.setItem("gdb-"+storage.clientId, item);
} catch (e) {
console.error("Local storage not supported; diagrams model data will not be preserved during Dropboc authentication.")
}
let authUrl: string = storage.dropbox.getAuthenticationUrl(window.location.href);
window.location.href = authUrl;
resolve(false);
} else if (!storage.dropbox.getAccessToken()) {
// if no redirect, check if there's an db_id and access_token in the current uri
if (window.location.hash.indexOf("access_token") !== -1 && window.location.hash.indexOf('id=dbid') !== -1) {
let accessToken: string = window.location.hash.substring(window.location.hash.indexOf('=') + 1, window.location.hash.indexOf('&'));
storage.dropbox.setAccessToken(accessToken);
// load in diagrams' models from before the auth flow started (preserve old app state)
try {
let fileContents: string = window.localStorage.getItem("gdb-"+storage.clientId);
storage.loadFromFileContents(fileContents);
localStorage.removeItem("gdb-"+storage.clientId);
} catch (e) {}
resolve(true);
} else {
try {
let item: string = storage.makeSaveFile();
window.localStorage.setItem("gdb-"+storage.clientId, item);
} catch (e) {
console.error("Local storage not supported; diagrams model data will not be preserved during Dropbox authentication.")
}
// if not, redirect to get an access_token from Dropbox login screen
let authUrl: string = storage.dropbox.getAuthenticationUrl(window.location.href);
window.location.href = authUrl;
resolve(false);
}
}
resolve(true);
});
return new Promise(function(resolve,reject){
resolve(true);
});
}
public testAuth() {
let xhr: XMLHttpRequest = new XMLHttpRequest();
let link: string = "https://www.dropbox.com/oauth2/authorize";
xhr.open('GET', link, true);
xhr.setRequestHeader('response_type', 'code');
xhr.setRequestHeader('client_id', this.clientId);
xhr.onload = function () {
if (xhr.readyState == 4 && (xhr.status == 200)) {
console.log(xhr.response);
} else {
throw Error(xhr.response); // failed to load
}
} // end xhr onload
xhr.send();
}
/**
* Get information about the currently logged in Dropbox user. Some properties of particular note include:
* <ul>
* <li>country</li>
* <li>email</li>
* <li>account_id</li>
* <li>name</li>
* <ul>
* <li>abbreivated_name</li>
* <li>display_name</li>
* <li>given_name</li>
* <li>surname</li>
* </ul>
* </ul>
* @return {Promise} Returns a Promise that resolves with information about the currently logged in Dropbox user
*/
public getUserInfo() {
const storage = this;
return new Promise(function (resolve, reject) {
// Case: No access token in URI
if (!storage.dropbox.getAccessToken() && window.location.hash.indexOf("access_token") == -1) {
storage.authorize(true);
}
// Case: Access token in URI, but not assigned to storage.dropbox.access_token
else if (!storage.dropbox.getAccessToken() && window.location.hash.indexOf("access_token") == 1) {
storage.authorize(false);
}
storage.dropbox.usersGetCurrentAccount(null).then(function (userData) {
resolve(userData);
}).catch(function (e) {
// Case: storage.dropbox.access_token has expired or become malformed; get another access token
if (e.status == 400) {
storage.authorize(true);
}
});
});
}
/**
* Display the custom GoDropBox filepicker {@link ui}. <b>Note: </b> This is no longer used for loadWithUI actions. These actions are handled with the official Dropbox Chooser API.
* @param {string} action Clarify what action is being done after file selection. Acceptable values:
* <ul>
* <li>Save</li>
* <li>Delete</li>
* <li>Load</li>
* </ul>
* @param {string} path The path in DropBox to look to for files and folders. The empty string directs to a Dropbox user's root
* directory. Path syntax is <code>/{path}/{to}/{folder}/</code>; i.e. <code>/Public/</code>.
* @param {string} numAdditionalFiles Number of files to show in UI, in addition to a static property that can only be modified by changing source code.
* This prevents long wait times while the UI loads if there are a large number of diagram files stored in Dropbox.
* @return {Promise} Returns a Promise which resolves (in {@link save}, {@link load}, or {@link remove}, after action is handled with a
* {@link DiagramFile} representing the saved/loaded/deleted file
*
public showUI(action: string, path?: string, numAdditionalFiles?: number) {
const storage = this;
const ui = storage.ui;
if (!path) path = "";
if (!numAdditionalFiles) numAdditionalFiles = 0;
if (!storage.dropbox.getAccessToken()) {
storage.authorize(true);
}
storage.dropbox.usersGetCurrentAccount(null).then(function (userData) {
if (userData) {
ui.innerHTML = "<img class='icons' src='" + storage.iconsRelativeDirectory + "dropBox.png'></img>";
let title: string = action + " Diagram File";
ui.innerHTML += "<strong>" + title + "</strong><hr></hr>";
document.getElementsByTagName('body')[0].appendChild(ui);
ui.style.visibility = 'visible';
let filesDiv: HTMLElement = document.createElement('div');
filesDiv.id = 'fileOptions';
// get all files / folders in the directory specified by 'path'
storage.dropbox.filesListFolder({ path: path }).then(function (resp) {
let files: Object[] = resp.entries;
let path: string = files[0]['path_lower'].split("/");
let parentDirectory: string; let currentDirectory: string;
if (path.length > 2) {
for (let i = 0; i < path.length - 1; i++) {
if (i === 0) {
parentDirectory = '';
currentDirectory = '';
}
else if (i < path.length - 2) {
parentDirectory += "/" + path[i];
currentDirectory += "/" + path[i];
} else currentDirectory += "/" + path[i];
}
}
storage.menuPath = (currentDirectory === undefined) ? '' : currentDirectory;
let currentDirectoryDisplay: string = (currentDirectory === undefined) ? "Root" : currentDirectory;
if (!document.getElementById('currentDirectory')) ui.innerHTML += "<span id='currentDirectory'>Current Directory: " + currentDirectoryDisplay + "</span>";
let numFilesToDisplay: number = GoDropBox._MIN_FILES_IN_UI + numAdditionalFiles;
let numFilesChecked: number = 0;
let numFilesDisplayed: number = 0;
let numFoldersDisplayed: number = 0;
let hasDisplayedAllElements: boolean = false;
for (let i = 0; i < files.length; i++) {
let file: Object = files[i];
// display all folders in this directory
if (file[".tag"] == "folder") {
numFoldersDisplayed++;
if (numFilesChecked + numFoldersDisplayed >= files.length) hasDisplayedAllElements = true;
let folderOption = document.createElement('div');
folderOption.className = 'folderOption';
let folder = document.createElement('a');
folder.href = "#";
folder.textContent = file['name'];
folder.id = file['id'];
folder.onclick = function () {
storage.showUI(action, file['path_lower'], 0);
}
folderOption.appendChild(folder);
filesDiv.appendChild(folderOption);
}
// limit how many files to display
else if (numFilesDisplayed < numFilesToDisplay) {
numFilesChecked++;
if (numFilesChecked + numFoldersDisplayed >= files.length) hasDisplayedAllElements = true;
if (file['name'].indexOf(".diagram") !== -1) {
numFilesDisplayed++;
if (action !== "Save" ) {
let fileOption = document.createElement('div');
fileOption.className = 'fileOption';
let fileRadio = document.createElement('input');
fileRadio.id = file['id'];
fileRadio.type = 'radio';
fileRadio.name = 'dropBoxFile';
fileRadio.setAttribute('data', file['path_lower']);
let fileLabel: HTMLLabelElement = document.createElement('label');
fileLabel.id = file['id'] + '-label';
fileLabel.textContent = file['name'];
fileOption.appendChild(fileRadio);
fileOption.appendChild(fileLabel);
filesDiv.appendChild(fileOption);
} else {
// no need to make diagram files selectable during save as actions
let fileOption = document.createElement('div');
fileOption.className = 'fileOption';
let fileLabel: HTMLLabelElement = document.createElement('label');
fileLabel.id = file['id'] + '-label';
fileLabel.textContent = file['name'];
fileOption.appendChild(fileLabel);
filesDiv.appendChild(fileOption);
}
}
}
}
// If there may be more diagram files to show, say so and provide user with option to try loading more in the UI
if (!hasDisplayedAllElements) {
let num: number = numAdditionalFiles + 50;
filesDiv.innerHTML += "<p>Observed " + (GoDropBox._MIN_FILES_IN_UI + numAdditionalFiles) + " files. There may be more diagram files not shown. " +
"<a id='dropBoxLoadMoreFiles'>Click here</a> to search for more.</p>";
document.getElementById('dropBoxLoadMoreFiles').onclick = function () {
storage.showUI(action, storage.menuPath, num);
}
}
// include a link to return to the parent directory
if (parentDirectory !== undefined) {
let parentDirectoryDisplay: string;
if (!parentDirectory) parentDirectoryDisplay = "root";
else parentDirectoryDisplay = parentDirectory;
let parentDiv: HTMLDivElement = document.createElement('div');
let parentAnchor: HTMLAnchorElement = document.createElement('a');
parentAnchor.id = 'dropBoxReturnToParentDir';
parentAnchor.text = "Back to " + parentDirectoryDisplay;
parentAnchor.onclick = function () {
storage.showUI(action, parentDirectory, 0);
}
parentDiv.appendChild(parentAnchor);
filesDiv.appendChild(parentDiv);
}
if (!document.getElementById(filesDiv.id)) ui.appendChild(filesDiv);
// italicize currently open file, if a file is currently open
if (storage.currentDiagramFile.id) {
var currentFileElement = document.getElementById(storage.currentDiagramFile.id + '-label');
if (currentFileElement) {
currentFileElement.style.fontStyle = "italic";
}
}
// user input div (only for save)
if (action === 'Save' && !document.getElementById('userInputDiv')) {
let userInputDiv: HTMLElement = document.createElement('div');
userInputDiv.id = 'userInputDiv';
userInputDiv.innerHTML = '<span>Save Diagram As </span><input id="userInput" placeholder="Enter filename"></input>';
ui.appendChild(userInputDiv);
}
// user data div
if (!document.getElementById('userDataDiv')) {
let userDataDiv: HTMLElement = document.createElement('div');
userDataDiv.id = 'userDataDiv';
let userDataSpan: HTMLSpanElement = document.createElement('span');
userDataSpan.textContent = userData.name.display_name + ', ' + userData.email;
userDataDiv.appendChild(userDataSpan);
let changeAccountAnchor: HTMLAnchorElement = document.createElement('a');
changeAccountAnchor.href = "#";
changeAccountAnchor.id = "dropBoxChangeAccount";
changeAccountAnchor.textContent = "Change Account";
changeAccountAnchor.onclick = function () {
storage.authorize(true); // from the authorization page, a user can sign in under a different DropBox account
}
userDataDiv.appendChild(changeAccountAnchor);
ui.appendChild(userDataDiv);
}
if (!document.getElementById('submitDiv') && !document.getElementById('cancelDiv')) {
// buttons
let submitDiv: HTMLElement = document.createElement('div');
submitDiv.id = "submitDiv";
let actionButton = document.createElement('button');
actionButton.id = 'actionButton';
actionButton.textContent = action;
actionButton.onclick = function () {
storage.processUIResult(action);
}
submitDiv.appendChild(actionButton);
ui.appendChild(submitDiv);
let cancelDiv: HTMLElement = document.createElement('div');
cancelDiv.id = 'cancelDiv';
let cancelButton = document.createElement('button');
cancelButton.textContent = "Cancel";
cancelButton.id = 'cancelButton';
cancelButton.onclick = function () {
storage.hideUI(true);
}
cancelDiv.appendChild(cancelButton);
ui.appendChild(cancelDiv);
}
});
}
}).catch(function (e) {
// Bad request: Access token is either expired or malformed. Get another one.
if (e.status == 400) {
storage.authorize(true);
}
});
return storage._deferredPromise.promise; // will not resolve until action (save, load, delete) completes
}*/
public showUI() {
const storage = this;
const ui = storage.ui;
ui.innerHTML = ''; // clear div
ui.style.visibility = 'visible';
ui.innerHTML = "<img class='icons' src='" + storage.iconsRelativeDirectory + "dropBox.png'></img><strong>Save Diagram As</strong><hr></hr>";
// user input div
let userInputDiv: HTMLElement = document.createElement('div');
userInputDiv.id = 'userInputDiv';
userInputDiv.innerHTML += '<input id="gdb-userInput" placeholder="Enter filename"></input>';
ui.appendChild(userInputDiv);
let submitDiv: HTMLElement = document.createElement('div');
submitDiv.id = "submitDiv";
let actionButton = document.createElement("button");
actionButton.id = "actionButton";
actionButton.textContent = "Save";
actionButton.onclick = function () {
let input: HTMLInputElement = <HTMLInputElement>(document.getElementById("gdb-userInput"));
let val: string = input.value;
if (val != "" && val != undefined && val != null) {
ui.style.visibility = 'hidden';
storage.saveWithUI(val);
}
}
submitDiv.appendChild(actionButton);
ui.appendChild(submitDiv);
let cancelDiv: HTMLElement = document.createElement('div');
cancelDiv.id = "cancelDiv";
let cancelButton = document.createElement("button");
cancelButton.id = "cancelButton";
cancelButton.textContent = "Cancel";
cancelButton.onclick = function () {
storage.hideUI(true);
}
cancelDiv.appendChild(cancelButton);
ui.appendChild(cancelDiv);
return storage._deferredPromise.promise;
}
/**
* Hide the custom GoDropBox filepicker {@link ui}; nullify {@link menuPath}.
* @param {boolean} isActionCanceled If action (Save, Delete, Load) is cancelled, resolve the Promise returned in {@link showUI} with a 'Canceled' notification.
*/
public hideUI(isActionCanceled?: boolean) {
const storage = this;
storage.menuPath = "";
super.hideUI(isActionCanceled);
}
/**
* @private
* @hidden
* Process the result of pressing the action (Save, Delete, Load) button on the custom GoDropBox filepicker {@link ui}.
* @param {string} action The action that must be done. Acceptable values:
* <ul>
* <li>Save</li>
* <li>Delete</li>
* <li>Load</li>
* </ul>
*/
public processUIResult(action: string) {
const storage = this;
/**
* Get the selected file (in menu's) Dropbox filepath
* @return {string} The selected file's Dropbox filepath
*/
function getSelectedFilepath() {
const radios = document.getElementsByName('dropBoxFile');
let selectedFile = null;
for (let i = 0; i < radios.length; i++) {
if ((<HTMLInputElement>radios[i]).checked) {
selectedFile = radios[i].getAttribute("data");
}
}
return selectedFile;
}
let filePath: string = getSelectedFilepath();
switch (action) {
case 'Save': {
if (storage.menuPath || storage.menuPath === '') {
let name: string = (<HTMLInputElement>document.getElementById('userInput')).value;
if (name) {
if (name.indexOf('.diagram') === -1) name += '.diagram';
storage.save(storage.menuPath + '/' + name);
} else {
// handle bad save name
console.log('Proposed file name is not valid'); // placeholder handler
}
}
break;
}
case 'Load': {
storage.load(filePath);
break;
}
case 'Delete': {
storage.remove(filePath);
break;
}
}
storage.hideUI();
}
/**
* Check whether a file exists in user's Dropbox at a given path.
* @param {string} path A valid Dropbox filepath. Path syntax is <code>/{path-to-file}/{filename}</code>; i.e. <code>/Public/example.diagram</code>.
* Alternatively, this may be a valid Dropbox file ID.
* @return {Promise} Returns a Promise that resolves with a boolean stating whether a file exists in user's Dropbox at a given path
*/
public checkFileExists(path: string) {
const storage = this;
if (path.indexOf('.diagram') === -1) path += '.diagram';
return new Promise(function(resolve: Function, reject: Function){
storage.dropbox.filesGetMetadata({ path: path }).then(function (resp) {
if (resp) resolve(true);
}).catch(function (err) {
resolve(false);
});
});
}
/**
* Get the Dropbox file reference object at a given path. Properties of particular note include:
* <ul>
* <li>name: The name of the file in DropBox</li>
* <li>id: The DropBox-given file ID<li>
* <li>path_diplay: A lower-case version of the path this file is stored at in DropBox</li>
* <li>.tag: A tag denoting the type of this file. Common values are "file" and "folder". </li>
* <ul>
* <b>Note:</b> The first three elements in the above list are requisite for creating valid {@link DiagramFile}s.
* @param {string} path A valid Dropbox filepath. Path syntax is <code>/{path-to-file}/{filename}</code>; i.e. <code>/Public/example.diagram</code>.
* Alternatively, this may be a valid Dropbox file ID.
* @return {Promise} Returns a Promise that resolves with a Dropbox file reference object at a given path
*/
public getFile(path: string) {
const storage = this;
if (path.indexOf('.diagram') === -1) path += '.diagram';
return storage.dropbox.filesGetMetadata({ path: path }).then(function (resp) {
if (resp) return resp;
}).catch(function (err) {
return null;
});
}
/**
* Save the current {@link managedDiagrams} model data to Dropbox with the filepicker {@link ui}. Returns a Promise that resolves with a
* {@link DiagramFile} representing the saved file.
* @param {string} filename Optional: The name to save data to Dropbox under. If this is not provided, you will be prompted for a filename
* @return {Promise}
*/
public saveWithUI(filename?: string) {
const storage = this;
if (filename == undefined || filename == null) {
//let filename: string = prompt("GIMME A NAME");
//storage.saveWithUI(filename);
return new Promise(function(resolve, reject){
resolve(storage.showUI());
});
} else {
if (filename.length < 8) {
filename += ".diagram";
} else {
let lastEight: string = filename.substring(filename.length-8, filename.length);
if (lastEight != ".diagram") {
filename += ".diagram";
}
}
return new Promise(function(resolve, reject) {
storage._options.success = function(resp) {
var a = 3;
// find the file that was just saved
// look at all files with "filename" in title
// find most recent of those
let savedFile: any = null;
storage.dropbox.filesListFolder({
path: "",
recursive: true
}).then(function(r){
var files = r.entries;
var possibleFiles = [];
/*for (let i in files) {
var file = files[i];
//var fname = filename.replace(/.diagram([^_]*)$/,'$1');
//console.log(fname);
if (file.filename.indexOf(fname) != -1 && file.filename.indexOf(".diagram") != -1) {
possibleFiles.push(file);
}
}*/
// find most recently modified (saved)
let latestestDate: Date = new Date(-8400000);
var latestFile = null;
//for (let i in files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
let dateModified = new Date(file.server_modified);
if (dateModified != null && dateModified != undefined && dateModified instanceof Date) {
if (dateModified > latestestDate) {
dateModified = latestestDate;
latestFile = file;
}
}
}
// resolve Promises
let savedFile: gcs.DiagramFile = { name: latestFile.name, path: latestFile.path_lower, id: latestFile.id };
storage.currentDiagramFile = savedFile;
resolve(savedFile);
storage._deferredPromise.promise.resolve(savedFile);
storage._deferredPromise.promise = storage.makeDeferredPromise();
});
}
function makeTextFile (text) {
var data = new Blob([text], {type: 'text/plain'});
var uri = "";
uri = window.URL.createObjectURL(data);
return uri;
}
var dataURI = "data:text/html,"+encodeURIComponent(storage.makeSaveFile());
var Dropbox = window["Dropbox"];
Dropbox.save(dataURI, filename, storage._options);
});
} // end if filename exists case
}
/**
* Save {@link managedDiagrams}' model data to Dropbox. If path is supplied save to that path. If no path is supplied but {@link currentDiagramFile} has non-null,
* valid properties, update saved diagram file content at the path in Dropbox corresponding to currentDiagramFile.path with current managedDiagrams' model data.
* If no path is supplied and currentDiagramFile is null or has null properties, this calls {@link saveWithUI}.
* @param {string} path A valid Dropbox filepath to save current diagram model to. Path syntax is <code>/{path-to-file}/{filename}</code>;
* i.e. <code>/Public/example.diagram</code>.
* Alternatively, this may be a valid Dropbox file ID.
* @return {Promise} Returns a Promise that resolves with a {@link DiagramFile} representing the saved file.
*/
public save(path?: string) {
const storage = this;
return new Promise(function (resolve, reject) {
if (path) { // save as
storage.dropbox.filesUpload({
contents: storage.makeSaveFile(),
path: path,
autorename: true, // instead of overwriting, save to a different name (i.e. test.diagram -> test(1).diagram)
mode: {'.tag': 'add'},
mute: false
}).then(function (resp) {
let savedFile: gcs.DiagramFile = { name: resp.name, id: resp.id, path: resp.path_lower };
storage.currentDiagramFile = savedFile;
resolve(savedFile); // used if saveDiagramAs was called without UI
// if saveAs has been called in processUIResult, need to resolve / reset the Deferred Promise instance variable
storage._deferredPromise.promise.resolve(savedFile);
storage._deferredPromise.promise = storage.makeDeferredPromise();
}).catch(function(e){
// Bad request: Access token is either expired or malformed. Get another one.
if (e.status == 400) {
storage.authorize(true);
}
});
} else if (storage.currentDiagramFile.path) { // save
path = storage.currentDiagramFile.path;
storage.dropbox.filesUpload({
contents: storage.makeSaveFile(),
path: path,
autorename: false,
mode: {'.tag': 'overwrite'},
mute: true
}).then(function (resp) {
let savedFile: Object = { name: resp.name, id: resp.id, path: resp.path_lower };
resolve(savedFile);
}).catch(function(e){
// Bad request: Access token is either expired or malformed. Get another one.
if (e.status == 400) {
storage.authorize(true);
}
});
} else {
resolve(storage.saveWithUI());
//throw Error("Cannot save file to Dropbox with path " + path);
}
});
}
/**
* Load the contents of a saved diagram from Dropbox using the custom filepicker {@link ui}.
* @return {Promise} Returns a Promise that resolves with a {@link DiagramFile} representing the loaded file.
*/
public loadWithUI() {
const storage = this;
storage._options.success = function(resp) {
var file = resp[0];
// get the file path
storage.dropbox.filesGetMetadata({ path: file.id }).then(function(resp){
let path: string = resp.path_display;
storage.load(path);
});
}
var Dropbox = window["Dropbox"];
Dropbox.choose(storage._options);
return storage._deferredPromise.promise; // will not resolve until action (save, load, delete) completes
}
/**
* Load the contents of a saved diagram from Dropbox.
* @param {string} path A valid Dropbox filepath to load diagram model data from. Path syntax is <code>/{path-to-file}/{filename}</code>;
* i.e. <code>/Public/example.diagram</code>.
* Alternatively, this may be a valid Dropbox file ID.
* @return {Promise} Returns a Promise that resolves with a {@link DiagramFile} representing the loaded file
*/
public load(path: string) {
const storage = this;
return new Promise(function (resolve, reject) {
if (path) {
storage.dropbox.filesGetTemporaryLink({ path: path }).then(function (resp) {
let link: string = resp.link;
storage.currentDiagramFile.name = resp.metadata.name;
storage.currentDiagramFile.id = resp.metadata.id;
storage.currentDiagramFile.path = path;
let xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.open('GET', link, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + storage.dropbox.getAccessToken());
xhr.onload = function () {
if (xhr.readyState == 4 && (xhr.status == 200)) {
storage.loadFromFileContents(xhr.response);
let loadedFile: gcs.DiagramFile = { name: resp.metadata.name, id: resp.metadata.id, path: resp.metadata.path_lower };
resolve(loadedFile); // used if loadDiagram was called without UI
// if loadDiagram has been called in processUIResult, need to resolve / reset the Deferred Promise instance variable
storage._deferredPromise.promise.resolve(loadedFile);
storage._deferredPromise.promise = storage.makeDeferredPromise();
} else {
throw Error("Cannot load file from Dropbox with path " + path); // failed to load
}
} // end xhr onload
xhr.send();
}).catch(function(e){
// Bad request: Access token is either expired or malformed. Get another one.
if (e.status == 400) {
storage.authorize(true);
}
});
} else throw Error("Cannot load file from Dropbox with path " + path);
});
}
/**
* Delete a chosen diagram file from Dropbox using the custom filepicker {@link ui}.
* @return {Promise} Returns a Promise that resolves with a {@link DiagramFile} representing the deleted file.
*/
public removeWithUI() {
const storage = this;
storage._options.success = function(resp) {
var file = resp[0];
// get the file path
storage.dropbox.filesGetMetadata({ path: file.id }).then(function(resp){
let path: string = resp.path_display;
storage.remove(path);
});
}
var Dropbox = window["Dropbox"];
Dropbox.choose(storage._options);
return storage._deferredPromise.promise; // will not resolve until action (save, load, delete) completes
}
/**
* Delete a given diagram file from Dropbox.
* @param {string} path A valid Dropbox filepath to delete diagram model data from. Path syntax is
* <code>/{path-to-file}/{filename}</code>; i.e. <code>/Public/example.diagram</code>.
* Alternatively, this may be a valid Dropbox file ID.
* @return {Promise} Returns a Promise that resolves with a {@link DiagramFile} representing the deleted file.
*/
public remove(path: string) {
const storage = this;
return new Promise(function (resolve, reject) {
if (path) {
storage.dropbox.filesDelete({ path: path }).then(function (resp) {
if (storage.currentDiagramFile && storage.currentDiagramFile['id'] === resp['id']) storage.currentDiagramFile = { name: null, path: null, id: null };
let deletedFile: gcs.DiagramFile = { name: resp.name, id: resp['id'], path: resp.path_lower };
resolve(deletedFile); // used if deleteDiagram was called without UI
// if deleteDiagram has been called in processUIResult, need to resolve / reset the Deferred Promise instance variable
storage._deferredPromise.promise.resolve(deletedFile);
storage._deferredPromise.promise = storage.makeDeferredPromise();
}).catch(function(e){
// Bad request: Access token is either expired or malformed. Get another one.
if (e.status == 400) {
storage.authorize(true);
}
});
} else throw Error('Cannot delete file from Dropbox with path ' + path);
});
}
} | the_stack |
import type Model from 'controller/model';
import type Preview from 'view/preview';
import type { FloatConfig } from 'controller/model';
import FloatingDragUI from 'view/floating/floating-drag-ui';
import { OS } from 'environment/environment';
import { deviceIsLandscape } from 'utils/dom';
import { isIframe } from 'utils/browser';
import {
addClass,
removeClass
} from 'utils/dom';
import { STATE_IDLE, STATE_COMPLETE, STATE_ERROR } from 'events/events';
import { isNumber } from 'utils/underscore';
import {
style,
} from 'utils/css';
import viewsManager from 'view/utils/views-manager';
import type { BoundingRect } from 'types/generic.type';
import { getPlayerSizeStyles } from 'view/utils/player-size';
const FLOATING_TOP_OFFSET = 62;
let _floatingPlayer: HTMLElement | null = null;
const fpContainer: {
floatingPlayer: HTMLElement | null;
} = {
floatingPlayer: _floatingPlayer
};
Object.defineProperty(fpContainer, 'floatingPlayer', {
get: () => _floatingPlayer,
set: (val) => {
if (val === _floatingPlayer) {
return;
}
_floatingPlayer = val;
const watchersToRun = watchers.slice();
watchers.length = 0;
watchersToRun.forEach(fc => {
fc.startFloating();
});
}
});
const watchers: FloatingController[] = [];
const addFPWatcher = (fc: FloatingController) => {
if (watchers.indexOf(fc) !== -1) {
return;
}
watchers.push(fc);
};
const removeFPWatcher = (fc: FloatingController) => {
const watcherIDX = watchers.indexOf(fc);
if (watcherIDX !== -1) {
watchers.splice(watcherIDX, 1);
}
};
export default class FloatingController {
_playerEl: HTMLElement;
_wrapperEl: HTMLElement;
_preview: Preview;
_model: Model;
_floatingUI: FloatingDragUI;
_mobileCheckCanFire: boolean;
_mobileDebounceTimeout?: number;
_floatingStoppedForever: boolean;
_lastIntRatio: number;
_canFloat?: boolean;
_isMobile: boolean;
_boundThrottledMobileFloatScrollHandler: Function;
_playerBounds: BoundingRect;
_boundInitFloatingBehavior: () => void;
_inTransition: boolean;
constructor(
model: Model,
playerBounds: BoundingRect,
elements: {
player: HTMLElement;
wrapper: HTMLElement;
preview: Preview;
},
isMobile: boolean = OS.mobile
) {
this._playerEl = elements.player;
this._wrapperEl = elements.wrapper;
this._preview = elements.preview;
this._model = model;
this._floatingUI = new FloatingDragUI(this._wrapperEl);
this._floatingStoppedForever = false;
this._lastIntRatio = 0;
this._playerBounds = playerBounds;
this._isMobile = isMobile;
this._mobileCheckCanFire = true;
this._inTransition = false;
this._boundThrottledMobileFloatScrollHandler = this.throttledMobileFloatScrollHandler.bind(this);
this._boundInitFloatingBehavior = this.initFloatingBehavior.bind(this);
}
setup(): void {
this._model.change('floating', this._boundInitFloatingBehavior);
}
initFloatingBehavior(): void {
// Don't reinitialize this behavior if the user dismissed the floating player
if (this._floatingStoppedForever) {
return;
}
// Setup floating scroll handler
viewsManager.removeScrollHandler(this._boundThrottledMobileFloatScrollHandler);
removeFPWatcher(this);
if (this.getFloatingConfig()) {
const fm = this.getFloatMode();
if (fm === 'notVisible') {
if (this._isMobile) {
viewsManager.addScrollHandler(this._boundThrottledMobileFloatScrollHandler);
this._boundThrottledMobileFloatScrollHandler();
} else {
this.checkFloatIntersection();
}
} else if (fm === 'always') {
this.startFloating();
} else if (fm === 'never') {
this.stopFloating();
}
}
}
updatePlayerBounds(pb: BoundingRect): void {
this._playerBounds = pb;
}
getFloatingConfig(): FloatConfig | undefined {
return this._model.get('floating');
}
getFloatMode(): string {
const fc = this.getFloatingConfig();
return (fc && fc.mode) || 'notVisible';
}
resize(): void {
if (this._model.get('isFloating')) {
this.updateFloatingSize();
}
}
fosMobileBehavior(): boolean {
return this._isMobile && !deviceIsLandscape() && !this._model.get('fullscreen');
}
shouldFloatOnViewable(): boolean {
const state = this._model.get('state');
return state !== STATE_IDLE && state !== STATE_ERROR && state !== STATE_COMPLETE;
}
startFloating(mobileFloatIntoPlace?: boolean): void {
const playerBounds = this._playerBounds;
if (this.getFloatingPlayer() === null) {
this.setFloatingPlayer(this._playerEl);
this.transitionFloating(true);
this._model.set('isFloating', true);
addClass(this._playerEl, 'jw-flag-floating');
if (mobileFloatIntoPlace) {
// Creates a dynamic animation where the top of the current player
// Smoothly transitions into the expected floating space in the event
// we can't start floating at 62px
style(this._wrapperEl, {
transform: `translateY(-${FLOATING_TOP_OFFSET - playerBounds.top}px)`
});
setTimeout(() => {
style(this._wrapperEl, {
transform: 'translateY(0)',
transition: 'transform 150ms cubic-bezier(0, 0.25, 0.25, 1)'
});
});
}
setTimeout(() => {
this.transitionFloating(false);
}, 50);
// Copy background from preview element
const previewEl = this._preview.el as HTMLElement;
style(this._playerEl, {
backgroundImage: previewEl.style.backgroundImage
});
this.updateFloatingSize();
if (!this._model.get('instreamMode')) {
this._floatingUI.enable();
}
} else if (this.getFloatingPlayer() !== this._playerEl && this.getFloatMode() === 'always') {
addFPWatcher(this);
}
}
stopFloating(forever?: boolean, mobileFloatIntoPlace?: boolean): void {
if (forever) {
this._floatingStoppedForever = true;
viewsManager.removeScrollHandler(this._boundThrottledMobileFloatScrollHandler);
}
if (this.getFloatingPlayer() !== this._playerEl) {
return;
}
this.transitionFloating(true);
this.setFloatingPlayer(null);
this._model.set('isFloating', false);
const playerBounds = this._playerBounds;
const resetFloatingStyles = () => {
removeClass(this._playerEl, 'jw-flag-floating');
this._model.trigger('forceAspectRatioChange', {});
// Wrapper should inherit from parent unless floating.
style(this._playerEl, { backgroundImage: null }); // Reset to avoid flicker.
style(this._wrapperEl, {
maxWidth: null,
width: null,
height: null,
transform: null,
transition: null,
'transition-timing-function': null
});
setTimeout(() => {
this.transitionFloating(false);
}, 50);
};
if (mobileFloatIntoPlace) {
// Reverses a dynamic animation where the top of the current player
// Smoothly transitions into the expected static space in the event
// we didn't start floating at 62px
style(this._wrapperEl, {
transform: `translateY(-${FLOATING_TOP_OFFSET - playerBounds.top}px)`,
'transition-timing-function': 'ease-out'
});
setTimeout(resetFloatingStyles, 150);
} else {
resetFloatingStyles();
}
this.disableFloatingUI();
}
transitionFloating(isTransitionIn: boolean): void {
this._inTransition = isTransitionIn;
// Hiding the wrapper will impact player viewability momentarily, but reduce CLS
// We could hide the wrappers contents (controls, overlays) and reduce some CLS, but not as much
const wrapper = this._wrapperEl;
style(wrapper, {
display: isTransitionIn ? 'none' : null
});
if (!isTransitionIn) {
// Perform resize and trigger "float" event responsively to prevent layout thrashing
this._model.trigger('forceResponsiveListener', {});
}
}
isInTransition(): boolean {
return this._inTransition;
}
updateFloatingSize(): void {
const playerBounds = this._playerBounds;
// Always use aspect ratio to determine floating player size
// This allows us to support fixed pixel width/height or 100%*100% by matching the player container
const width = this._model.get('width');
const height = this._model.get('height');
const styles = getPlayerSizeStyles(this._model, width);
styles.maxWidth = Math.min(400, playerBounds.width);
if (!this._model.get('aspectratio')) {
const containerWidth = playerBounds.width;
const containerHeight = playerBounds.height;
let aspectRatio = (containerHeight / containerWidth) || 0.5625; // (fallback to 16 by 9)
if (isNumber(width) && isNumber(height)) {
aspectRatio = height / width;
}
this._model.trigger('forceAspectRatioChange', { ratio: (aspectRatio * 100) + '%' });
}
style(this._wrapperEl, styles);
}
enableFloatingUI(): void {
this._floatingUI.enable();
}
disableFloatingUI(): void {
this._floatingUI.disable();
}
setFloatingPlayer(container: HTMLElement | null): void {
fpContainer.floatingPlayer = container;
}
getFloatingPlayer(): HTMLElement | null {
return fpContainer.floatingPlayer;
}
destroy(): void {
if (this.getFloatingPlayer() === this._playerEl) {
this.setFloatingPlayer(null);
}
if (this.getFloatingConfig() && this._isMobile) {
viewsManager.removeScrollHandler(this._boundThrottledMobileFloatScrollHandler);
}
removeFPWatcher(this);
this._model.off('change:floating', this._boundInitFloatingBehavior);
}
updateFloating(intersectionRatio: number, mobileFloatIntoPlace?: boolean): void {
// Player is 50% visible or less and no floating player already in the DOM. Player is not in iframe
const shouldFloat = intersectionRatio < 0.5 && !isIframe() && this.shouldFloatOnViewable();
if (shouldFloat) {
this.startFloating(mobileFloatIntoPlace);
} else {
this.stopFloating(false, mobileFloatIntoPlace);
}
}
// Functions for handler float on scroll (mobile)
checkFloatOnScroll(): void {
if (this.getFloatMode() !== 'notVisible') {
return;
}
const floating = this._model.get('isFloating');
const pb = this._playerBounds;
const enoughRoomForFloat = pb.top < FLOATING_TOP_OFFSET;
const scrollPos = window.scrollY || window.pageYOffset;
const hasCrossedThreshold = enoughRoomForFloat ?
pb.top <= scrollPos :
pb.top <= scrollPos + FLOATING_TOP_OFFSET;
if (!floating && hasCrossedThreshold) {
this.updateFloating(0, enoughRoomForFloat);
} else if (floating && !hasCrossedThreshold) {
this.updateFloating(1, enoughRoomForFloat);
}
}
throttledMobileFloatScrollHandler(): void {
if (!this.fosMobileBehavior() || !this._model.get('inDom')) {
return;
}
clearTimeout(this._mobileDebounceTimeout);
this._mobileDebounceTimeout = setTimeout(this.checkFloatOnScroll.bind(this), 150);
if (!this._mobileCheckCanFire) {
return;
}
this._mobileCheckCanFire = false;
this.checkFloatOnScroll();
setTimeout(() => {
this._mobileCheckCanFire = true;
}, 50);
}
// End functions for float on scroll (mobile)
checkFloatIntersection(ratio?: number): void {
const ratioIsNumber = typeof ratio === 'number';
let intersectionRatio = (ratioIsNumber ? ratio : this._lastIntRatio) as number;
// Ensure even if floating mode was not `notVisible` to start, that any change takes
// into account any instance of seeing the player
this._canFloat = this._canFloat || intersectionRatio >= 0.5;
if (
this.getFloatingConfig() &&
this.getFloatMode() === 'notVisible' &&
!this.fosMobileBehavior() &&
!this._floatingStoppedForever
) {
// Only start floating if player has been mostly visible at least once.
if (this._canFloat) {
this.updateFloating(intersectionRatio);
}
}
if (ratioIsNumber) {
this._lastIntRatio = ratio as number;
}
}
updateStyles(): void {
if (!this._floatingStoppedForever && this.getFloatingConfig() && this.getFloatMode() === 'notVisible') {
this._boundThrottledMobileFloatScrollHandler();
}
}
} | the_stack |
import { EOL } from "os";
import { DeviceAndroidDebugBridge } from "../android/device-android-debug-bridge";
import { TARGET_FRAMEWORK_IDENTIFIERS } from "../../constants";
import { exported } from "../../decorators";
import { IDictionary, IErrors, INet } from "../../declarations";
import { ICleanupService } from "../../../definitions/cleanup-service";
import { IInjector } from "../../definitions/yok";
import { injector } from "../../yok";
import { IStaticConfig } from "../../../declarations";
import * as _ from "lodash";
export class AndroidProcessService implements Mobile.IAndroidProcessService {
private _devicesAdbs: IDictionary<Mobile.IDeviceAndroidDebugBridge>;
private _forwardedLocalPorts: IDictionary<number>;
constructor(
private $errors: IErrors,
private $cleanupService: ICleanupService,
private $injector: IInjector,
private $net: INet,
private $staticConfig: IStaticConfig
) {
this._devicesAdbs = {};
this._forwardedLocalPorts = {};
}
public async forwardFreeTcpToAbstractPort(
portForwardInputData: Mobile.IPortForwardData
): Promise<number> {
const adb = await this.setupForPortForwarding(portForwardInputData);
return this.forwardPort(portForwardInputData, adb);
}
public async mapAbstractToTcpPort(
deviceIdentifier: string,
appIdentifier: string,
framework: string
): Promise<string> {
const adb = await this.setupForPortForwarding({
deviceIdentifier,
appIdentifier,
});
const processId = (await this.getProcessIds(adb, [appIdentifier]))[
appIdentifier
];
const applicationNotStartedErrorMessage = `The application is not started on the device with identifier ${deviceIdentifier}.`;
if (!processId) {
this.$errors.fail(applicationNotStartedErrorMessage);
}
const abstractPortsInformation = await this.getAbstractPortsInformation(
adb
);
const abstractPort = await this.getAbstractPortForApplication(
adb,
processId,
appIdentifier,
abstractPortsInformation,
framework
);
if (!abstractPort) {
this.$errors.fail(applicationNotStartedErrorMessage);
}
const forwardedTcpPort = await this.forwardPort(
{
deviceIdentifier,
appIdentifier,
abstractPort: `localabstract:${abstractPort}`,
},
adb
);
return forwardedTcpPort && forwardedTcpPort.toString();
}
public async getMappedAbstractToTcpPorts(
deviceIdentifier: string,
appIdentifiers: string[],
framework: string
): Promise<IDictionary<number>> {
const adb = this.getAdb(deviceIdentifier),
abstractPortsInformation = await this.getAbstractPortsInformation(adb),
processIds = await this.getProcessIds(adb, appIdentifiers),
adbForwardList = await adb.executeCommand(["forward", "--list"]),
localPorts: IDictionary<number> = {};
await Promise.all(
_.map(appIdentifiers, async (appIdentifier) => {
localPorts[appIdentifier] = null;
const processId = processIds[appIdentifier];
if (!processId) {
return;
}
const abstractPort = await this.getAbstractPortForApplication(
adb,
processId,
appIdentifier,
abstractPortsInformation,
framework
);
if (!abstractPort) {
return;
}
const localPort = await this.getAlreadyMappedPort(
adb,
deviceIdentifier,
abstractPort,
adbForwardList
);
if (localPort) {
localPorts[appIdentifier] = localPort;
}
})
);
return localPorts;
}
public async getDebuggableApps(
deviceIdentifier: string
): Promise<Mobile.IDeviceApplicationInformation[]> {
const adb = this.getAdb(deviceIdentifier);
const androidWebViewPortInformation = (
await this.getAbstractPortsInformation(adb)
).split(EOL);
// TODO: Add tests and make sure only unique names are returned. Input before groupBy is:
// [ { deviceIdentifier: 'SH26BW100473',
// appIdentifier: 'com.telerik.EmptyNS',
// framework: 'NativeScript' },
// { deviceIdentifier: 'SH26BW100473',
// appIdentifier: 'com.telerik.EmptyNS',
// framework: 'Cordova' },
// { deviceIdentifier: 'SH26BW100473',
// appIdentifier: 'chrome',
// framework: 'Cordova' },
// { deviceIdentifier: 'SH26BW100473',
// appIdentifier: 'chrome',
// framework: 'Cordova' } ]
const portInformation = await Promise.all(
_.map(
androidWebViewPortInformation,
async (line) =>
(await this.getApplicationInfoFromWebViewPortInformation(
adb,
deviceIdentifier,
line
)) ||
(await this.getNativeScriptApplicationInformation(
adb,
deviceIdentifier,
line
))
)
);
return _(portInformation)
.filter((deviceAppInfo) => !!deviceAppInfo)
.groupBy((element) => element.framework)
.map((group: Mobile.IDeviceApplicationInformation[]) =>
_.uniqBy(group, (g) => g.appIdentifier)
)
.flatten()
.value();
}
@exported("androidProcessService")
public async getAppProcessId(
deviceIdentifier: string,
appIdentifier: string
): Promise<string> {
const adb = this.getAdb(deviceIdentifier);
const processId = (await this.getProcessIds(adb, [appIdentifier]))[
appIdentifier
];
return processId ? processId.toString() : null;
}
private async forwardPort(
portForwardInputData: Mobile.IPortForwardData,
adb: Mobile.IDeviceAndroidDebugBridge
): Promise<number> {
let localPort = await this.getAlreadyMappedPort(
adb,
portForwardInputData.deviceIdentifier,
portForwardInputData.abstractPort
);
if (!localPort) {
localPort = await this.$net.getFreePort();
await adb.executeCommand(
["forward", `tcp:${localPort}`, portForwardInputData.abstractPort],
{ deviceIdentifier: portForwardInputData.deviceIdentifier }
);
}
this._forwardedLocalPorts[
portForwardInputData.deviceIdentifier
] = localPort;
await this.$cleanupService.addCleanupCommand({
command: await this.$staticConfig.getAdbFilePath(),
args: [
"-s",
portForwardInputData.deviceIdentifier,
"forward",
"--remove",
`tcp:${localPort}`,
],
});
return localPort && +localPort;
}
private async setupForPortForwarding(
portForwardInputData?: Mobile.IPortForwardDataBase
): Promise<Mobile.IDeviceAndroidDebugBridge> {
const adb = this.getAdb(portForwardInputData.deviceIdentifier);
return adb;
}
private async getApplicationInfoFromWebViewPortInformation(
adb: Mobile.IDeviceAndroidDebugBridge,
deviceIdentifier: string,
information: string
): Promise<Mobile.IDeviceApplicationInformation> {
// Need to search by processId to check for old Android webviews (@webview_devtools_remote_<processId>).
const processIdRegExp = /@webview_devtools_remote_(.+)/g;
const processIdMatches = processIdRegExp.exec(information);
let cordovaAppIdentifier: string;
if (processIdMatches) {
const processId = processIdMatches[1];
cordovaAppIdentifier = await this.getApplicationIdentifierFromPid(
adb,
processId
);
} else {
// Search for appIdentifier (@<appIdentifier>_devtools_remote).
const chromeAppIdentifierRegExp = /@(.+)_devtools_remote\s?/g;
const chromeAppIdentifierMatches = chromeAppIdentifierRegExp.exec(
information
);
if (chromeAppIdentifierMatches && chromeAppIdentifierMatches.length > 0) {
cordovaAppIdentifier = chromeAppIdentifierMatches[1];
}
}
if (cordovaAppIdentifier) {
return {
deviceIdentifier: deviceIdentifier,
appIdentifier: cordovaAppIdentifier,
framework: TARGET_FRAMEWORK_IDENTIFIERS.Cordova,
};
}
return null;
}
private async getNativeScriptApplicationInformation(
adb: Mobile.IDeviceAndroidDebugBridge,
deviceIdentifier: string,
information: string
): Promise<Mobile.IDeviceApplicationInformation> {
// Search for appIdentifier (@<appIdentifier-debug>).
const nativeScriptAppIdentifierRegExp = /@(.+)-(debug|inspectorServer)/g;
const nativeScriptAppIdentifierMatches = nativeScriptAppIdentifierRegExp.exec(
information
);
if (
nativeScriptAppIdentifierMatches &&
nativeScriptAppIdentifierMatches.length > 0
) {
const appIdentifier = nativeScriptAppIdentifierMatches[1];
return {
deviceIdentifier: deviceIdentifier,
appIdentifier: appIdentifier,
framework: TARGET_FRAMEWORK_IDENTIFIERS.NativeScript,
};
}
return null;
}
private async getAbstractPortForApplication(
adb: Mobile.IDeviceAndroidDebugBridge,
processId: string | number,
appIdentifier: string,
abstractPortsInformation: string,
framework: string
): Promise<string> {
// The result will look like this (without the columns names):
// Num RefCount Protocol Flags Type St Inode Path
// 0000000000000000: 00000002 00000000 00010000 0001 01 189004 @webview_devtools_remote_25512
// The Path column is the abstract port.
framework = framework || "";
switch (framework.toLowerCase()) {
case TARGET_FRAMEWORK_IDENTIFIERS.Cordova.toLowerCase():
return this.getCordovaPortInformation(
abstractPortsInformation,
appIdentifier,
processId
);
case TARGET_FRAMEWORK_IDENTIFIERS.NativeScript.toLowerCase():
return this.getNativeScriptPortInformation(
abstractPortsInformation,
appIdentifier
);
default:
return (
this.getCordovaPortInformation(
abstractPortsInformation,
appIdentifier,
processId
) ||
this.getNativeScriptPortInformation(
abstractPortsInformation,
appIdentifier
)
);
}
}
private getCordovaPortInformation(
abstractPortsInformation: string,
appIdentifier: string,
processId: string | number
): string {
return (
this.getPortInformation(
abstractPortsInformation,
`${appIdentifier}_devtools_remote`
) || this.getPortInformation(abstractPortsInformation, processId)
);
}
private getNativeScriptPortInformation(
abstractPortsInformation: string,
appIdentifier: string
): string {
return this.getPortInformation(
abstractPortsInformation,
`${appIdentifier}-debug`
);
}
private async getAbstractPortsInformation(
adb: Mobile.IDeviceAndroidDebugBridge
): Promise<string> {
return adb.executeShellCommand(["cat", "/proc/net/unix"]);
}
private getPortInformation(
abstractPortsInformation: string,
searchedInfo: string | number
): string {
const processRegExp = new RegExp(
`\\w+:\\s+(?:\\w+\\s+){1,6}@(.*?${searchedInfo})$`,
"gm"
);
const match = processRegExp.exec(abstractPortsInformation);
return match && match[1];
}
private async getProcessIds(
adb: Mobile.IDeviceAndroidDebugBridge,
appIdentifiers: string[]
): Promise<IDictionary<number>> {
// Process information will look like this (without the columns names):
// USER PID PPID VSIZE RSS WCHAN PC NAME
// u0_a63 25512 1334 1519560 96040 ffffffff f76a8f75 S com.telerik.appbuildertabstest
const result: IDictionary<number> = {};
const processIdInformation: string = await adb.executeShellCommand(["ps"]);
_.each(appIdentifiers, (appIdentifier) => {
const processIdRegExp = new RegExp(`^\\w*\\s*(\\d+).*?${appIdentifier}$`);
result[appIdentifier] = this.getFirstMatchingGroupFromMultilineResult<
number
>(processIdInformation, processIdRegExp);
});
return result;
}
private async getAlreadyMappedPort(
adb: Mobile.IDeviceAndroidDebugBridge,
deviceIdentifier: string,
abstractPort: string,
adbForwardList?: any
): Promise<number> {
const allForwardedPorts: string =
adbForwardList || (await adb.executeCommand(["forward", "--list"])) || "";
// Sample output:
// 5e2e580b tcp:62503 localabstract:webview_devtools_remote_7985
// 5e2e580b tcp:62524 localabstract:webview_devtools_remote_7986
// 5e2e580b tcp:63160 localabstract:webview_devtools_remote_7987
// 5e2e580b tcp:57577 localabstract:com.telerik.nrel-debug
const regex = new RegExp(
`${deviceIdentifier}\\s+?tcp:(\\d+?)\\s+?.*?${abstractPort}$`
);
return this.getFirstMatchingGroupFromMultilineResult<number>(
allForwardedPorts,
regex
);
}
private getAdb(deviceIdentifier: string): Mobile.IDeviceAndroidDebugBridge {
if (!this._devicesAdbs[deviceIdentifier]) {
this._devicesAdbs[deviceIdentifier] = this.$injector.resolve(
DeviceAndroidDebugBridge,
{
identifier: deviceIdentifier,
}
);
}
return this._devicesAdbs[deviceIdentifier];
}
private async getApplicationIdentifierFromPid(
adb: Mobile.IDeviceAndroidDebugBridge,
pid: string,
psData?: string
): Promise<string> {
psData = psData || (await adb.executeShellCommand(["ps"]));
// Process information will look like this (without the columns names):
// USER PID PPID VSIZE RSS WCHAN PC NAME
// u0_a63 25512 1334 1519560 96040 ffffffff f76a8f75 S com.telerik.appbuildertabstest
return this.getFirstMatchingGroupFromMultilineResult<string>(
psData,
new RegExp(`\\s+${pid}(?:\\s+\\d+){3}\\s+.*\\s+(.*?)$`)
);
}
private getFirstMatchingGroupFromMultilineResult<T>(
input: string,
regex: RegExp
): T {
let result: T;
_((input || "").split("\n"))
.map((line) => line.trim())
.filter((line) => !!line)
.each((line) => {
const matches = line.match(regex);
if (matches && matches[1]) {
result = <any>matches[1];
return false;
}
});
return result;
}
}
injector.register("androidProcessService", AndroidProcessService); | the_stack |
import { fromAscii, toHex } from "@cosmjs/encoding";
import { Uint53 } from "@cosmjs/math";
import {
Account,
accountFromAny,
AuthExtension,
BankExtension,
Block,
BroadcastTxResponse,
Coin,
IndexedTx,
isSearchByHeightQuery,
isSearchBySentFromOrToQuery,
isSearchByTagsQuery,
QueryClient,
SearchTxFilter,
SearchTxQuery,
SequenceResponse,
setupAuthExtension,
setupBankExtension,
TimeoutError,
} from "@cosmjs/stargate";
import { Tendermint34Client, toRfc3339WithNanoseconds } from "@cosmjs/tendermint-rpc";
import { assert, sleep } from "@cosmjs/utils";
import { CodeInfoResponse } from "cosmjs-types/cosmwasm/wasm/v1/query";
import { ContractCodeHistoryOperationType } from "cosmjs-types/cosmwasm/wasm/v1/types";
import { JsonObject, setupWasmExtension, WasmExtension } from "./queries";
// Re-exports that belong to public CosmWasmClient interfaces
export {
JsonObject, // returned by CosmWasmClient.queryContractSmart
};
export interface Code {
readonly id: number;
/** Bech32 account address */
readonly creator: string;
/** Hex-encoded sha256 hash of the code stored here */
readonly checksum: string;
// `source` and `builder` were removed in wasmd 0.18
// https://github.com/CosmWasm/wasmd/issues/540
}
export interface CodeDetails extends Code {
/** The original Wasm bytes */
readonly data: Uint8Array;
}
export interface Contract {
readonly address: string;
readonly codeId: number;
/** Bech32 account address */
readonly creator: string;
/** Bech32-encoded admin address */
readonly admin: string | undefined;
readonly label: string;
/**
* The IBC port ID assigned to this contract by wasmd.
*
* This is set for all IBC contracts (https://github.com/CosmWasm/wasmd/blob/v0.16.0/x/wasm/keeper/keeper.go#L299-L306).
*/
readonly ibcPortId: string | undefined;
}
export interface ContractCodeHistoryEntry {
/** The source of this history entry */
readonly operation: "Genesis" | "Init" | "Migrate";
readonly codeId: number;
readonly msg: Record<string, unknown>;
}
/** Use for testing only */
export interface PrivateCosmWasmClient {
readonly tmClient: Tendermint34Client | undefined;
readonly queryClient: (QueryClient & AuthExtension & BankExtension & WasmExtension) | undefined;
}
export class CosmWasmClient {
private readonly tmClient: Tendermint34Client | undefined;
private readonly queryClient: (QueryClient & AuthExtension & BankExtension & WasmExtension) | undefined;
private readonly codesCache = new Map<number, CodeDetails>();
private chainId: string | undefined;
public static async connect(endpoint: string): Promise<CosmWasmClient> {
const tmClient = await Tendermint34Client.connect(endpoint);
return new CosmWasmClient(tmClient);
}
protected constructor(tmClient: Tendermint34Client | undefined) {
if (tmClient) {
this.tmClient = tmClient;
this.queryClient = QueryClient.withExtensions(
tmClient,
setupAuthExtension,
setupBankExtension,
setupWasmExtension,
);
}
}
protected getTmClient(): Tendermint34Client | undefined {
return this.tmClient;
}
protected forceGetTmClient(): Tendermint34Client {
if (!this.tmClient) {
throw new Error(
"Tendermint client not available. You cannot use online functionality in offline mode.",
);
}
return this.tmClient;
}
protected getQueryClient(): (QueryClient & AuthExtension & BankExtension & WasmExtension) | undefined {
return this.queryClient;
}
protected forceGetQueryClient(): QueryClient & AuthExtension & BankExtension & WasmExtension {
if (!this.queryClient) {
throw new Error("Query client not available. You cannot use online functionality in offline mode.");
}
return this.queryClient;
}
public async getChainId(): Promise<string> {
if (!this.chainId) {
const response = await this.forceGetTmClient().status();
const chainId = response.nodeInfo.network;
if (!chainId) throw new Error("Chain ID must not be empty");
this.chainId = chainId;
}
return this.chainId;
}
public async getHeight(): Promise<number> {
const status = await this.forceGetTmClient().status();
return status.syncInfo.latestBlockHeight;
}
public async getAccount(searchAddress: string): Promise<Account | null> {
try {
const account = await this.forceGetQueryClient().auth.account(searchAddress);
return account ? accountFromAny(account) : null;
} catch (error) {
if (/rpc error: code = NotFound/i.test(error)) {
return null;
}
throw error;
}
}
public async getSequence(address: string): Promise<SequenceResponse> {
const account = await this.getAccount(address);
if (!account) {
throw new Error(
"Account does not exist on chain. Send some tokens there before trying to query sequence.",
);
}
return {
accountNumber: account.accountNumber,
sequence: account.sequence,
};
}
public async getBlock(height?: number): Promise<Block> {
const response = await this.forceGetTmClient().block(height);
return {
id: toHex(response.blockId.hash).toUpperCase(),
header: {
version: {
block: new Uint53(response.block.header.version.block).toString(),
app: new Uint53(response.block.header.version.app).toString(),
},
height: response.block.header.height,
chainId: response.block.header.chainId,
time: toRfc3339WithNanoseconds(response.block.header.time),
},
txs: response.block.txs,
};
}
public async getBalance(address: string, searchDenom: string): Promise<Coin> {
return this.forceGetQueryClient().bank.balance(address, searchDenom);
}
public async getTx(id: string): Promise<IndexedTx | null> {
const results = await this.txsQuery(`tx.hash='${id}'`);
return results[0] ?? null;
}
public async searchTx(query: SearchTxQuery, filter: SearchTxFilter = {}): Promise<readonly IndexedTx[]> {
const minHeight = filter.minHeight || 0;
const maxHeight = filter.maxHeight || Number.MAX_SAFE_INTEGER;
if (maxHeight < minHeight) return []; // optional optimization
function withFilters(originalQuery: string): string {
return `${originalQuery} AND tx.height>=${minHeight} AND tx.height<=${maxHeight}`;
}
let txs: readonly IndexedTx[];
if (isSearchByHeightQuery(query)) {
txs =
query.height >= minHeight && query.height <= maxHeight
? await this.txsQuery(`tx.height=${query.height}`)
: [];
} else if (isSearchBySentFromOrToQuery(query)) {
const sentQuery = withFilters(`message.module='bank' AND transfer.sender='${query.sentFromOrTo}'`);
const receivedQuery = withFilters(
`message.module='bank' AND transfer.recipient='${query.sentFromOrTo}'`,
);
const [sent, received] = await Promise.all(
[sentQuery, receivedQuery].map((rawQuery) => this.txsQuery(rawQuery)),
);
const sentHashes = sent.map((t) => t.hash);
txs = [...sent, ...received.filter((t) => !sentHashes.includes(t.hash))];
} else if (isSearchByTagsQuery(query)) {
const rawQuery = withFilters(query.tags.map((t) => `${t.key}='${t.value}'`).join(" AND "));
txs = await this.txsQuery(rawQuery);
} else {
throw new Error("Unknown query type");
}
const filtered = txs.filter((tx) => tx.height >= minHeight && tx.height <= maxHeight);
return filtered;
}
public disconnect(): void {
if (this.tmClient) this.tmClient.disconnect();
}
/**
* Broadcasts a signed transaction to the network and monitors its inclusion in a block.
*
* If broadcasting is rejected by the node for some reason (e.g. because of a CheckTx failure),
* an error is thrown.
*
* If the transaction is not included in a block before the provided timeout, this errors with a `TimeoutError`.
*
* If the transaction is included in a block, a `BroadcastTxResponse` is returned. The caller then
* usually needs to check for execution success or failure.
*/
// NOTE: This method is tested against slow chains and timeouts in the @cosmjs/stargate package.
// Make sure it is kept in sync!
public async broadcastTx(
tx: Uint8Array,
timeoutMs = 60_000,
pollIntervalMs = 3_000,
): Promise<BroadcastTxResponse> {
let timedOut = false;
const txPollTimeout = setTimeout(() => {
timedOut = true;
}, timeoutMs);
const pollForTx = async (txId: string): Promise<BroadcastTxResponse> => {
if (timedOut) {
throw new TimeoutError(
`Transaction with ID ${txId} was submitted but was not yet found on the chain. You might want to check later.`,
txId,
);
}
await sleep(pollIntervalMs);
const result = await this.getTx(txId);
return result
? {
code: result.code,
height: result.height,
rawLog: result.rawLog,
transactionHash: txId,
gasUsed: result.gasUsed,
gasWanted: result.gasWanted,
}
: pollForTx(txId);
};
const broadcasted = await this.forceGetTmClient().broadcastTxSync({ tx });
if (broadcasted.code) {
throw new Error(
`Broadcasting transaction failed with code ${broadcasted.code} (codespace: ${broadcasted.codeSpace}). Log: ${broadcasted.log}`,
);
}
const transactionId = toHex(broadcasted.hash).toUpperCase();
return new Promise((resolve, reject) =>
pollForTx(transactionId).then(
(value) => {
clearTimeout(txPollTimeout);
resolve(value);
},
(error) => {
clearTimeout(txPollTimeout);
reject(error);
},
),
);
}
public async getCodes(): Promise<readonly Code[]> {
const { codeInfos } = await this.forceGetQueryClient().wasm.listCodeInfo();
return (codeInfos || []).map((entry: CodeInfoResponse): Code => {
assert(entry.creator && entry.codeId && entry.dataHash, "entry incomplete");
return {
id: entry.codeId.toNumber(),
creator: entry.creator,
checksum: toHex(entry.dataHash),
};
});
}
public async getCodeDetails(codeId: number): Promise<CodeDetails> {
const cached = this.codesCache.get(codeId);
if (cached) return cached;
const { codeInfo, data } = await this.forceGetQueryClient().wasm.getCode(codeId);
assert(
codeInfo && codeInfo.codeId && codeInfo.creator && codeInfo.dataHash && data,
"codeInfo missing or incomplete",
);
const codeDetails: CodeDetails = {
id: codeInfo.codeId.toNumber(),
creator: codeInfo.creator,
checksum: toHex(codeInfo.dataHash),
data: data,
};
this.codesCache.set(codeId, codeDetails);
return codeDetails;
}
public async getContracts(codeId: number): Promise<readonly string[]> {
// TODO: handle pagination - accept as arg or auto-loop
const { contracts } = await this.forceGetQueryClient().wasm.listContractsByCodeId(codeId);
return contracts;
}
/**
* Throws an error if no contract was found at the address
*/
public async getContract(address: string): Promise<Contract> {
const { address: retrievedAddress, contractInfo } = await this.forceGetQueryClient().wasm.getContractInfo(
address,
);
if (!contractInfo) throw new Error(`No contract found at address "${address}"`);
assert(retrievedAddress, "address missing");
assert(contractInfo.codeId && contractInfo.creator && contractInfo.label, "contractInfo incomplete");
return {
address: retrievedAddress,
codeId: contractInfo.codeId.toNumber(),
creator: contractInfo.creator,
admin: contractInfo.admin || undefined,
label: contractInfo.label,
ibcPortId: contractInfo.ibcPortId || undefined,
};
}
/**
* Throws an error if no contract was found at the address
*/
public async getContractCodeHistory(address: string): Promise<readonly ContractCodeHistoryEntry[]> {
const result = await this.forceGetQueryClient().wasm.getContractCodeHistory(address);
if (!result) throw new Error(`No contract history found for address "${address}"`);
const operations: Record<number, "Init" | "Genesis" | "Migrate"> = {
[ContractCodeHistoryOperationType.CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT]: "Init",
[ContractCodeHistoryOperationType.CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS]: "Genesis",
[ContractCodeHistoryOperationType.CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE]: "Migrate",
};
return (result.entries || []).map((entry): ContractCodeHistoryEntry => {
assert(entry.operation && entry.codeId && entry.msg);
return {
operation: operations[entry.operation],
codeId: entry.codeId.toNumber(),
msg: JSON.parse(fromAscii(entry.msg)),
};
});
}
/**
* Returns the data at the key if present (raw contract dependent storage data)
* or null if no data at this key.
*
* Promise is rejected when contract does not exist.
*/
public async queryContractRaw(address: string, key: Uint8Array): Promise<Uint8Array | null> {
// just test contract existence
await this.getContract(address);
const { data } = await this.forceGetQueryClient().wasm.queryContractRaw(address, key);
return data ?? null;
}
/**
* Makes a smart query on the contract, returns the parsed JSON document.
*
* Promise is rejected when contract does not exist.
* Promise is rejected for invalid query format.
* Promise is rejected for invalid response format.
*/
public async queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject> {
try {
return await this.forceGetQueryClient().wasm.queryContractSmart(address, queryMsg);
} catch (error) {
if (error instanceof Error) {
if (error.message.startsWith("not found: contract")) {
throw new Error(`No contract found at address "${address}"`);
} else {
throw error;
}
} else {
throw error;
}
}
}
private async txsQuery(query: string): Promise<readonly IndexedTx[]> {
const results = await this.forceGetTmClient().txSearchAll({ query: query });
return results.txs.map((tx) => {
return {
height: tx.height,
hash: toHex(tx.hash).toUpperCase(),
code: tx.result.code,
rawLog: tx.result.log || "",
tx: tx.tx,
gasUsed: tx.result.gasUsed,
gasWanted: tx.result.gasWanted,
};
});
}
} | the_stack |
import { CalendarEvent, Config } from '../../../common/interface';
import { Context } from '../../../context/store';
import { DateTime } from 'luxon';
import { EVENT_TYPE } from '../../../common/enums';
import { disableTouchDragging } from '../../eventButton/EventButton.utils';
import { formatDateTimeToString, parseCssDark } from '../../../utils/common';
import { getDaysNum } from '../../../utils/calendarDays';
import { useContext, useEffect, useRef, useState } from 'react';
import CurrentHourLine from '../../currentHourLine/CurrentHourLine';
import EventButton from '../../eventButton/EventButton';
import LuxonHelper from '../../../utils/luxonHelper';
const renderEvents = (dataset: any[], day: DateTime) => {
return dataset.map((eventRaw: any) => {
const item: CalendarEvent = eventRaw.event;
return (
<EventButton
key={`${item.id}${item.internalID ? item.internalID : ''}`}
item={eventRaw}
type={EVENT_TYPE.NORMAL}
meta={item.meta}
day={day}
/>
);
});
};
export const HOUR_DIVIDER = 4;
export const getDateFromPosition = (
value: number,
day: DateTime,
config: Config
): DateTime => {
let stringValue = String(value);
stringValue = stringValue.includes('.') ? stringValue : `${stringValue}.0`;
const [hourStart, minuteStart] = stringValue.split('.');
return day
.set({
hour: Number(hourStart),
minute: Number(`0.${minuteStart}`) * 60,
second: 0,
millisecond: 0,
})
.setZone(config.timezone);
};
export const getHourHeightPartialUnit = (config: Config) =>
Number((config.hourHeight / HOUR_DIVIDER).toFixed(0));
interface DaysViewOneDayProps {
key: string;
day: DateTime;
index: number;
data: any;
}
const DaysViewOneDay = (props: DaysViewOneDayProps) => {
const { day, index, data } = props;
const [store] = useContext(Context);
const { width, selectedView, config, callbacks, isNewEventOpen } = store;
const { onNewEventClick } = callbacks;
const { isDark, hourHeight } = config;
const [offsetTop, setOffsetTop] = useState<any>(null);
const [offsetTopEnd, setOffsetTopEnd] = useState<any>(null);
const startAt: any = useRef(null);
const endAt: any = useRef(null);
const [startAtState, setStartAt] = useState<DateTime | null>(null);
const [endAtState, setEndAt] = useState<DateTime | null>(null);
// const [isDraggingNewEvent, setIsDraggingNewEvent] = useState(false);
const newEventStartOffset: any = useRef(null);
const newEventEndOffset: any = useRef(null);
const startAtRef: any = useRef(null);
const isDraggingRef: any = useRef(null);
const isUpdating: any = useRef(false);
const style: any = {
position: 'absolute',
top: offsetTop,
height: offsetTopEnd - offsetTop,
background: store.style.primaryColor,
width: '100%',
zIndex: 9,
borderRadius: 8,
opacity: 0.8,
};
const handleEventClickInternal = (event: any) => {
if (isDraggingRef.current || isUpdating.current) {
return;
}
if (onNewEventClick) {
const rect: { top: number } = event.target.getBoundingClientRect();
const y: number = event.clientY - rect.top;
const startAtOnClick = getDateFromPosition(
Number((y / hourHeight).toFixed(0)),
day,
config
);
if (!startAtOnClick?.toUTC()?.toString()) {
return;
}
const endAtOnClick = startAtOnClick.plus({ hour: 1 });
// Get hour from click event
const hour: number = y / hourHeight;
onNewEventClick(
{
day: day.toJSDate(),
hour,
startAt: startAtOnClick?.toUTC().toString(),
endAt: endAtOnClick?.toUTC().toString(),
event,
view: selectedView,
},
event
);
}
};
const onMove = (e: any) => {
isDraggingRef.current = true;
// setIsDraggingNewEvent(true);
e.preventDefault();
e.stopPropagation();
if (disableTouchDragging(e)) {
return;
}
// Get column element for day, where event is placed
const dayElement: any = document.getElementById(
`Kalend__day__${day.toString()}`
);
const touches: any = e.nativeEvent?.touches?.[0];
const dayElementRect = dayElement.getBoundingClientRect();
let y: number;
// handle touch movement
if (touches) {
y = touches.clientY - dayElementRect.top;
} else {
// handle mouse movement
y = e.clientY - dayElementRect.top;
}
// initial dragging
if (newEventStartOffset.current === null) {
const yString = (y / getHourHeightPartialUnit(config))
.toFixed(0)
.split('.');
const yValue = Number(yString[0]) * getHourHeightPartialUnit(config);
setOffsetTop(yValue);
const startAtValue = getDateFromPosition(
yValue / hourHeight,
day,
config
);
startAtRef.current = startAtValue;
startAt.current = startAtValue;
setStartAt(startAtValue);
setOffsetTop(yValue);
setOffsetTopEnd(yValue);
newEventStartOffset.current = yValue;
newEventEndOffset.current = yValue;
startAtRef.current = startAtValue;
endAt.current = startAtValue;
setEndAt(startAtValue);
return;
}
// handle dragging up
if (newEventStartOffset.current && y < newEventStartOffset.current) {
const yString = (y / getHourHeightPartialUnit(config))
.toFixed(0)
.split('.');
const yValue = Number(yString[0]) * getHourHeightPartialUnit(config);
setOffsetTop(yValue);
const startAtValue = getDateFromPosition(
yValue / hourHeight,
day,
config
);
startAtRef.current = startAtValue;
startAt.current = startAtValue;
setStartAt(startAtValue);
return;
}
// handle dragging down
const yString = (y / getHourHeightPartialUnit(config))
.toFixed(0)
.split('.');
const yValue = Number(yString[0]) * getHourHeightPartialUnit(config);
setOffsetTopEnd(yValue);
const endAtValue = getDateFromPosition(yValue / hourHeight, day, config);
endAt.current = endAtValue;
setEndAt(endAtValue);
};
/**
* Cancel dragging event
* remove listeners clean long click timeout and reset state
* @param event
*/
const onMouseUp = (event: any) => {
event.stopPropagation();
event.preventDefault();
// clean listeners
document.removeEventListener('mouseup', onMouseUp, true);
document.removeEventListener('mousemove', onMove, true);
const targetClass = event.target.className;
// prevent propagating when clicking on event due to listeners
if (targetClass.indexOf('Kalend__Event') !== -1) {
return;
}
if (!isDraggingRef.current) {
handleEventClickInternal(event);
return;
}
// correct layout with actual value from endAt date
if (endAt) {
const correctedValue = (endAt.hour + endAt.minute / 60) * hourHeight;
newEventEndOffset.current = correctedValue;
setOffsetTopEnd(correctedValue);
}
if (isUpdating.current) {
return;
}
if (onNewEventClick && isDraggingRef.current) {
const startValue: number = offsetTop / hourHeight;
isUpdating.current = true;
if (!startAt?.current?.toUTC()?.toString()) {
isDraggingRef.current = false;
isUpdating.current = false;
return;
}
onNewEventClick(
{
day: day.toJSDate(),
hour: startValue,
event,
startAt: startAt.current?.toUTC().toString(),
endAt: endAt.current?.toUTC().toString(),
view: selectedView,
},
event
);
}
isDraggingRef.current = false;
isUpdating.current = false;
};
/**
* Start event dragging on long press/touch
* Set listeners
* @param e
*/
const onMouseDownLong = (e: any) => {
if (disableTouchDragging(e)) {
return;
}
e.preventDefault();
e.stopPropagation();
if (e.button !== 0) return;
document.addEventListener('mousemove', onMove, true);
document.addEventListener('mouseup', onMouseUp, true);
};
/**
* Initial long press click/touch on event
* @param e
*/
const onMouseDown = (e: any) => {
e.preventDefault();
e.stopPropagation();
// if (isDraggingRef.current) {
// onMouseUp(e);
// return;
// }
onMouseDownLong(e);
};
const oneDayStyle: any = {
width: width / getDaysNum(selectedView),
height: hourHeight * 24,
};
const isToday: boolean = LuxonHelper.isToday(day);
const isFirstDay: boolean = index === 0;
const dataForDay: any = data;
const dateNow: any = DateTime.local();
const nowPosition: number =
dateNow
.diff(DateTime.local().set({ hour: 0, minute: 0, second: 0 }), 'minutes')
.toObject().minutes /
(60 / hourHeight);
useEffect(() => {
if (!store.config.autoScroll) {
return;
}
if (isToday) {
const elements: any = document.querySelectorAll(
'.calendar-body__wrapper'
);
for (const element of elements) {
element.scrollTo({ top: nowPosition - 40, behavior: 'smooth' });
}
}
}, []);
const handleCloseNewEventDrag = (e?: any) => {
if (e) {
e.preventDefault();
e.stopPropagation();
}
setOffsetTopEnd(null);
setOffsetTop(null);
// setIsDraggingNewEvent(false);
isDraggingRef.current = false;
newEventStartOffset.current = null;
newEventEndOffset.current = null;
startAt.current = null;
endAt.current = null;
setStartAt(null);
setEndAt(null);
isUpdating.current = false;
};
useEffect(() => {
if (!isNewEventOpen) {
handleCloseNewEventDrag();
}
}, [isNewEventOpen]);
return (
<div
id={`Kalend__day__${day.toString()}`}
key={day.toString()}
style={oneDayStyle}
onMouseDown={onMouseDown}
onMouseUp={onMouseUp}
// onTouchStart={onMouseDown}
// onTouchMove={onMove}
// onTouchEnd={onMouseUp}
className={
!isFirstDay
? parseCssDark('Kalend__DayViewOneDay', isDark)
: 'Kalend__DayViewOneDay'
}
// onClick={handleEventClickInternal}
>
{isToday && config.showTimeLine ? <CurrentHourLine /> : null}
{store.daysViewLayout?.[formatDateTimeToString(day)] &&
dataForDay &&
dataForDay.length > 0
? renderEvents(dataForDay, day)
: null}
{isDraggingRef.current ? (
<div
style={{
width: '100%',
height: '100%',
background: 'transparent',
position: 'fixed',
top: 0,
left: 0,
zIndex: 8,
}}
onClick={handleCloseNewEventDrag}
/>
) : null}
{isDraggingRef.current ? (
<div style={style}>
<div
style={{
paddingTop: 4,
paddingLeft: 4,
fontSize: 12,
}}
>
<p style={{ color: 'white' }}>New event</p>
<p style={{ color: 'white' }}>
{startAtState ? startAtState.toFormat('HH:mm') : ''} -{' '}
{endAtState ? endAtState.toFormat('HH:mm') : ''}
</p>
</div>
</div>
) : null}
</div>
);
};
export default DaysViewOneDay; | the_stack |
import { Matrix4, matrixEquals4 } from './Matrix4'
import { Vector3 } from './Vector3'
import { Euler, EulerRotationOrder, eulerEquals } from './Euler'
import { Quaternion } from './Quaternion'
import { Float32BufferAttribute } from '../core/BufferAttribute'
import * as MathUtils from './MathUtils'
import { eps } from './test-constants'
describe('Maths', () => {
describe('Matrix4', () => {
test('constructor', () => {
const a = new Matrix4()
expect(a.determinant()).toBe(1)
const b = new Matrix4()
b.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
expect(b.elements[0]).toBe(0)
expect(b.elements[1]).toBe(4)
expect(b.elements[2]).toBe(8)
expect(b.elements[3]).toBe(12)
expect(b.elements[4]).toBe(1)
expect(b.elements[5]).toBe(5)
expect(b.elements[6]).toBe(9)
expect(b.elements[7]).toBe(13)
expect(b.elements[8]).toBe(2)
expect(b.elements[9]).toBe(6)
expect(b.elements[10]).toBe(10)
expect(b.elements[11]).toBe(14)
expect(b.elements[12]).toBe(3)
expect(b.elements[13]).toBe(7)
expect(b.elements[14]).toBe(11)
expect(b.elements[15]).toBe(15)
expect(matrixEquals4(a, b)).toBeFalsy()
})
// PUBLIC STUFF
todo('isMatrix4')
test('set', () => {
const b = new Matrix4()
expect(b.determinant()).toBe(1)
b.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
expect(b.elements[0]).toBe(0)
expect(b.elements[1]).toBe(4)
expect(b.elements[2]).toBe(8)
expect(b.elements[3]).toBe(12)
expect(b.elements[4]).toBe(1)
expect(b.elements[5]).toBe(5)
expect(b.elements[6]).toBe(9)
expect(b.elements[7]).toBe(13)
expect(b.elements[8]).toBe(2)
expect(b.elements[9]).toBe(6)
expect(b.elements[10]).toBe(10)
expect(b.elements[11]).toBe(14)
expect(b.elements[12]).toBe(3)
expect(b.elements[13]).toBe(7)
expect(b.elements[14]).toBe(11)
expect(b.elements[15]).toBe(15)
})
test('identity', () => {
const b = new Matrix4()
b.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
expect(b.elements[0]).toBe(0)
expect(b.elements[1]).toBe(4)
expect(b.elements[2]).toBe(8)
expect(b.elements[3]).toBe(12)
expect(b.elements[4]).toBe(1)
expect(b.elements[5]).toBe(5)
expect(b.elements[6]).toBe(9)
expect(b.elements[7]).toBe(13)
expect(b.elements[8]).toBe(2)
expect(b.elements[9]).toBe(6)
expect(b.elements[10]).toBe(10)
expect(b.elements[11]).toBe(14)
expect(b.elements[12]).toBe(3)
expect(b.elements[13]).toBe(7)
expect(b.elements[14]).toBe(11)
expect(b.elements[15]).toBe(15)
const a = new Matrix4()
expect(matrixEquals4(a, b)).toBeFalsy()
b.identity()
expect(matrixEquals4(a, b)).toBeTruthy()
})
test('clone', () => {
const a = new Matrix4()
a.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
const b = a.clone()
expect(matrixEquals4(a, b)).toBeTruthy()
// ensure that it is a true copy
a.elements[0] = 2
expect(matrixEquals4(a, b)).toBeFalsy()
})
test('copy', () => {
const a = new Matrix4()
a.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
const b = new Matrix4()
b.copy(a)
expect(matrixEquals4(a, b)).toBeTruthy()
// ensure that it is a true copy
a.elements[0] = 2
expect(matrixEquals4(a, b)).toBeFalsy()
})
test('copyPosition', () => {
const a = new Matrix4().set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
const b = new Matrix4().set(1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 0, 13, 14, 15, 16)
expect(matrixEquals4(a, b)).toBeFalsy()
b.copyPosition(a)
expect(matrixEquals4(a, b)).toBeTruthy()
})
test('makeBasis/extractBasis', () => {
const identityBasis = [new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1)]
const a = new Matrix4().makeBasis(identityBasis[0], identityBasis[1], identityBasis[2])
const identity = new Matrix4()
expect(matrixEquals4(a, identity)).toBeTruthy()
const testBases = [[new Vector3(0, 1, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1)]]
for (let i = 0; i < testBases.length; i++) {
const testBasis = testBases[i]
const b = new Matrix4().makeBasis(testBasis[0], testBasis[1], testBasis[2])
const outBasis = [new Vector3(), new Vector3(), new Vector3()]
b.extractBasis(outBasis[0], outBasis[1], outBasis[2])
// check what goes in, is what comes out.
for (let j = 0; j < outBasis.length; j++) {
expect(outBasis[j].equals(testBasis[j])).toBeTruthy()
}
// get the basis out the hard war
for (let j = 0; j < identityBasis.length; j++) {
outBasis[j].copy(identityBasis[j])
outBasis[j].applyMatrix4(b)
}
// did the multiply method of basis extraction work?
for (let j = 0; j < outBasis.length; j++) {
expect(outBasis[j].equals(testBasis[j])).toBeTruthy()
}
}
})
todo('extractRotation')
test('makeRotationFromEuler/extractRotation', () => {
const testValues: Array<Euler> = [
new Euler(0, 0, 0, EulerRotationOrder.XYZ),
new Euler(1, 0, 0, EulerRotationOrder.XYZ),
new Euler(0, 1, 0, EulerRotationOrder.ZYX),
new Euler(0, 0, 0.5, EulerRotationOrder.YZX),
new Euler(0, 0, -0.5, EulerRotationOrder.YZX),
]
for (let i = 0; i < testValues.length; i++) {
const v = testValues[i]
const m = new Matrix4()
m.makeRotationFromEuler(v)
const v2 = new Euler()
v2.setFromRotationMatrix(m, v.order)
const m2 = new Matrix4()
m2.makeRotationFromEuler(v2)
// TODO restore the concatenated string messages, which currently cause a runtime error.
// 'makeRotationFromEuler #' + i.toString() + ': original and Euler-derived matrices are equal'
expect(matrixEquals4(m, m2, eps)).toBeTruthy()
// 'makeRotationFromEuler #' + i.toString() + ': original and matrix-derived Eulers are equal'
expect(eulerEquals(v, v2, eps)).toBeTruthy()
const m3 = new Matrix4()
m3.extractRotation(m2)
const v3 = new Euler()
v3.setFromRotationMatrix(m3, v.order)
// TODO restore the concatenated string messages, which currently cause a runtime error.
// 'extractRotation #' + i.toString() + ': original and extracted matrices are equal'
expect(matrixEquals4(m, m3, eps)).toBeTruthy()
// 'extractRotation #' + i.toString() + ': original and extracted Eulers are equal'
expect(eulerEquals(v, v3, eps)).toBeTruthy()
}
})
test('lookAt', () => {
const a = new Matrix4()
const expected = new Matrix4().identity()
const eye = new Vector3(0, 0, 0)
const target = new Vector3(0, 1, -1)
const up = new Vector3(0, 1, 0)
a.lookAt(eye, target, up)
const rotation = new Euler().setFromRotationMatrix(a)
expect(rotation.x * (180 / Mathf.PI) == 45).toBeTruthy() // Check the rotation
// eye and target are in the same position
eye.copy(target)
a.lookAt(eye, target, up)
expect(matrixEquals4(a, expected)).toBeTruthy() // Check the result for eye == target
// up and z are parallel
eye.set(0, 1, 0)
target.set(0, 0, 0)
a.lookAt(eye, target, up)
expected.set(1, 0, 0, 0, 0, 0.0001, 1, 0, 0, -1, 0.0001, 0, 0, 0, 0, 1)
expect(matrixEquals4(a, expected)).toBeTruthy() // Check the result for when up and z are parallel
})
todo('multiply')
todo('premultiply')
test('multiplyMatrices', () => {
// Reference:
//
// #!/usr/bin/env python
// from __future__ import print_function
// import numpy as np
// print(
// np.dot(
// np.reshape([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53], (4, 4)),
// np.reshape([59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131], (4, 4))
// )
// )
//
// [[ 1585 1655 1787 1861]
// [ 5318 5562 5980 6246]
// [10514 11006 11840 12378]
// [15894 16634 17888 18710]]
const lhs = new Matrix4()
lhs.set(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53)
const rhs = new Matrix4()
rhs.set(59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131)
const ans = new Matrix4()
ans.multiplyMatrices(lhs, rhs)
expect(ans.elements[0]).toBe(1585)
expect(ans.elements[1]).toBe(5318)
expect(ans.elements[2]).toBe(10514)
expect(ans.elements[3]).toBe(15894)
expect(ans.elements[4]).toBe(1655)
expect(ans.elements[5]).toBe(5562)
expect(ans.elements[6]).toBe(11006)
expect(ans.elements[7]).toBe(16634)
expect(ans.elements[8]).toBe(1787)
expect(ans.elements[9]).toBe(5980)
expect(ans.elements[10]).toBe(11840)
expect(ans.elements[11]).toBe(17888)
expect(ans.elements[12]).toBe(1861)
expect(ans.elements[13]).toBe(6246)
expect(ans.elements[14]).toBe(12378)
expect(ans.elements[15]).toBe(18710)
})
test('multiplyScalar', () => {
const b = new Matrix4().set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
expect(b.elements[0]).toBe(0)
expect(b.elements[1]).toBe(4)
expect(b.elements[2]).toBe(8)
expect(b.elements[3]).toBe(12)
expect(b.elements[4]).toBe(1)
expect(b.elements[5]).toBe(5)
expect(b.elements[6]).toBe(9)
expect(b.elements[7]).toBe(13)
expect(b.elements[8]).toBe(2)
expect(b.elements[9]).toBe(6)
expect(b.elements[10]).toBe(10)
expect(b.elements[11]).toBe(14)
expect(b.elements[12]).toBe(3)
expect(b.elements[13]).toBe(7)
expect(b.elements[14]).toBe(11)
expect(b.elements[15]).toBe(15)
b.multiplyScalar(2)
expect(b.elements[0]).toBe(0 * 2)
expect(b.elements[1]).toBe(4 * 2)
expect(b.elements[2]).toBe(8 * 2)
expect(b.elements[3]).toBe(12 * 2)
expect(b.elements[4]).toBe(1 * 2)
expect(b.elements[5]).toBe(5 * 2)
expect(b.elements[6]).toBe(9 * 2)
expect(b.elements[7]).toBe(13 * 2)
expect(b.elements[8]).toBe(2 * 2)
expect(b.elements[9]).toBe(6 * 2)
expect(b.elements[10]).toBe(10 * 2)
expect(b.elements[11]).toBe(14 * 2)
expect(b.elements[12]).toBe(3 * 2)
expect(b.elements[13]).toBe(7 * 2)
expect(b.elements[14]).toBe(11 * 2)
expect(b.elements[15]).toBe(15 * 2)
})
// test('applyToBufferAttribute', assert => {
// var a = new Matrix4().set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
// var attr = new Float32BufferAttribute([1, 2, 1, 3, 0, 3], 3)
// var expected = new Float32BufferAttribute(
// [
// 0.1666666716337204,
// 0.4444444477558136,
// 0.7222222089767456,
// 0.1599999964237213,
// 0.4399999976158142,
// 0.7200000286102295,
// ],
// 3
// )
// var applied = a.applyToBufferAttribute(attr)
// assert.strictEqual(
// expected.count,
// applied.count,
// 'Applied buffer and expected buffer have the same number of entries'
// )
// for (var i = 0, l = expected.count; i < l; i++) {
// assert.ok(Mathf.abs(applied.getX(i) - expected.getX(i)) <= eps, 'Check x')
// assert.ok(Mathf.abs(applied.getY(i) - expected.getY(i)) <= eps, 'Check y')
// assert.ok(Mathf.abs(applied.getZ(i) - expected.getZ(i)) <= eps, 'Check z')
// }
// })
test('determinant', () => {
const a = new Matrix4()
expect(a.determinant()).toBe(1)
a.elements[0] = 2
expect(a.determinant()).toBe(2)
a.elements[0] = 0
expect(a.determinant()).toBe(0)
// calculated via http://www.euclideanspace.com/maths/algebra/matrix/functions/determinant/fourD/index.htm
a.set(2, 3, 4, 5, -1, -21, -3, -4, 6, 7, 8, 10, -8, -9, -10, -12)
expect(a.determinant()).toBe(76)
})
test('transpose', () => {
const a = new Matrix4()
let b = a.clone().transpose()
expect(matrixEquals4(a, b)).toBeTruthy()
b = new Matrix4().set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
const c = b.clone().transpose()
expect(!matrixEquals4(b, c)).toBeTruthy()
c.transpose()
expect(matrixEquals4(b, c)).toBeTruthy()
})
todo('setPosition')
test('getInverse', () => {
const identity = new Matrix4()
const a = new Matrix4()
const b = new Matrix4()
b.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
const c = new Matrix4()
c.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
expect(matrixEquals4(a, b)).toBeFalsy()
b.getInverse(a)
expect(matrixEquals4(b, new Matrix4())).toBeTruthy()
expect(b.getInverse(c)).toBeFalsy()
const testMatrices: Array<Matrix4> = [
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
new Matrix4(),
]
testMatrices[0].makeRotationX(0.3)
testMatrices[1].makeRotationX(-0.3)
testMatrices[2].makeRotationY(0.3)
testMatrices[3].makeRotationY(-0.3)
testMatrices[4].makeRotationZ(0.3)
testMatrices[5].makeRotationZ(-0.3)
testMatrices[6].makeScale(1, 2, 3)
testMatrices[7].makeScale(1 / 8, 1 / 2, 1 / 3)
testMatrices[8].makePerspective(-1, 1, 1, -1, 1, 1000)
testMatrices[9].makePerspective(-16, 16, 9, -9, 0.1, 10000)
testMatrices[10].makeTranslation(1, 2, 3)
for (let i = 0, il = testMatrices.length; i < il; i++) {
const m = testMatrices[i]
const mInverse = new Matrix4()
expect(mInverse.getInverse(m)).toBeTruthy()
const mSelfInverse = m.clone()
mSelfInverse.getInverse(mSelfInverse)
// self-inverse should the same as inverse
expect(matrixEquals4(mSelfInverse, mInverse)).toBeTruthy()
// the determinant of the inverse should be the reciprocal
expect(m.determinant() * mInverse.determinant()).toBeCloseTo(1)
const mProduct = new Matrix4()
mProduct.multiplyMatrices(m, mInverse)
// the determinant of the identity matrix is 1
expect(mProduct.determinant()).toBeCloseTo(1)
expect(matrixEquals4(mProduct, identity)).toBeTruthy()
}
})
todo('scale')
test('getMaxScaleOnAxis', () => {
const a = new Matrix4()
a.set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
const expected = Mathf.sqrt(3 * 3 + 7 * 7 + 11 * 11)
expect(a.getMaxScaleOnAxis()).toBeCloseTo(expected)
})
todo('makeTranslation')
todo('makeRotationX')
todo('makeRotationY')
todo('makeRotationZ')
test('makeRotationAxis', () => {
const axis = new Vector3(1.5, 0.0, 1.0).normalize()
const radians = MathUtils.degToRad(45)
const a = new Matrix4().makeRotationAxis(axis, radians)
const expected = new Matrix4().set(
0.9098790095958609,
-0.39223227027636803,
0.13518148560620882,
0,
0.39223227027636803,
0.7071067811865476,
-0.588348405414552,
0,
0.13518148560620882,
0.588348405414552,
0.7972277715906868,
0,
0,
0,
0,
1
)
expect(matrixEquals4(a, expected)).toBeTruthy()
})
todo('makeScale')
todo('makeShear')
test('compose/decompose', () => {
const tValues: Array<Vector3> = [
new Vector3(),
new Vector3(3, 0, 0),
new Vector3(0, 4, 0),
new Vector3(0, 0, 5),
new Vector3(-6, 0, 0),
new Vector3(0, -7, 0),
new Vector3(0, 0, -8),
new Vector3(-2, 5, -9),
new Vector3(-2, -5, -9),
]
const sValues: Array<Vector3> = [
new Vector3(1, 1, 1),
new Vector3(2, 2, 2),
new Vector3(1, -1, 1),
new Vector3(-1, 1, 1),
new Vector3(1, 1, -1),
new Vector3(2, -2, 1),
new Vector3(-1, 2, -2),
new Vector3(-1, -1, -1),
new Vector3(-2, -2, -2),
]
const rValues: Array<Quaternion> = [
new Quaternion(),
new Quaternion(),
new Quaternion(),
new Quaternion(0, 0.9238795292366128, 0, 0.38268342717215614),
]
rValues[1].setFromEuler(new Euler(1, 1, 0))
rValues[2].setFromEuler(new Euler(1, -1, 1))
for (let ti = 0; ti < tValues.length; ti++) {
for (let si = 0; si < sValues.length; si++) {
for (let ri = 0; ri < rValues.length; ri++) {
const t = tValues[ti]
const s = sValues[si]
const r = rValues[ri]
const m = new Matrix4()
m.compose(t, r, s)
const t2 = new Vector3()
const r2 = new Quaternion()
const s2 = new Vector3()
m.decompose(t2, r2, s2)
const m2 = new Matrix4()
m2.compose(t2, r2, s2)
/*
// debug code
var matrixIsSame = matrixEquals4( m, m2 );
if ( ! matrixIsSame ) {
console.log( t, s, r );
console.log( t2, s2, r2 );
console.log( m, m2 );
}
*/
expect(matrixEquals4(m, m2)).toBeTruthy()
}
}
}
})
todo('makePerspective')
test('makeOrthographic', () => {
const a = new Matrix4().makeOrthographic(-1, 1, -1, 1, 1, 100)
const expected = new Matrix4().set(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -2 / 99, -101 / 99, 0, 0, 0, 1)
expect(matrixEquals4(a, expected)).toBeTruthy()
})
test('equals', () => {
const a = new Matrix4().set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
const b = new Matrix4().set(0, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
expect(a.equals(b)).toBeFalsy() // Check that a does not equal b
expect(b.equals(a)).toBeFalsy() // Check that b does not equal a
a.copy(b)
expect(a.equals(b)).toBeTruthy() // Check that a equals b after copy()
expect(b.equals(a)).toBeTruthy() // Check that b equals a after copy()
})
todo('fromArray')
test('toArray', () => {
const a = new Matrix4().set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
const noOffset: f32[] = [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16]
const withOffset: f32[] = [0, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16]
let arr = a.toArray()
expect<f32[]>(arr).toStrictEqual(noOffset) // No array, no offset
arr = [6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22, 23]
a.toArray(arr)
expect<f32[]>(arr).toStrictEqual(noOffset) // With array, no offset
arr = [0, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22, 23]
a.toArray(arr, 1)
expect<f32[]>(arr).toStrictEqual(withOffset) // With array, with offset
})
})
}) | the_stack |
export type SearchOptions = {
/**
* Create a new query with an empty search query.
*/
readonly query?: string;
/**
* Allows a search for similar objects, but the query has to be constructed on your end and included alongside an empty query.
*
* The similarQuery should be made from the tags and keywords of the relevant object.
*/
readonly similarQuery?: string;
/**
* Filter hits by facet value.
*/
readonly facetFilters?: string | readonly string[] | ReadonlyArray<readonly string[] | string>;
/**
* Create filters for ranking purposes, where records that match the filter are ranked highest.
*/
readonly optionalFilters?: string | readonly string[] | ReadonlyArray<readonly string[] | string>;
/**
* Filter on numeric attributes.
*/
readonly numericFilters?: string | readonly string[] | ReadonlyArray<readonly string[] | string>;
/**
* Filter hits by tags. tagFilters is a different way of filtering, which relies on the _tags
* attribute. It uses a simpler syntax than filters. You can use it when you want to do
* simple filtering based on tags.
*/
readonly tagFilters?: string | readonly string[] | ReadonlyArray<readonly string[] | string>;
/**
* Determines how to calculate the total score for filtering.
*/
readonly sumOrFiltersScores?: boolean;
/**
* Filter the query with numeric, facet and/or tag filters.
*/
readonly filters?: string;
/**
* Specify the page to retrieve.
*/
readonly page?: number;
/**
* Set the number of hits per page.
*/
readonly hitsPerPage?: number;
/**
* Specify the offset of the first hit to return.
*/
readonly offset?: number;
/**
* Set the number of hits to retrieve (used only with offset).
*/
readonly length?: number;
/**
* List of attributes to highlight.
*/
readonly attributesToHighlight?: readonly string[];
/**
* List of attributes to snippet, with an optional maximum number of words to snippet.
*/
readonly attributesToSnippet?: readonly string[];
/**
* Gives control over which attributes to retrieve and which not to retrieve.
*/
readonly attributesToRetrieve?: readonly string[];
/**
* The HTML string to insert before the highlighted parts in all highlight and snippet results.
*/
readonly highlightPreTag?: string;
/**
* The HTML string to insert after the highlighted parts in all highlight and snippet results
*/
readonly highlightPostTag?: string;
/**
* String used as an ellipsis indicator when a snippet is truncated.
*/
readonly snippetEllipsisText?: string;
/**
* Restrict highlighting and snippeting to items that matched the query.
*/
readonly restrictHighlightAndSnippetArrays?: boolean;
/**
* Facets to retrieve.
*/
readonly facets?: readonly string[];
/**
* Maximum number of facet values to return for each facet during a regular search.
*/
readonly maxValuesPerFacet?: number;
/**
* Force faceting to be applied after de-duplication (via the Distinct setting).
*/
readonly facetingAfterDistinct?: boolean;
/**
* Minimum number of characters a word in the query string must contain to accept matches with 1 typo
*/
readonly minWordSizefor1Typo?: number;
/**
* Minimum number of characters a word in the query string must contain to accept matches with 2 typos.
*/
readonly minWordSizefor2Typos?: number;
/**
* Whether to allow typos on numbers (“numeric tokens”) in the query string.
*/
readonly allowTyposOnNumericTokens?: boolean;
/**
* List of attributes on which you want to disable typo tolerance.
*/
readonly disableTypoToleranceOnAttributes?: readonly string[];
/**
* Controls if and how query words are interpreted as prefixes.
*/
readonly queryType?: 'prefixLast' | 'prefixAll' | 'prefixNone';
/**
* Selects a strategy to remove words from the query when it doesn’t match any hits.
*/
readonly removeWordsIfNoResults?: 'none' | 'lastWords' | 'firstWords' | 'allOptional';
/**
* Enables the advanced query syntax.
*/
readonly advancedSyntax?: boolean;
/**
* AdvancedSyntaxFeatures can be exactPhrase or excludeWords
*/
readonly advancedSyntaxFeatures?: ReadonlyArray<'exactPhrase' | 'excludeWords'>;
/**
* A list of words that should be considered as optional when found in the query.
*/
readonly optionalWords?: string | readonly string[];
/**
* List of attributes on which you want to disable the exact ranking criterion.
*/
readonly disableExactOnAttributes?: readonly string[];
/**
* Controls how the exact ranking criterion is computed when the query contains only one word.
*/
readonly exactOnSingleWordQuery?: 'attribute' | 'none' | 'word';
/**
* List of alternatives that should be considered an exact match by the exact ranking criterion.
*/
readonly alternativesAsExact?: ReadonlyArray<
'ignorePlurals' | 'singleWordSynonym' | 'multiWordsSynonym'
>;
/**
* Whether rules should be globally enabled.
*/
readonly enableRules?: boolean;
/**
* Enables contextual rules.
*/
readonly ruleContexts?: readonly string[];
/**
* Enables de-duplication or grouping of results.
*/
readonly distinct?: boolean | number;
/**
* Whether the current query will be taken into account in the Analytics
*/
readonly analytics?: boolean;
/**
* List of tags to apply to the query in the analytics.
*/
readonly analyticsTags?: readonly string[];
/**
* Whether to take into account an index’s synonyms for a particular search.
*/
readonly synonyms?: boolean;
/**
* Whether to highlight and snippet the original word that matches the synonym or the synonym itself.
*/
readonly replaceSynonymsInHighlight?: boolean;
/**
* Precision of the proximity ranking criterion.
*/
readonly minProximity?: number;
/**
* Choose which fields the response will contain. Applies to search and browse queries.
*/
readonly responseFields?: readonly string[];
/**
* Maximum number of facet hits to return during a search for facet values.
*/
readonly maxFacetHits?: number;
/**
* Whether to include or exclude a query from the processing-time percentile computation.
*/
readonly percentileComputation?: boolean;
/**
* Enable the Click Analytics feature.
*/
readonly clickAnalytics?: boolean;
/**
* The `personalizationImpact` parameter sets the percentage of the impact that personalization has on ranking records. The
* value must be between 0 and 100 (inclusive). This parameter will not be taken into account if `enablePersonalization`
* is **false**.
*/
readonly personalizationImpact?: number;
/**
* Enable personalization for the query
*/
readonly enablePersonalization?: boolean;
/**
* Restricts a given query to look in only a subset of your searchable attributes.
*/
readonly restrictSearchableAttributes?: readonly string[];
/**
* Restricts a given query to look in only a subset of your searchable attributes.
*/
readonly sortFacetValuesBy?: 'count' | 'alpha';
/**
* Controls whether typo tolerance is enabled and how it is applied.
*/
readonly typoTolerance?: boolean | 'min' | 'strict';
/**
* Search for entries around a central geolocation, enabling a geo search within a circular area.
*/
readonly aroundLatLng?: string;
/**
* Search for entries around a given location automatically computed from the requester’s IP address.
*/
readonly aroundLatLngViaIP?: boolean;
/**
* Search for entries around a given location automatically computed from the requester’s IP address.
*/
readonly aroundRadius?: number | 'all';
/**
* Precision of geo search (in meters), to add grouping by geo location to the ranking formula.
*/
readonly aroundPrecision?:
| number
| ReadonlyArray<{ readonly from: number; readonly value: number }>;
/**
* Minimum radius (in meters) used for a geo search when aroundRadius is not set.
*/
readonly minimumAroundRadius?: number;
/**
* Search inside a rectangular area (in geo coordinates).
*/
readonly insideBoundingBox?: ReadonlyArray<readonly number[]> | string;
/**
* Search inside a polygon (in geo coordinates).
*/
readonly insidePolygon?: ReadonlyArray<readonly number[]>;
/**
* Treats singular, plurals, and other forms of declensions as matching terms.
*/
readonly ignorePlurals?: boolean | readonly string[];
/**
* Removes stop (common) words from the query before executing it.
*/
readonly removeStopWords?: boolean | readonly string[];
/**
* List of supported languages with their associated language ISO code.
*
* Apply a set of natural language best practices such as ignorePlurals,
* removeStopWords, removeWordsIfNoResults, analyticsTags and ruleContexts.
*/
readonly naturalLanguages?: readonly string[];
/**
* When true, each hit in the response contains an additional _rankingInfo object.
*/
readonly getRankingInfo?: boolean;
/**
* A user identifier.
* Format: alpha numeric string [a-zA-Z0-9_-]
* Length: between 1 and 64 characters.
*/
readonly userToken?: string;
/**
* Can be to enable or disable A/B tests at query time.
* Engine's default: true
*/
readonly enableABTest?: boolean;
/**
* Enable word segmentation (also called decompounding) at query time for
* compatible languages. For example, this turns the Dutch query
* "spaanplaatbehang" into "spaan plaat behang" to retrieve more relevant
* results.
*/
readonly decompoundQuery?: boolean;
/**
* The relevancy threshold to apply to search in a virtual index [0-100]. A Bigger
* value means fewer, but more relevant results, smaller value means more, but
* less relevant results.
*/
readonly relevancyStrictness?: number;
/**
* Whether this search should use Dynamic Re-Ranking.
* @link https://www.algolia.com/doc/guides/algolia-ai/re-ranking/
*
* Note: You need to turn on Dynamic Re-Ranking on your index for it to have an effect on
* your search results. You can do this through the Re-Ranking page on the dashboard.
* This parameter is only used to turn off Dynamic Re-Ranking (with false) at search time.
*/
readonly enableReRanking?: boolean;
/**
* When Dynamic Re-Ranking is enabled, only records that match these filters will be impacted by Dynamic Re-Ranking.
*/
readonly reRankingApplyFilter?:
| string
| readonly string[]
| ReadonlyArray<readonly string[] | string>
| null;
/**
* Sets the languages to be used by language-specific settings and functionalities such as ignorePlurals, removeStopWords, and CJK word-detection.
*/
readonly queryLanguages?: readonly string[];
}; | the_stack |
import { Component, Element, Prop, h, Watch, EventEmitter, Event } from '@stencil/core';
import { select, event } from 'd3-selection';
import { max, min } from 'd3-array';
import { scaleBand, scaleLinear, scaleOrdinal } from 'd3-scale';
import { line } from 'd3-shape';
import { v4 as uuid } from 'uuid';
import 'd3-transition';
import { IBoxModelType } from '@visa/charts-types';
import Utils from '@visa/visa-charts-utils';
const {
// circularFind,
initTooltipStyle,
drawAxis,
drawGrid,
drawTooltip,
formatStats,
// applyAT, // removed as this chart is not ready to support accessibility
getLicenses,
checkInteraction,
checkClicked,
checkHovered,
interactionStyle,
getColors,
outlineColor,
visaColors
} = Utils;
@Component({
tag: 'pareto-chart',
styleUrl: 'pareto-chart.scss'
})
export class ParetoChart {
@Event() clickFunc: EventEmitter;
@Event() hoverFunc: EventEmitter;
@Event() mouseOutFunc: EventEmitter;
@Prop() height: any = 400;
@Prop() width: any = 800;
@Prop() data: any[];
@Prop() showDataLabel: boolean = true; // to be removed
// chart accessors
@Prop() ordinalAccessor: any = 'label';
@Prop() valueAccessor: any = 'value';
@Prop() groupAccessor: any;
@Prop() uniqueID;
// value manipulations
@Prop() maxValueOverride: any;
// data label props object
@Prop({ mutable: true }) showTooltip = true;
@Prop() dataLabel: any = {
visible: true,
placement: 'top',
content: 'valueAccessor',
format: '0,0.00'
};
// reference line array for in order to draw one or many reference lines
@Prop() referenceLines: any = [];
// layout of chart verticle/horizontal/radial
@Prop() layout: string = 'vertical';
@Prop() mainTitle: string;
@Prop() subTitle: string;
@Prop() xAxis: any = {
visible: true,
gridVisible: true,
tickInterval: 1
};
@Prop() yAxis: any = {
visible: true,
gridVisible: true,
tickInterval: 1
};
@Prop() wrapLabel: boolean = false;
@Prop({ mutable: true }) colors;
@Prop({ mutable: true }) colorPalette = 'single_blue';
@Prop({ mutable: true }) hoverStyle: any;
@Prop({ mutable: true }) clickStyle: any;
@Prop({ mutable: true }) hoverOpacity = 1;
@Prop() cursor: any = 'default';
@Prop() sortOrder: any = '';
@Prop() roundedCorner: any = 0;
@Prop() margin: IBoxModelType = {
top: this.height * 0.01,
bottom: this.height * 0.01,
right: this.width * 0.01,
left: this.width * 0.01
};
@Prop({ mutable: true }) padding: IBoxModelType = {
top: 20,
bottom: 60,
right: 80,
left: 80
};
@Prop({ mutable: true }) hideDataTable = false;
// assign pareto line props
@Prop() paretoStroke: any = '#767676';
@Prop() paretoHighlight: any = '#15195A';
@Prop() paretoDot: any = 3;
@Prop() paretoThreshold: any;
// Interactivity
@Prop({ mutable: true }) hoverHighlight;
@Prop({ mutable: true }) clickHighlight = [];
@Prop({ mutable: true }) interactionKeys;
@Element()
barChartEl: HTMLElement;
svg: any;
root: any;
rootG: any;
tooltipG: any;
bars: any;
x: any;
y: any;
yCum: any;
line: any;
innerHeight: number;
innerWidth: number;
innerPaddedHeight: number;
innerPaddedWidth: number;
innerXAxis: any;
innerYAxis: any;
colorArr: any;
chartID: string;
shouldUpdateChart: boolean = false;
shouldUpdateBarStyle: boolean = false;
@Watch('uniqueID')
idWatcher(newID, _oldID) {
this.chartID = newID;
this.barChartEl.id = this.chartID;
}
@Watch('data')
dataWatcher(_newData, _oldData) {
// console.log('we are in data watcher', _newData, _oldData);
this.shouldUpdateChart = true;
}
@Watch('hoverHighlight')
@Watch('clickHighlight')
highlightWatcher(_newHighlight, _oldHighlight) {
// console.log('we are in highlight watcher', _newHighlight, _oldHighlight);
this.shouldUpdateBarStyle = true;
}
componentWillLoad() {
this.chartID = this.uniqueID || 'bar-chart-' + uuid();
this.barChartEl.id = this.chartID;
// console.log('component will load',)
this.updateChartVariable();
}
componentDidLoad() {
// console.log('component did load')
this.updateData();
this.drawChart();
this.setTooltipInitialStyle();
}
componentWillUpdate() {
// console.log('component will update')
this.updateChartVariable();
}
componentDidUpdate() {
// console.log('component did update')
// sorting of data defalut is asc
if (this.sortOrder === 'asc') {
this.data.sort((a, b) => Number(a[this.valueAccessor]) - Number(b[this.valueAccessor]));
} else if (this.sortOrder === 'desc') {
this.data.sort((a, b) => Number(b[this.valueAccessor]) - Number(a[this.valueAccessor]));
}
// this is a very unsophisticated pattern to handle hover issues only
// if we are only updating bar style then don't redraw
if (this.shouldUpdateBarStyle) {
this.shouldUpdateBarStyle = false;
this.updateBarSytle(this.bars);
} else {
// otherwise re-draw to handle any other possible change
this.shouldUpdateChart = false;
this.updateData();
this.drawChart();
}
}
updateData() {
var totalAmount = 0;
this.data.map((d, i) => {
d[this.valueAccessor] = parseFloat(d[this.valueAccessor]);
//prepare accumulative data for pareto line
d[this.valueAccessor] = +d[this.valueAccessor];
totalAmount += d[this.valueAccessor];
d.CumulativeAmount = i === 0 ? d[this.valueAccessor] : d[this.valueAccessor] + this.data[i - 1].CumulativeAmount;
});
//prepare accumulative data for pareto line
this.data.map(d => {
d.CumulativePercentage = d.CumulativeAmount / totalAmount;
});
}
updateChartVariable() {
this.innerXAxis = { ...this.xAxis, gridVisible: !(this.layout === 'vertical') && this.xAxis.gridVisible };
this.innerYAxis = { ...this.yAxis, gridVisible: this.layout === 'vertical' && this.yAxis.gridVisible };
if (!this.innerXAxis.visible) {
this.padding.bottom = this.height * 0.05;
}
if (!this.innerYAxis.visible) {
this.padding.left = this.width * 0.05;
}
this.interactionKeys ? '' : (this.interactionKeys = [this.groupAccessor || this.ordinalAccessor]);
// before we render/load we need to set our height and width based on props
this.innerHeight = this.height - this.margin.top - this.margin.bottom;
this.innerWidth = this.width - this.margin.left - this.margin.right;
this.innerPaddedHeight = this.innerHeight - this.padding.top - this.padding.bottom;
this.innerPaddedWidth = this.innerWidth - this.padding.left - this.padding.right;
}
updateBarSytle(bar) {
bar
.attr('fill', d =>
this.clickHighlight.length > 0 &&
checkClicked(d, this.clickHighlight, this.interactionKeys) &&
this.clickStyle.color
? visaColors[this.clickStyle.color] || this.clickStyle.color
: this.hoverHighlight && checkHovered(d, this.hoverHighlight, this.interactionKeys) && this.hoverStyle.color
? visaColors[this.hoverStyle.color] || this.hoverStyle.color
: this.groupAccessor
? this.colorArr(d[this.groupAccessor])
: this.colorArr(d[this.valueAccessor])
)
.attr('style', d => {
// set style for interaction: hovered/focus state- dashed, clicked state- solid outline
return interactionStyle({
data: d,
clickHighlight: this.clickHighlight,
hoverHighlight: this.hoverHighlight,
clickStyle: this.clickStyle,
hoverStyle: this.hoverStyle,
interactionKeys: this.interactionKeys,
defaultStroke: outlineColor(
this.groupAccessor ? this.colorArr(d[this.groupAccessor]) : this.colorArr(d[this.valueAccessor])
),
defaultStrokeWidth: 3
});
})
.attr('opacity', d =>
checkInteraction(d, 1, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.interactionKeys)
);
}
drawChart() {
// console.log('draw chart', this.data)
this.reSetRoot();
// scale band based on layout of chart
if (this.layout === 'vertical') {
this.y = scaleLinear()
.domain([0, this.maxValueOverride || max(this.data, d => d[this.valueAccessor])])
.range([this.innerPaddedHeight, 0]);
//for pareto-chart grid synchronize only
if (this.yAxis.gridVisible == true) {
var ceilingTen = Math.ceil(max(this.data, d => d[this.valueAccessor]) * 10) / 10;
// console.log('show yAxis grid', ceilingTen)
this.y = scaleLinear()
.domain([0, ceilingTen])
.range([this.innerPaddedHeight, 0]);
}
this.x = scaleBand()
.domain(this.data.map(d => d[this.ordinalAccessor]))
.range([0, this.innerPaddedWidth])
.padding(0.2);
// create accumulative y axis
this.yCum = scaleLinear()
.domain([0, 1])
.range([this.innerPaddedHeight, 0]);
} else if (this.layout === 'horizontal') {
this.x = scaleLinear()
.domain([0, this.maxValueOverride || max(this.data, d => d[this.valueAccessor])])
.range([0, this.innerPaddedWidth]);
this.y = scaleBand()
.domain(this.data.map(d => d[this.ordinalAccessor]))
.range([this.innerPaddedHeight, 0])
.padding(0.2);
}
this.line = line()
.x(d => this.x(d[this.ordinalAccessor]) + this.x.bandwidth() / 2)
.y(d => this.yCum(d.CumulativePercentage));
//.interpolate('basis');
const minValue = min(this.data, d => d[this.valueAccessor]);
const maxValue = max(this.data, d => d[this.valueAccessor]);
this.colorArr = this.groupAccessor
? getColors(
this.colors || this.colorPalette,
scaleOrdinal()
.domain(this.data.map(d => d[this.groupAccessor]))
.domain()
)
: getColors(this.colors || this.colorPalette, [minValue, maxValue]);
// interaction style default, adapted from bar chart
this.hoverStyle = this.hoverStyle
? this.hoverStyle
: this.colorPalette.includes('single')
? {
color: 'comp_blue',
strokeWidth: 3
}
: {
strokeWidth: 3
};
this.clickStyle = this.clickStyle
? this.clickStyle
: this.colorPalette.includes('single')
? {
color: 'supp_purple',
strokeWidth: 3
}
: {
strokeWidth: 3
};
this.drawGrid();
this.drawAxis();
this.drawBars();
if (this.line) {
this.drawLine();
}
this.drawDataLabels();
this.drawReferenceLines();
// if (!this.hideAccessibility) {
// applyAT({
// rootEle: this.barChartEl,
// svg: this.svg,
// title: this.mainTitle,
// subTitle: this.subTitle,
// data: this.data,
// // toolTipEl: this.tooltipG, // temporarilly removed during tooltip update, needs to be addressed during applyAT updatze
// hasXAxis: this.xAxis ? this.xAxis.visible : false,
// hasYAxis: this.yAxis ? this.yAxis.visible : false,
// xAxisLabel: this.xAxis.label ? this.xAxis.label : '',
// yAxisLabel: this.yAxis.label1 ? this.yAxis.label1 : '',
// secondaryYAxisLabel: this.yAxis.label2 ? this.yAxis.label2 : '',
// chartTag: 'pareto-chart',
// yAxis: this.y ? this.y : false,
// secondaryYAxis: this.yCum ? this.yCum : false,
// layout: this.layout ? this.layout : false,
// hideDataTable: this.hideDataTable
// });
// }
}
// reset graph size based on window size
reSetRoot() {
if (this.svg) {
this.svg.remove();
}
this.svg = select(this.barChartEl)
.select('#visa-viz-d3-pareto-container')
.append('svg')
.attr('width', this.width)
.attr('height', this.height)
.attr('viewBox', '0 0 ' + this.width + ' ' + this.height);
this.root = this.svg
.append('g')
.attr('id', 'visa-viz-margin-container-g')
.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);
this.rootG = this.root
.append('g')
.attr('id', 'visa-viz-padding-container-g')
.attr('transform', `translate(${this.padding.left}, ${this.padding.top})`);
this.tooltipG = select(this.barChartEl).select('.pareto-tooltip');
}
// draw axis line
drawAxis() {
drawAxis({
root: this.rootG,
height: this.innerPaddedHeight,
width: this.innerPaddedWidth,
axisScale: this.x,
left: false,
wrapLabel: this.wrapLabel && this.layout === 'vertical' ? this.x.bandwidth() : '',
format: this.xAxis.format,
tickInterval: this.xAxis.tickInterval,
label: this.xAxis.label,
padding: this.padding,
hide: !this.innerXAxis.visible
});
drawAxis({
root: this.rootG,
height: this.innerPaddedHeight,
width: this.innerPaddedWidth,
axisScale: this.y,
left: true,
wrapLabel: this.wrapLabel ? this.padding.left || 100 : '',
format: this.yAxis.format,
tickInterval: this.yAxis.tickInterval,
label: this.yAxis.label,
padding: this.padding,
hide: !this.innerYAxis.visible
});
drawAxis({
root: this.rootG,
height: this.innerPaddedHeight,
width: this.innerPaddedWidth,
axisScale: this.yCum,
right: true,
wrapLabel: this.wrapLabel ? this.padding.left || 100 : '',
format: this.yAxis.formatCum || '0.0%',
hide: !this.innerYAxis.visible
});
}
// helper function that will assign different label placements within the viz - specific to bar for now
placeDataLabels = (dRecord, xORy) => {
let xPlacement;
let yPlacement;
let dEm;
let dEmOther = '0em';
let textAnchor;
// console.log('we are in placeDataLabels', dRecord, xORy, this.dataLabel); // tslint:disable-line no-console
if (this.layout === 'vertical') {
if ((this.dataLabel.placement || 'top') === 'top') {
xPlacement = this.x(dRecord[this.ordinalAccessor]) + this.x.bandwidth() / 2;
yPlacement = this.y(Math.max(0, dRecord[this.valueAccessor]));
dEm = '-.3em';
textAnchor = 'middle';
} else if ((this.dataLabel.placement || 'top') === 'bottom') {
xPlacement = this.x(dRecord[this.ordinalAccessor]) + this.x.bandwidth() / 2;
yPlacement = this.y(0) - 5;
dEm = '-.2em';
textAnchor = 'middle';
}
} else if (this.layout === 'horizontal') {
if ((this.dataLabel.placement || 'top') === 'top') {
yPlacement = this.y(dRecord[this.ordinalAccessor]) + this.y.bandwidth() / 2 + 4;
xPlacement = this.x(dRecord[this.valueAccessor]) + 4;
dEm = '.2em';
textAnchor = 'start';
} else if ((this.dataLabel.placement || 'top') === 'bottom') {
yPlacement = this.y(dRecord[this.ordinalAccessor]) + this.y.bandwidth() / 2 + 4;
xPlacement = this.x(0);
dEm = '.2em';
textAnchor = 'start';
} else if ((this.dataLabel.placement || 'top') === 'bottomAbove') {
yPlacement = this.y(dRecord[this.ordinalAccessor]);
xPlacement = this.x(0);
dEm = '.2em';
dEmOther = '-.2em';
textAnchor = 'start';
} else if ((this.dataLabel.placement || 'top') === 'bottomBelow') {
yPlacement = this.y(dRecord[this.ordinalAccessor]) + this.y.bandwidth();
xPlacement = this.x(0);
dEm = '.2em';
dEmOther = '1em';
textAnchor = 'start';
}
}
if (xORy === 'x') {
return xPlacement;
} else if (xORy === 'y') {
return yPlacement;
} else if (xORy === 'em') {
return dEm;
} else if (xORy === 'em2') {
return dEmOther;
} else if (xORy === 'anchor') {
return textAnchor;
} else {
return null;
}
};
// based on whether value accessor and format was provided return the right thing
formatDataLabel(d) {
if (this.dataLabel.content === 'ordinalAccessor') {
return d[this.ordinalAccessor];
} else {
if (this.dataLabel.format) {
return formatStats(d[this.valueAccessor], this.dataLabel.format);
} else {
return d[this.valueAccessor];
}
}
}
// handle data labels
drawDataLabels() {
// check whether to show label, if so they render parts appropriately
if (this.dataLabel.visible) {
this.rootG.selectAll('text.dataLabel').remove();
// console.log('we are in data label', this.dataLabel, this ); // tslint:disable-line no-console
// now we can place the labels correctly on the graph
this.rootG
.append('g')
.attr('class', 'bar-dataLabel-group')
.attr('id', 'bar-dataLabel-group')
.selectAll('.text')
.data(this.data)
.enter()
.append('text')
.attr('x', d => this.placeDataLabels(d, 'x'))
.attr('y', d => this.placeDataLabels(d, 'y'))
.attr(this.layout === 'vertical' ? 'dy' : 'dx', d => this.placeDataLabels(d, 'em'))
.attr(this.layout === 'vertical' ? 'dx' : 'dy', d => this.placeDataLabels(d, 'em2'))
.attr('text-anchor', d => this.placeDataLabels(d, 'anchor'))
.attr('class', 'bar-dataLabel-' + this.layout)
.text(d => this.formatDataLabel(d))
.on('click', d => this.onClickHandler(d))
.on('mouseover', d => this.onHoverHandler(d))
.on('mouseout', () => this.onMouseOutHandler());
}
}
// dashed line grid for chart
drawGrid() {
drawGrid(
this.rootG,
this.innerPaddedHeight,
this.innerPaddedWidth,
this.x,
false,
!this.innerXAxis.gridVisible,
this.xAxis.tickInterval
);
drawGrid(
this.rootG,
this.innerPaddedHeight,
this.innerPaddedWidth,
this.y,
true,
!this.innerYAxis.gridVisible,
this.yAxis.tickInterval
);
}
// bars based on data
drawBars() {
if (this.layout === 'vertical') {
this.bars = this.rootG
.append('g')
.attr('class', 'bar-group')
.selectAll('.bar')
.data(this.data)
.enter()
.append('rect')
.attr('class', 'bar')
.attr('tabindex', (_, index) => (index === 0 ? '0' : '-1'))
.attr('rx', this.roundedCorner)
.attr('ry', this.roundedCorner)
.attr('x', d => this.x(d[this.ordinalAccessor]))
.attr('y', d => this.y(Math.max(0, d[this.valueAccessor]))) // this.y(d[this.valueAccessor]))
.attr('height', d => Math.abs(this.y(0) - this.y(d[this.valueAccessor])))
.attr('width', this.x.bandwidth())
.attr('cursor', this.cursor)
.attr('fill', d =>
this.clickHighlight.length > 0 &&
checkClicked(d, this.clickHighlight, this.interactionKeys) &&
this.clickStyle.color
? visaColors[this.clickStyle.color] || this.clickStyle.color
: this.hoverHighlight && checkHovered(d, this.hoverHighlight, this.interactionKeys) && this.hoverStyle.color
? visaColors[this.hoverStyle.color] || this.hoverStyle.color
: this.groupAccessor
? this.colorArr(d[this.groupAccessor])
: this.colorArr(d[this.valueAccessor])
)
.attr('style', d => {
// set style for interaction: hovered/focus state- dashed, clicked state- solid outline
return interactionStyle({
data: d,
clickHighlight: this.clickHighlight,
hoverHighlight: this.hoverHighlight,
clickStyle: this.clickStyle,
hoverStyle: this.hoverStyle,
interactionKeys: this.interactionKeys,
defaultStroke: outlineColor(
this.groupAccessor ? this.colorArr(d[this.groupAccessor]) : this.colorArr(d[this.valueAccessor])
),
defaultStrokeWidth: 3
});
})
.attr('opacity', d =>
checkInteraction(d, 1, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.interactionKeys)
)
.on('click', d => this.onClickHandler(d))
.on('mouseover', d => this.onHoverHandler(d))
.on('mouseout', () => this.onMouseOutHandler());
} else if (this.layout === 'horizontal') {
this.bars = this.rootG
.append('g')
.attr('class', 'bar-group')
.selectAll('.bar')
.data(this.data)
.enter()
.append('rect')
.attr('class', d => (this.clickHighlight.includes(d[this.ordinalAccessor]) ? 'bar highlight' : 'bar'))
.attr('tabindex', (_, index) => (index === 0 ? '0' : '-1'))
.attr('rx', this.roundedCorner)
.attr('ry', this.roundedCorner)
.attr('x', d => this.x(Math.min(0, d[this.valueAccessor])))
.attr('y', d => this.y(d[this.ordinalAccessor]))
.attr('height', this.y.bandwidth())
.attr('width', d => Math.abs(this.x(d[this.valueAccessor]) - this.x(0)))
.attr('cursor', this.cursor)
.attr('fill', d =>
this.clickHighlight.length > 0 &&
checkClicked(d, this.clickHighlight, this.interactionKeys) &&
this.clickStyle.color
? visaColors[this.clickStyle.color] || this.clickStyle.color
: this.hoverHighlight && checkHovered(d, this.hoverHighlight, this.interactionKeys) && this.hoverStyle.color
? visaColors[this.hoverStyle.color] || this.hoverStyle.color
: this.groupAccessor
? this.colorArr(d[this.groupAccessor])
: this.colorArr(d[this.valueAccessor])
)
.attr('style', d => {
// set style for interaction: hovered/focus state- dashed, clicked state- solid outline
return interactionStyle({
data: d,
clickHighlight: this.clickHighlight,
hoverHighlight: this.hoverHighlight,
clickStyle: this.clickStyle,
hoverStyle: this.hoverStyle,
interactionKeys: this.interactionKeys,
defaultStroke: outlineColor(
this.groupAccessor ? this.colorArr(d[this.groupAccessor]) : this.colorArr(d[this.valueAccessor])
),
defaultStrokeWidth: 3
});
})
.on('click', d => this.onClickHandler(d))
.on('mouseover', d => this.onHoverHandler(d))
.on('mouseout', () => this.onMouseOutHandler());
}
}
drawLine() {
let hasReachedThreshold = false;
let reachedThresholdIndex;
for (let i = 0; i < this.data.length; i++) {
if (!hasReachedThreshold && this.data[i].CumulativePercentage > this.paretoThreshold) {
reachedThresholdIndex = i;
hasReachedThreshold = true;
}
}
const lineG = this.rootG.append('g').attr('class', 'pareto-line');
lineG
.append('path')
.datum(this.data)
.attr('d', this.line)
.attr('class', 'pareto-line-path')
.attr('x', this.x.bandwidth() / 2)
.attr('fill', 'none')
.attr('stroke', this.paretoStroke)
.attr('stroke-width', 1);
lineG
.selectAll('.pareto-background-dot')
.data([this.data[reachedThresholdIndex]])
.enter()
.append('circle')
.attr('class', 'pareto-background-dot')
.attr('fill', '#fff')
.attr('stroke', this.paretoHighlight)
.attr('stroke-width', '1px')
.attr('r', this.paretoDot + 6)
.attr('cx', d => this.x(d[this.ordinalAccessor]) + this.x.bandwidth() / 2)
.attr('cy', d => this.yCum(d.CumulativePercentage));
lineG
.selectAll('.pareto-dot')
.data(this.data)
.enter()
.append('circle')
.attr('class', 'pareto-dot')
.attr('fill', (_, i) => {
if (i === reachedThresholdIndex) {
return this.paretoHighlight;
} else {
return this.paretoStroke;
}
})
.attr('r', (_, i) => (reachedThresholdIndex === i ? this.paretoDot + 3 : this.paretoDot))
.attr('cx', d => this.x(d[this.ordinalAccessor]) + this.x.bandwidth() / 2)
.attr('cy', d => this.yCum(d.CumulativePercentage));
lineG
.selectAll('text')
.data(this.data)
.enter()
.append('text')
.attr('x', d => this.placeDataLabels(d, 'x'))
.attr('y', d => this.yCum(d.CumulativePercentage))
.attr('dy', '-1em')
.attr('text-anchor', 'middle')
.attr('class', 'pareto-label')
.attr('fill', this.paretoHighlight)
.text((d, i) => (reachedThresholdIndex === i ? formatStats(d.CumulativePercentage, '0.0%') : ''));
}
drawReferenceLines() {
// first check whether we have reference lines array populated
if (this.referenceLines.length > 0) {
if (this.layout === 'vertical') {
this.rootG
.append('g')
.attr('class', 'bar-reference-line-group')
.selectAll('.bar-reference-line')
.data(this.referenceLines)
.enter()
.append('line')
.attr('id', d => d.referenceID)
.attr('class', 'bar-reference-line')
.attr('x1', 0)
.attr('x2', this.innerPaddedWidth)
.attr('y1', d => this.y(d.referenceData.referenceValue))
.attr('y2', d => this.y(d.referenceData.referenceValue))
.style('stroke', d => d.referenceData.strokeColor)
.style('stroke-width', d => d.referenceData.strokeWidth)
.style('opacity', d => d.referenceData.strokeOpacity);
this.rootG
.select('.bar-reference-line-group')
.selectAll('.bar-reference-line-label')
.data(this.referenceLines)
.enter()
.append('text')
.attr('id', d => d.referenceID + '-label')
.attr('class', 'bar-reference-line-label')
.attr('text-anchor', d =>
(d.referenceData.labelPlacementHorizontal || 'right') === 'right' ? 'start' : 'end'
)
.attr('x', d =>
(d.referenceData.labelPlacementHorizontal || 'right') === 'right' ? this.innerPaddedWidth : 0
)
.attr('dx', d => ((d.referenceData.labelPlacementHorizontal || 'right') === 'right' ? '0.1em' : '-0.1em'))
.attr('y', d => this.y(d.referenceData.referenceValue))
.attr('dy', '0.3em')
.text(d => d.referenceData.labelValue)
.style('fill', d => d.referenceData.strokeColor);
} else if (this.layout === 'horizontal') {
this.rootG
.append('g')
.attr('class', 'bar-reference-line-group')
.selectAll('.bar-reference-line')
.data(this.referenceLines)
.enter()
.append('line')
.attr('id', d => d.referenceID)
.attr('class', 'bar-reference-line')
.attr('y1', 0)
.attr('y2', this.innerPaddedHeight)
.attr('x1', d => this.x(d.referenceData.referenceValue))
.attr('x2', d => this.x(d.referenceData.referenceValue))
.style('stroke', d => d.referenceData.strokeColor)
.style('stroke-width', d => d.referenceData.strokeWidth)
.style('opacity', d => d.referenceData.strokeOpacity);
this.rootG
.select('.bar-reference-line-group')
.selectAll('.bar-reference-line-label')
.data(this.referenceLines)
.enter()
.append('text')
.attr('id', d => d.referenceID + '-label')
.attr('class', 'bar-reference-line-label')
.attr('text-anchor', 'middle')
.attr('x', d => this.x(d.referenceData.referenceValue))
.attr('y', d => ((d.referenceData.labelPlacementVertical || 'top') === 'top' ? 0 : this.innerPaddedHeight))
.attr('dy', d => ((d.referenceData.labelPlacementVertical || 'top') === 'top' ? '-0.3em' : '1em'))
.text(d => d.referenceData.labelValue)
.style('fill', d => d.referenceData.strokeColor);
}
this.rootG.exit().remove();
}
}
onClickHandler(d) {
this.clickFunc.emit(d);
}
onHoverHandler(d) {
this.hoverFunc.emit(d);
if (this.showTooltip) {
this.eventsTooltip({ data: d, evt: event, isToShow: true });
}
}
onMouseOutHandler() {
this.mouseOutFunc.emit();
if (this.showTooltip) {
this.eventsTooltip({ isToShow: false });
}
}
// set initial style (instead of copying css class across the lib)
setTooltipInitialStyle() {
initTooltipStyle(this.tooltipG);
}
// tooltip
eventsTooltip({ data, evt, isToShow }: { data?: any; evt?: any; isToShow: boolean }) {
drawTooltip({
root: this.tooltipG,
data,
event: evt,
isToShow,
tooltipLabel: undefined,
xAxis: this.xAxis,
yAxis: this.yAxis,
dataLabel: this.dataLabel,
layout: this.layout,
ordinalAccessor: this.ordinalAccessor,
valueAccessor: this.valueAccessor,
chartType: 'bar'
});
}
render() {
// console.log('pareto-chart render', this.data)
const theme = 'light';
return (
<div class={`o-layout is--${this.layout} ${theme}`}>
<div class="o-layout--chart">
<h1 class="visa-ui-header--4">{this.mainTitle}</h1>
<p class="visa-ui-text--instructions">{this.subTitle}</p>
<div class="pareto-tooltip vcl-tooltip" style={{ display: this.showTooltip ? 'block' : 'none' }} />
<div id="visa-viz-d3-pareto-container" />
</div>
</div>
);
}
}
// incorporate OSS licenses into build
window['VisaChartsLibOSSLicenses'] = getLicenses(); // tslint:disable-line no-string-literal | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
import {Role} from "./index";
/**
* Provides an IAM instance profile.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const role = new aws.iam.Role("role", {
* path: "/",
* assumeRolePolicy: `{
* "Version": "2012-10-17",
* "Statement": [
* {
* "Action": "sts:AssumeRole",
* "Principal": {
* "Service": "ec2.amazonaws.com"
* },
* "Effect": "Allow",
* "Sid": ""
* }
* ]
* }
* `,
* });
* const testProfile = new aws.iam.InstanceProfile("testProfile", {role: role.name});
* ```
*
* ## Import
*
* Instance Profiles can be imported using the `name`, e.g.
*
* ```sh
* $ pulumi import aws:iam/instanceProfile:InstanceProfile test_profile app-instance-profile-1
* ```
*/
export class InstanceProfile extends pulumi.CustomResource {
/**
* Get an existing InstanceProfile resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: InstanceProfileState, opts?: pulumi.CustomResourceOptions): InstanceProfile {
return new InstanceProfile(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:iam/instanceProfile:InstanceProfile';
/**
* Returns true if the given object is an instance of InstanceProfile. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is InstanceProfile {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === InstanceProfile.__pulumiType;
}
/**
* ARN assigned by AWS to the instance profile.
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* Creation timestamp of the instance profile.
*/
public /*out*/ readonly createDate!: pulumi.Output<string>;
/**
* Name of the instance profile. If omitted, this provider will assign a random, unique name. Conflicts with `namePrefix`. Can be a string of characters consisting of upper and lowercase alphanumeric characters and these special characters: `_`, `+`, `=`, `,`, `.`, `@`, `-`. Spaces are not allowed.
*/
public readonly name!: pulumi.Output<string>;
/**
* Creates a unique name beginning with the specified prefix. Conflicts with `name`.
*/
public readonly namePrefix!: pulumi.Output<string | undefined>;
/**
* Path to the instance profile. For more information about paths, see [IAM Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) in the IAM User Guide. Can be a string of characters consisting of either a forward slash (`/`) by itself or a string that must begin and end with forward slashes. Can include any ASCII character from the ! (\u0021) through the DEL character (\u007F), including most punctuation characters, digits, and upper and lowercase letters.
*/
public readonly path!: pulumi.Output<string | undefined>;
/**
* Name of the role to add to the profile.
*/
public readonly role!: pulumi.Output<string | undefined>;
/**
* Map of resource tags for the IAM Instance Profile. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* [Unique ID][1] assigned by AWS.
*/
public /*out*/ readonly uniqueId!: pulumi.Output<string>;
/**
* Create a InstanceProfile resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: InstanceProfileArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: InstanceProfileArgs | InstanceProfileState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as InstanceProfileState | undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["createDate"] = state ? state.createDate : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["namePrefix"] = state ? state.namePrefix : undefined;
inputs["path"] = state ? state.path : undefined;
inputs["role"] = state ? state.role : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["uniqueId"] = state ? state.uniqueId : undefined;
} else {
const args = argsOrState as InstanceProfileArgs | undefined;
inputs["name"] = args ? args.name : undefined;
inputs["namePrefix"] = args ? args.namePrefix : undefined;
inputs["path"] = args ? args.path : undefined;
inputs["role"] = args ? args.role : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["arn"] = undefined /*out*/;
inputs["createDate"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
inputs["uniqueId"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(InstanceProfile.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering InstanceProfile resources.
*/
export interface InstanceProfileState {
/**
* ARN assigned by AWS to the instance profile.
*/
arn?: pulumi.Input<string>;
/**
* Creation timestamp of the instance profile.
*/
createDate?: pulumi.Input<string>;
/**
* Name of the instance profile. If omitted, this provider will assign a random, unique name. Conflicts with `namePrefix`. Can be a string of characters consisting of upper and lowercase alphanumeric characters and these special characters: `_`, `+`, `=`, `,`, `.`, `@`, `-`. Spaces are not allowed.
*/
name?: pulumi.Input<string>;
/**
* Creates a unique name beginning with the specified prefix. Conflicts with `name`.
*/
namePrefix?: pulumi.Input<string>;
/**
* Path to the instance profile. For more information about paths, see [IAM Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) in the IAM User Guide. Can be a string of characters consisting of either a forward slash (`/`) by itself or a string that must begin and end with forward slashes. Can include any ASCII character from the ! (\u0021) through the DEL character (\u007F), including most punctuation characters, digits, and upper and lowercase letters.
*/
path?: pulumi.Input<string>;
/**
* Name of the role to add to the profile.
*/
role?: pulumi.Input<string | Role>;
/**
* Map of resource tags for the IAM Instance Profile. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* [Unique ID][1] assigned by AWS.
*/
uniqueId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a InstanceProfile resource.
*/
export interface InstanceProfileArgs {
/**
* Name of the instance profile. If omitted, this provider will assign a random, unique name. Conflicts with `namePrefix`. Can be a string of characters consisting of upper and lowercase alphanumeric characters and these special characters: `_`, `+`, `=`, `,`, `.`, `@`, `-`. Spaces are not allowed.
*/
name?: pulumi.Input<string>;
/**
* Creates a unique name beginning with the specified prefix. Conflicts with `name`.
*/
namePrefix?: pulumi.Input<string>;
/**
* Path to the instance profile. For more information about paths, see [IAM Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) in the IAM User Guide. Can be a string of characters consisting of either a forward slash (`/`) by itself or a string that must begin and end with forward slashes. Can include any ASCII character from the ! (\u0021) through the DEL character (\u007F), including most punctuation characters, digits, and upper and lowercase letters.
*/
path?: pulumi.Input<string>;
/**
* Name of the role to add to the profile.
*/
role?: pulumi.Input<string | Role>;
/**
* Map of resource tags for the IAM Instance Profile. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
} | the_stack |
export const wrapper: XELib;
/**
* Handles are distinguished from `number`.
*
* They are only meaninful to xelib and one should not pass arbitrary numbers.
*/
export type Handle = number & { __xelib_handle__: never };
/**
* A type which can either be a `Handle` type or `0`.
*
* In most cases `0` means "all files", "not found", etc.
*/
export type Zeroable<H extends Handle> = H | 0;
// Distinguish types of handles
/**
* Handle to an Element
*/
export type ElementHandle = Handle & { __xelib_element__: never };
/**
* Handle to a Container
*/
export type ContainerHandle = Handle & { __xelib_container__: never };
/**
* Handle to a file
*/
export type FileHandle = ContainerHandle & { __xelib_file__: never };
/**
* Handle to a Record
*/
export type RecordHandle = ElementHandle & { __xelib_record__: never };
/**
* Handle to node tree
* @see GetNodes
*/
export type NodeTreeHandle = Handle & { __xelib_nodetree__: never };
/**
* Sort modes that can be used with SetSortMode.
* @see SetSortMode
*/
export enum SortMode {
/**
* No sorting.
* Elements will be in native order corresponding to the order in which they were found in the plugin file they were loaded from.
*/
None = 0,
/**
* Files are sorted by load order,
* groups are sorted by signature,
* and records are sorted by FormID
*/
FormID = 1,
/**
* Files are sorted by filename,
* groups are sorted by display name,
* and record are sorted by their EditorID.
*/
EditorID = 2,
/**
* Files are sorted by filename,
* groups are sorted by display name,
* and records are sorted by their FULL name.
*/
Name = 3,
}
/**
* States returned by GetLoaderStatus.
* @see GetLoaderStatus
*/
export enum LoaderState {
/**
* Indicates the loader hasn't been run and isn't running.
*/
IsInactive = 0,
/**
* Indicates the loader is currently active.
*/
IsActive = 1,
/**
* Indicates the loader is done.
*/
IsDone = 2,
/**
* Indicates the loader encountered an error.
*/
IsError = 3,
}
/**
* Game modes for use with SetGameMode.
* @see SetGameMode
*/
export enum GameMode {
/**
* Fallout: New Vegas
*/
gmFNV = 0,
/**
* Fallout 3
*/
gmFO3 = 1,
/**
* The Elder Scrolls IV: Oblivion
*/
gmTES4 = 2,
/**
* The Elder Scrolls V: Skyrim
*/
gmTES5 = 3,
/**
* Skyrim: Special Edition
*/
gmSSE = 4,
/**
* Fallout 4
*/
gmFO4 = 5,
}
/**
* Object corresponding to a supported game mode.
*/
export interface Game {
/**
* The name of the game used for display purposes.
*/
name: string;
/**
* The name of the game used to find the correct Hardcoded.dat file.
*/
shortName: string;
/**
* The game mode for the game.
*/
mode: GameMode;
/**
* The filename of the game executable.
*/
exeName: string;
}
/**
* @see BuildArchive
*/
export enum ArchiveType {
/**
* Unused.
*/
baNone = 0,
/**
* Used for Morrowind archives.
*/
baTES3 = 1,
/**
* Used for Fallout 3, Oblivion, and Skyrim Classic archives.
*/
baFO3 = 2,
/**
* Used for Skyrim: Special Edition archives.
*/
baSSE = 3,
/**
* Used for Fallout 4 archives.
*/
baFO4 = 4,
/**
* Used for Fallout 4 texture archives.
*/
baFO4dds = 5,
}
/**
* @see XELib.ElementType
*/
export enum ElementType {
etFile = 0,
etMainRecord = 1,
etGroupRecord = 2,
etSubRecord = 3,
etSubRecordStruct = 4,
etSubRecordArray = 5,
etSubRecordUnion = 6,
etArray = 7,
etStruct = 8,
etValue = 9,
etFlag = 10,
etStringListTerminator = 11,
etUnion = 12,
etStructChapter = 13,
}
/**
* @see XELib.DefType
*/
export enum DefType {
dtSubRecord = 1,
dtSubRecordArray = 2,
dtSubRecordStruct = 3,
dtSubRecordUnion = 4,
dtString = 5,
dtLString = 6,
dtLenString = 7,
dtByteArray = 8,
dtInteger = 9,
dtIntegerFormater = 10,
dtIntegerFormaterUnion = 11,
dtFlag = 12,
dtFloat = 13,
dtArray = 14,
dtStruct = 15,
dtUnion = 16,
dtEmpty = 17,
dtStructChapter = 18,
}
/**
* Used by Smash.
* @see XELib.SmashType
*/
export enum SmashType {
stUnknown = 0,
stRecord = 1,
stString = 2,
stInteger = 3,
stFlag = 4,
stFloat = 5,
stStruct = 6,
stUnsortedArray = 7,
stUnsortedStructArray = 8,
stSortedArray = 9,
stSortedStructArray = 10,
stByteArray = 11,
stUnion = 12,
}
/**
* Used to determine what form to use when the user is editing values.
* @see XELib.ValueType
*/
export enum ValueType {
vtUnknown = 0,
vtBytes = 1,
vtNumber = 2,
vtString = 3,
vtText = 4,
vtReference = 5,
vtFlags = 6,
vtEnum = 7,
vtColor = 8,
vtArray = 9,
vtStruct = 10,
}
/**
* Corresponds to the conflict status of an individual element.
* @see XELib.ConflictThis
*/
export enum ConflictThis {
ctUnknown = 0,
ctIgnored = 1,
ctNotDefined = 2,
ctIdenticalToMaster = 3,
ctOnlyOne = 4,
ctHiddenByModGroup = 5,
ctMaster = 6,
ctConflictBenign = 7,
ctOverride = 8,
ctIdenticalToMasterWinsConflict = 9,
ctConflictWins = 10,
ctConflictLoses = 11,
}
/**
* Corresponds to the overall conflict status of an element.
* @see XELib.ConflictAll
*/
export enum ConflictAll {
caUnknown = 0,
caOnlyOne = 1,
caNoConflict = 2,
caConflictBenign = 3,
caOverride = 4,
caConflict = 5,
caConflictCritical = 6,
}
/**
* Options that can be passed to GetREFRs.
* @see GetREFRs
*/
export interface GetREFRsOptions {
/**
* Pass true to exclude deleted REFRs.
* @default false
*/
excludeDeleted?: boolean | undefined;
/**
* Pass true to exclude disabled REFRs.
* @default false
*/
excludeDisabled?: boolean | undefined;
/**
* Pass true to exclude REFRs which have an XESP element.
* @default false
*/
excludeXESP?: boolean | undefined;
}
export interface Vector {
X?: number | undefined;
Y?: number | undefined;
Z?: number | undefined;
}
/**
* Identity utility type
*
* So I can "extend" the typeof an enum
* @internal
*/
export type I<T> = T;
/**
* API for xelib wrapper
*/
export interface XELib
extends I<typeof LoaderState>,
I<typeof GameMode>,
I<typeof ArchiveType>,
I<typeof ElementType>,
I<typeof DefType>,
I<typeof SmashType>,
I<typeof ValueType>,
I<typeof ConflictThis>,
I<typeof ConflictAll> {
/**
* Meta functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FMeta}
*/
/**
* @see SortMode
*/
sortBy: typeof SortMode;
/**
* Initializes XEditLib.
* This should be called after the DLL loaded to prepare the library for future function calls.
*
* @param dllPath Path to XEditLib.dll
*/
Initialize(dllPath: string): void;
/**
* Finalizes XEditLib.
* This should be called just before the DLL is unloaded to rename saved files, save logs, and free all memory used by the library.
*/
Finalize(): void;
/**
* Gets the value of a global from the library. Supported globals include:
*
* - ProgramPath: The path to the folder containing XEditLib.dll.
* - Version: The version of XEditLib.dll.
* - GameName: The short game name associated with the current game mode.
* - AppName: The abbreviated game name associated with the current game mode.
* - LongGameName: The full game name associated with the current game mode.
* - DataPath: The game data path associated with the current game mode.
* - AppDataPath: The game application data path associated with the current game mode.
* - MyGamesPath: The my games folder path associated with the current game mode.
* - GameIniPath: The path to the INI file associated with the current game mode.
*/
GetGlobal(key: string): string;
/**
* Returns a list of name value pairs for all globals.
* Entries are separated by \r\n, and name value pairs are separated by =.
*/
GetGlobals(): string;
/**
* Sets the sort mode to be used by GetElements when the sort argument is set to true.
* @see GetElements
* @see SortMode
*/
SetSortMode(mode: keyof typeof SortMode, reverse: boolean): void;
/**
* Releases the input handle if it is allocated.
*/
Release(id: Handle): void;
/**
* Releases the input handle if it is allocated.
* For use with handles returned by GetNodes.
* @see GetNodes
*/
ReleaseNodes(id: Handle): void;
/**
* Finds other handles to a particular interface.
*/
GetDuplicateHandles(id: Handle): Handle[];
/**
* Message functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FMessages}
*/
/**
* Gets any messages that have been added to XEditLib's internal log
* since the last time this function was called.
*/
GetMessages(): string;
/**
* Clears all messages from the XEditLib's internal log.
*/
ClearMessages(): void;
/**
* Returns a message corresponding to the last exception that occurred.
* Returns an empty string if no exception has occurred since the last time this function was called.
*/
GetExceptionMessage(): string;
/**
* Setup functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FSetup}
*/
/**
* @see LoaderState
*/
loaderStates: typeof LoaderState;
/**
* @see GameMode
*/
gameModes: typeof GameMode;
/**
* Array of game objects corresponding to each supported game mode.
*/
games: readonly Game[];
/**
* Retrieves the path to the game corresponding to gameMode from the registry.
* Returns an empty string if the game path cannot be found.
* @see GameMode
*/
GetGamePath(gameMode: GameMode): string;
/**
* Sets the game path to be used when loading plugin and resource files to gamePath.
*/
SetGamePath(gamePath: string): void;
/**
* Retrieves the the language used for gameMode from the game INI file.
* Returns an empty string if the game INI file cannot be found.
* @see GameMode
*/
GetGameLanguage(gameMode: GameMode): string;
/**
* Sets the language to be used when loading string files to language.
*/
SetLanguage(language: string): void;
/**
* Sets the game mode to gameMode.
* @see GameMode
*/
SetGameMode(gameMode: GameMode): void;
/**
* Returns the user's load order determined from loadorder.txt, plugins.txt, or plugin dates depending on the game and available files.
* The load order is returned as a list of filenames separated by \r\n.
*/
GetLoadOrder(): string;
/**
* Returns the user's active plugins determined from plugins.txt.
* Active plugins are returned as a list of filenames separated by \r\n.
*/
GetActivePlugins(): string;
/**
* Loads plugin files in loadOrder.
* If smartLoad is set to true, master files required by files in loadOrder will be automatically loaded as necessary.
* Plugin loading is performed in a background thread, use GetLoaderStatus to track the loader and determine when it is done.
* @see GetLoaderStatus
*/
LoadPlugins(
loadOrder: string,
/**
* @default true
*/
smartLoad?: boolean,
): void;
/**
* Loads the plugin file filename at the next available load order position after currently loaded plugins files.
* Plugin loading is performed in a background thread, use GetLoaderStatus to track the loader and determine when it is done.
* @see GetLoaderStatus
*/
LoadPlugin(filename: string): void;
/**
* Loads the header of plugin file filename and returns a handle to it.
* This plugin should be unloaded with UnloadPlugin once you're done with it.
* Note: Unlike LoadPlugin, this function does not use a background thread.
* @see UnloadPlugin
*/
LoadPluginHeader(filename: string): FileHandle;
/**
* Builds referenced by information for the plugin file id.
* If id is 0 reference information will be built for all loaded plugins.
*/
BuildReferences(id: Zeroable<FileHandle>, sync: boolean): void;
/**
* Unloads the plugin file id.
* Only plugins at the end of the active load order which have not have references built can be unloaded.
* Plugin headers loaded with LoadPluginHeader can also be unloaded.
*/
UnloadPlugin(id: FileHandle): void;
/**
* Returns the status of the loader.
* @see LoaderState
*/
GetLoaderStatus(): LoaderState;
/**
* Returns an array of all loaded filenames.
* Excludes hardcoded files if excludeHardcoded is true.
*/
GetLoadedFileNames(excludeHardcoded: boolean): string[];
/**
* Resource functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FResources}
*/
/**
* @see ArchiveType
*/
archiveTypes: typeof ArchiveType;
/**
* Extracts container name to destination, replacing existing files if replace is true.
* Returns true if the container is extracted successfully.
*/
ExtractContainer(name: string, destination: string, replace: boolean): boolean;
/**
* Extracts file source from container name to destination.
* Returns true if the file is extracted successfully.
*/
ExtractFile(name: string, source: string, destination: string): boolean;
/**
* Returns an array of the file paths in container name in folder.
*/
GetContainerFiles(name: string, folder: string): string[];
/**
* Returns the name of the container where the winning version of the file path is stored.
*/
GetFileContainer(path: string): string;
/**
* Returns an array of the names of the currently loaded containers.
*/
GetLoadedContainers(): string[];
/**
* Loads the container at filePath.
* Returns true if the container is loaded succesfully.
*/
LoadContainer(filePath: string): boolean;
/**
* Creates a new archive name in folder containing files at the filePaths relative to folder.
* Uses archive type archiveType.
* Compresses the archive if compress is true and packs data if share is true.
* Pass a hexadecimal integer as a string to af or ff to set custom archive flags or file flags, respectively.
* @see ArchiveType
*/
BuildArchive(
name: string,
folder: string,
filePaths: string,
archiveType: ArchiveType,
compress: boolean,
share: boolean,
af: string,
ff: string,
): void;
/**
* Return the pixel image data for the texture resource resourceName.
*/
GetTextureData(resourceName: string): ImageData;
/**
* Element functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FElements}
*/
/**
* @see ElementType
*/
elementTypes: typeof ElementType;
/**
* @see DefType
*/
defTypes: typeof DefType;
/**
* @see SmashType
*/
smashTypes: typeof SmashType;
/**
* @see ValueType
*/
valueTypes: typeof ValueType;
/**
* Returns true if an element exists at the given path.
*/
HasElement(id: Zeroable<Handle>, path: string): boolean;
/**
* Resolves the element at path and returns a handle to it.
* Returns 0 if the element is not found.
*/
GetElement(id: Zeroable<Handle>, path: string): Zeroable<ElementHandle>;
/**
* Traverses path, creating any elements that are not found.
* Returns a handle to the element at the end of the path.
*/
AddElement(id: Zeroable<Handle>, path: string): ElementHandle;
/**
* Traverses path, creating any elements that are not found.
* Sets the value of the element at the end of the path to value, and returns a handle to it.
*/
AddElementValue(id: Zeroable<Handle>, path: string, value: string): ElementHandle;
/**
* Removes the element at path if it exists.
*/
RemoveElement(id: Zeroable<Handle>, path: string): void;
/**
* Removes the element id.
* If the element cannot be removed it gets its parent container and attempts to remove it.
* This repeats until the container can be removed or the code reaches a main record.
*/
RemoveElementOrParent(id: ElementHandle): void;
/**
* Assigns id2 to id.
* This is equivalent to drag and drop.
*/
SetElement(id: ElementHandle, id2: ElementHandle): void;
/**
* Returns an array of handles for all of the elements found in the container at path.
*/
GetElements(id: Zeroable<ContainerHandle>, path: string): ElementHandle[];
/**
* Returns an array of the names of all elements that can exist at path.
*/
GetDefNames(id: Zeroable<Handle>, path: string): string[];
/**
* Returns an array of the signatures that can be added to id.
*/
GetAddList(id: Handle): string[];
/**
* Returns the record referenced by the element at path.
* Note: this returns the master of the record, not the winning override.
*/
GetLinksTo(id: Zeroable<Handle>, path: string): RecordHandle;
/**
* Sets the record referenced by the element at path to id2.
*/
SetLinksTo(id: Handle, id2: Zeroable<RecordHandle>, path: string): void;
/**
* Returns a handle to the container of id.
* Returns 0 on failure.
*/
GetContainer(id: Handle): Zeroable<ContainerHandle>;
/**
* Returns a handle to the file id belongs to.
*/
GetElementFile(id: ElementHandle): FileHandle;
/**
* Returns the number of element children id has.
*/
ElementCount(id: Handle): number;
/**
* Returns true if id and id2 refer to the same element.
*/
ElementEquals(id: ElementHandle, id2: ElementHandle): boolean;
/**
* Returns true if the value at path matches value.
* When the element at path contains a reference, value can be a Form ID, Editor ID, or FULL Name.
* FULL Names passed to this function must be surrounded by double quotes.
*/
ElementMatches(id: Zeroable<Handle>, path: string, value: string): boolean;
/**
* Returns true if the array at path contains an item which matches value at subpath.
*/
HasArrayItem(id: Zeroable<Handle>, path: string, subpath: string, value: string): boolean;
/**
* Returns the first item in the array at path which matches value at subpath.
* Returns 0 if no matching element is found.
*/
GetArrayItem(id: Zeroable<Handle>, path: string, subpath: string, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the array at path and sets value at subpath.
* @returns Handle to the added array item.
*/
AddArrayItem(id: Zeroable<Handle>, path: string, subpath: string, value: string): ElementHandle;
/**
* Removes the first item in the array at path which matches value at subpath.
*/
RemoveArrayItem(id: Zeroable<Handle>, path: string, subpath: string, value: string): void;
/**
* Moves the array item id to position index.
*/
MoveArrayItem(id: ElementHandle, index: number): void;
/**
* Copies element id into id2.
* Records are copied as overrides if asNew is false.
* @returns Handle to the copied element.
*/
CopyElement(id: ElementHandle, id2: ContainerHandle, asNew: boolean): ElementHandle;
/**
* @returns true if id is allowed to reference signature.
*/
GetSignatureAllowed(id: Handle, signature: string): boolean;
/**
* @returns Array of all signatures id is allowed to reference.
*/
GetAllowedSignatures(id: Handle): string[];
/**
* @returns true if id has been modified during the current session.
*/
GetIsModified(id: Handle): boolean;
/**
* @returns true if id has can be edited.
*/
GetIsEditable(id: Handle): boolean;
/**
* @returns true if id can be removed.
*/
GetIsRemoveable(id: Handle): boolean;
/**
* @returns true if elements can be added to id.
*/
GetCanAdd(id: Handle): boolean;
/**
* @returns the elementType of id.
*/
ElementType(id: ElementHandle): ElementType;
/**
* @returns id's element type.
*/
DefType(id: ElementHandle): DefType;
/**
* @returns id's definition type.
*/
SmashType(id: ElementHandle): SmashType;
/**
* @returns id's value type.
*/
ValueType(id: ElementHandle): ValueType;
/**
* @returns true if id is a sorted array.
*/
IsSorted(id: ElementHandle): boolean;
/**
* @returns true if id contains flags.
*/
IsFlags(id: ElementHandle): boolean;
/**
* Element value functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FElement_Values}
*/
/**
* Note: This is not the same as XEdit's Name function - LongName is.
* @returns The name of id.
*/
Name(id: Handle): string;
/**
* Identical to the Name function from XEdit scripting.
*/
LongName(id: Handle): string;
/**
* @returns the name of id used for display purposes in ZEdit's user interface.
*/
DisplayName(id: Handle): string;
/**
* All paths returned from this function can be used with GetElement.
* @returns The path to id.
* @see GetElement
*/
Path(id: Handle): string;
/**
* All paths returned from this function can be used with GetElement.
* @returns Fully qualified path to id.
* @see GetElement
*/
LongPath(id: Handle): string;
/**
* All paths returned from this function can be used with GetElement.
* @returns Path of id within its parent record.
* @see GetElement
*/
LocalPath(id: Handle): string;
/**
* @returns The signature of id.
*/
Signature(id: Handle): string;
/**
* @returns The sort key of id.
*/
SortKey(id: Handle): string;
/**
* This is the same value displayed in the record view.
* @returns the editor value at path.
* @returns an empty string if path does not exist.
*/
GetValue(id: Zeroable<Handle>, path: string): string;
/**
* Sets the editor value at path to value.
* This is the same value displayed in the record view.
*/
SetValue(id: Zeroable<Handle>, path: string, value: string): void;
/**
* @returns The native integer value at path.
* @returns 0 if path does not exist.
*/
GetIntValye(id: Zeroable<Handle>, path: string): number;
/**
* Sets the native integer value at path to value.
*/
SetIntValue(id: Zeroable<Handle>, path: string, value: number): void;
/**
* @returns The native unsigned integer value at path.
* @returns 0 if path does not exist.
*/
GetUIntValue(id: Zeroable<Handle>, path: string): number;
/**
* Sets the native unsigned integer value at path to value.
*/
SetUIntValue(id: Zeroable<Handle>, path: string, value: number): void;
/**
* @returns The native float value at path.
* @returns 0.0 if path does not exist.
*/
GetFloatValue(id: Zeroable<Handle>, path: string): number;
/**
* Sets the native float value at path to value.
*/
SetFloatValue(id: Zeroable<Handle>, path: string, value: number): void;
/**
* Resolves the flags element at path, and sets flag name to state.
*/
SetFlag(id: Zeroable<Handle>, path: string, name: string, state: boolean): void;
/**
* Resolves the flags element at path, and gets the state of flag name.
*/
GetFlag(id: Zeroable<Handle>, path: string, name: string): boolean;
/**
* Resolves the flags element at path and returns an array of the names of the enabled flags on it.
*/
GetEnabledFlags(id: Zeroable<Handle>, path: string): string[];
/**
* Resolves the flags element at path and sets the enabled flags to flags.
* Note: This disables any active flags that are not in flags.
*/
SetEnabledFlags(id: Zeroable<Handle>, path: string, flags: readonly string[]): void;
/**
* Resolves the flags element at path and returns an array of the names of all of the flags it supports.
* Flag positions in the array indicate the binary bits they corresponds to.
*/
GetAllFlags(id: Zeroable<Handle>, path: string): string[];
/**
* Resolves the enumeration element at path and returns an array of the options it supports.
* Enumeration positions in the array indicate the binary bits they corresponds to.
*/
GetEnumOptions(id: Zeroable<Handle>, path: string): string[];
/**
* File functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FFiles}
*/
/**
* Creates a new file filename.
* @returns Handle to the file
*/
AddFile(filename: string): FileHandle;
/**
* Resolves the file with load order loadOrder and returns a handle to it.
* Returns 0 if a matching file is not found.
*/
FileByLoadOrder(loadOrder: number): Zeroable<FileHandle>;
/**
* Resolves the file with name equal to filename and returns a handle to it.
* Returns 0 if a matching file is not found.
*/
FileByName(filename: string): Zeroable<FileHandle>;
/**
* Resolves the file with author equal to author and returns a handle to it.
* Returns 0 if a matching file is not found.
*/
FileByAuthor(author: string): Zeroable<FileHandle>;
/**
* Removes all records and groups in file id.
*/
NukeFile(id: FileHandle): void;
/**
* Renames file id to newFileName.
*/
RenameFile(id: FileHandle): void;
/**
* Saves file to filePath.
* Passing an empty string for filePath indicates the file should be saved in the game data folder to {filename}.esp.
*/
SaveFile(id: FileHandle, filePath: string): void;
/**
* @returns Number of records in file id.
*/
GetRecordCount(id: FileHandle): number;
/**
* @returns Number of override records in file id.
*/
GetOverrideRecordCount(id: FileHandle): number;
/**
* @returns MD5 Hash of file id.
*/
MD5Hash(id: FileHandle): string;
/**
* @returns CRC Hash of file id.
*/
CRCHash(id: FileHandle): string;
/**
* @returns Load order of file id.
*/
GetFileLoadOrder(id: FileHandle): number;
/**
* @returns Handle to the file header of file id.
*/
GetFileHeader(id: FileHandle): Handle;
/**
* File value functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FFile_Values}
*/
/**
* @returns Next Object ID of file id.
*/
GetNextObjecID(id: FileHandle): number;
/**
* Sets the Next Object ID of file id to nextObjectID.
*/
SetNextObjectID(id: FileHandle, nextObjectID: number): void;
/**
* This is equivalent to calling Name(id).
* @returns File name of file id.
*/
GetFileName(id: FileHandle): string;
/**
* @returns Author of file id.
*/
GetFileAuthor(id: FileHandle): string;
/**
* Sets the author of file id to author.
*/
SetFileAuthor(id: FileHandle, author: string): void;
/**
* @returns Description of file id.
*/
GetFileDescription(id: FileHandle): string;
/**
* Sets the description of file id to description.
*/
SetFileDescription(id: FileHandle, description: string): void;
/**
* @returns State of the ESM flag on file id.
*/
GetIsESM(id: FileHandle): boolean;
/**
* Sets the the state of the ESM flag on file id to state.
*/
SetIsESM(id: FileHandle, state: boolean): void;
/**
* Record functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FRecords}
*/
/**
* @see ConflictThis
*/
conflictThis: typeof ConflictThis;
/**
* @see ConflictAll
*/
conflictAll: typeof ConflictAll;
/**
* @returns Form ID of the record id.
*/
GetFormID(id: RecordHandle, native?: boolean, local?: boolean): number;
/**
* @returns Form ID of the record id as a hexadecimal string.
*/
GetHexFormID(id: RecordHandle, native?: boolean, local?: boolean): string;
/**
* Set the form ID of the record id.
* @returns Form ID of the record id as a hexadecimal string.
*/
SetFormID(id: RecordHandle, newFormID: number, native?: boolean, fixReferences?: boolean): string;
/**
* Pass 0 as id and a load order formID to perform a lookup by load order form ID.
* Pass a file handle as id and a file formID to perform a lookup by native (file) form ID.
* @returns Handle to the record matching formID in id.
*/
GetRecord(id: Zeroable<FileHandle>, formID: number): RecordHandle;
/**
* Pass 0 for id to search all loaded files.
* @returns Array of all records matching search found in id.
*/
GetRecords(
id: Zeroable<FileHandle>,
search: string,
/**
* @default false
*/
includeOverrides?: boolean,
): RecordHandle[];
/**
* @returns Array of all REFR records referencing base records with signatures in search found within id.
* @see GetREFRsOptions
*/
GetREFRs(id: Handle, search: string, opts?: GetREFRsOptions): RecordHandle[];
/**
* @returns Array of handles corresponding to the overrides of record id.
*/
GetOverrides(id: RecordHandle): RecordHandle[];
/**
* @returns Handle for the master record of id.
* @returns New handle to record id if it is a master record.
*/
GetMasterRecord(id: RecordHandle): RecordHandle;
/**
* @returns Handle for the winning override of record id in the masters of file id2.
*/
GetPreviousOverride(id: RecordHandle, id2: FileHandle): RecordHandle;
/**
* @returns Handle for the winning override of record id.
*/
GetWinningOverride(id: RecordHandle): RecordHandle;
/**
* @returns Handle for the file that record id is injected into.
*/
GetInjectionTarget(id: RecordHandle): FileHandle;
/**
* @returns Next record after id which matches search.
* @returns 0 if no match is found.
*/
FindNextRecord(id: Handle, search: string, byEdid: boolean, byName: boolean): Zeroable<RecordHandle>;
/**
* @returns Previous record after id which matches search.
* @returns 0 if no match is found.
*/
FindPreviousRecord(id: Handle, search: string, byEdid: boolean, byName: boolean): Zeroable<RecordHandle>;
/**
* Excludes results which do not contain search in their LongName.
* @returns Up to limitTo records matching signature which can be referenced by the file containing id.
*/
FindValidReferences(id: FileHandle, signature: string, search: string, limitTo: number): string[];
/**
* References must be built with xelib.BuildReferences to be returned.
* @returns Array of the records that reference record id.
*/
GetReferencedBy(id: RecordHandle): RecordHandle[];
/**
* Exchanges all references to oldFormID with references to newFormID on record id.
*/
ExchangeReferences(id: RecordHandle, oldFormID: number, newFormID: number): void;
/**
* @returns true if record id is a master record.
*/
IsMaster(id: RecordHandle): boolean;
/**
* @returns true if record id is an injected record.
*/
IsInjected(id: RecordHandle): boolean;
/**
* @returns true if record id is an override record.
*/
IsOverride(id: RecordHandle): boolean;
/**
* @returns true if record id is a winning override record.
*/
IsWinningOverride(id: RecordHandle): boolean;
/**
* The handle returned by this function must be freed with xelib.ReleaseNodes.
* NOTE: Can be slow for very large records like NAVI.
* @returns Handle pointing to a node tree for rec.
* @see ReleaseNodes
*/
GetNodes(rec: RecordHandle): NodeTreeHandle;
/**
* Pass a handle for a node tree retrieved using GetNodes for nodes if you plan on calling this function for more than one element from the same record.
* NOTE: Can be slow for very large records like NAVI.
* @returns ConflictAll and ConflictThis values for element.
*/
GetConflictData(
nodes: Zeroable<NodeTreeHandle>,
element: ElementHandle,
asString: true,
): [keyof typeof ConflictAll, keyof typeof ConflictThis];
GetConflictData(
nodes: Zeroable<NodeTreeHandle>,
element: ElementHandle,
asString?: false,
): [ConflictAll, ConflictThis];
/**
* You must pass a handle for a node tree retrieved using GetNodes to nodes.
* Note that this is different from xelib.GetElements in that it returns an array with null handles in it as placeholders for unassigned elements.
* @returns Handles for the element children of element.
* @see GetNodes
* @see GetElements
*/
GetNodeElements(nodes: NodeTreeHandle, element: ElementHandle): Array<Zeroable<ElementHandle>>;
/**
* Record value functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FRecord_Values}
*/
/**
* @returns Editor ID of record id.
* @returns Empty string if the record does not have an editor ID.
*/
EditorID(id: RecordHandle): string;
/**
* @returns FULL name of record id.
* @returns Empty string if the record does not have an FULL name.
*/
FullName(id: RecordHandle): string;
/**
* Translates record id by vector.
*/
Translate(id: RecordHandle, vector: Vector): void;
/**
* Rotates record id by vector degrees.
*/
Rotate(id: RecordHandle, vector: Vector): void;
/**
* Gets the state of record flag name on record id.
*/
GetRecordFlag(id: RecordHandle, name: string): boolean;
/**
* Sets record flag name on record id to state.
*/
SetRecordFlag(id: RecordHandle, name: string, state: boolean): void;
/**
* @returns true if the `Keywords` array on `record` has an element matching `value`.
*/
HasKeyword(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Keywords` array on `record` matching `value`.
* @returns Handle to the element if found, else returns 0.
*/
GetKeyword(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Keywords` array on `record`.
* @returns Handle to the added Keyword element.
*/
AddKeyword(record: RecordHandle, value: string): ElementHandle;
/**
* Removes the first item in the `Keywords` array on `record` matching `value`.
*/
RemoveKeyword(record: RecordHandle, value: string): void;
/**
* @returns true if the `FormIDs` array on `record` has an element matching `value`.
*/
HasFormID(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `FormIDs` array on `record` matching `value`.
* @returns Handle to the element if found, else returns 0.
*/
// tslint:disable-next-line adjacent-overload-signatures
GetFormID(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `FormIDs` array on `record`.
* @returns Handle to the added Form ID element.
*/
AddFormID(record: RecordHandle, value: string): ElementHandle;
/**
* Removes the first item in the `FormIDs` array on `record` matching `value`.
*/
RemoveFormID(record: RecordHandle, value: string): void;
/**
* @returns true if the `Music Tracks` array on `record` has an element matching `value`.
*/
HasMusicTrack(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Music Tracks` array on `record` matching `value`.
* @returns Handle to the element if found, else returns 0.
*/
GetMusicTrack(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Music Tracks` array on `record`.
* @returns Handle to the added Music Track element.
*/
AddMusicTrack(record: RecordHandle, value: string): ElementHandle;
/**
* Removes the first item in the `Music Tracks` array on `record` matching `value`.
*/
RemoveMusicTrack(record: RecordHandle, value: string): void;
/**
* @returns true if the `Footstep Sets` array on `record` has an element matching `value`.
*/
HasFootstep(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Footstep Sets` array on `record` matching `value`.
* @returns Handle to the element if found, else returns 0.
*/
GetFootstep(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Footstep Sets` array on `record`.
* @returns Handle to the added Footstep element.
*/
AddFootstep(record: Handle, value: string): ElementHandle;
/**
* Removes the first item in the `Footstep Sets` array on `record` matching `value`.
*/
RemoveFootstep(record: RecordHandle, value: string): void;
/**
* @returns true if the `Additional Races` array on `record` has an element matching `value`.
*/
HasAdditionalRace(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Additional Races` array on `record` matching `value`.
* @returns Handle to the element if found, else returns 0.
*/
GetAdditionalRace(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an value the `Additional Races` array on `record`.
* @returns Handle to the added Additional Race element.
*/
AddAdditionalRace(record: RecordHandle, value: string): ElementHandle;
/**
* Removes the first item in the `Additional Races` array on `record` matching `value`.
*/
RemoveAdditionalRace(record: RecordHandle, value: string): void;
/**
* @returns true if the `Perks` array on `record` has an element matching `value` at path `Perk`.
*/
HasPerk(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Perks` array on `record` matching `value` at path `Perk`.
* @returns Handle to the element if found, else returns 0.
*/
GetPerk(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an value the `Perks` array on `record`,
* setting `Perk` to `value` and `rank` if provided.
* @returns Handle to the added Perk element.
*/
AddPerk(record: RecordHandle, value: string, rank?: string): ElementHandle;
/**
* Removes the first item in the `Perks` array on `record` matching `value` at `Perk`.
*/
RemovePerk(record: RecordHandle, value: string): void;
/**
* @returns true if the `Effects` array on `record` has an element matching `value` at `EFID - Base Effect`.
*/
HasEffect(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Effects` array on `record` matching `value` at `EFID - Base Effect`.
* @returns Handle to the element if found, else returns 0.
*/
GetEffect(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Effects` array on `record`,
* setting `EFID - Base Effect` to `value`,
* `EFIT\Magnitude` to `value2`,
* `EFIT\Area` to `value3`,
* and `EFIT\Duration` to `value4`.
* @returns Handle to the added Effect element.
*/
AddEffect(record: RecordHandle, value: string, value2: string, value3: string, value4: string): ElementHandle;
/**
* Removes the first item in the `Effects` array on `record` matching `value` at `EFID - Base Effect`.
*/
RemoveEffect(record: RecordHandle, value: string): void;
/**
* @returns true if the `Items` array on `record` has an element matching `value` at `CNTO\Item`.
*/
HasItem(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Items` array on `record` matching `value` at `CNTO\Item`.
* @returns Handle to the element if found, else returns 0.
*/
GetItem(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Items` array on `record`,
* setting `CNTO\Item` to `value`, and `CNTO\Count` to `value2`.
* @returns Handle to the added Item element.
*/
AddItem(record: RecordHandle, value: string, value2: string): ElementHandle;
/**
* Removes the first item in the `Items` array on `record` matching `value` at `CNTO\Item`.
*/
RemoveItem(record: RecordHandle, value: string): void;
/**
* @returns true if the `Leveled List Entries` array on `record` has an element matching `value` at `LVLO\Reference`.
*/
HasLeveledEntry(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Leveled List Entries` array on `record` matching `value` at `LVLO\Reference`.
* @returns Handle to the element if found, else returns 0.
*/
GetLeveledEntry(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Leveled List Entries` array on `record`,
* setting `LVLO\Reference` to `value`, `LVLO\Level` to `value2`, and `LVLO\Count` to `value3`.
* @returns Handle to the added LeveledEntry element.
*/
AddLeveledEntry(record: RecordHandle, value: string, value2: string, value3: string): ElementHandle;
/**
* Removes the first item in the `Leveled List Entries` array on `record`
* matching `value` at `LVLO\Reference`.
*/
RemoveLeveledEntry(record: RecordHandle, value: string): void;
/**
* @returns true if the `VMAD\Scripts` array on `record` has an element matching `value` at `scriptName`.
*/
HasScript(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `VMAD\Scripts` array on `record` matching `value` at `scriptName`.
* @returns Handle to the element if found, else returns 0.
*/
GetScript(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `VMAD\Scripts` array on `record`,
* setting `scriptName` to `value`, and `Flags` to `value2`.
* @returns Handle to the added Script element.
*/
AddScript(record: RecordHandle, value: string, value2: string): ElementHandle;
/**
* Removes the first item in the `VMAD\Scripts` array on `record` matching `value` at `scriptName`.
*/
RemoveScript(record: RecordHandle, value: string): void;
/**
* @returns true if the `Properties` array on `scriptElement` has an element matching `value` at `propertyName`.
*/
HasScriptProperty(scriptElement: ElementHandle, value: string): boolean;
/**
* Finds the first item in the `Properties` array on `scriptElement` matching `value` at `propertyName`.
* @returns Handle to the element if found, else returns 0.
*/
GetScriptProperty(scriptElement: ElementHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Properties` array on `scriptElement`,
* setting `propertyName` to `value`, and `CNTO\Count` to `value2`.
* @returns Handle to the added ScriptProperty element.
*/
AddScriptProperty(scriptElement: ElementHandle, value: string, value2: string): ElementHandle;
/**
* Removes the first item in the `Properties` array on `scriptElement` matching `value` at `propertyName`.
*/
RemoveScriptProperty(scriptElement: ElementHandle, value: string): void;
/**
* @returns true if the `Conditions` array on `record` has an element matching `value` at `CTDA\Function`.
*/
HasCondition(record: RecordHandle, value: string): boolean;
/**
* Finds the first item in the `Conditions` array on `record` matching `value` at `CTDA\Function`.
* @returns Handle to the element if found, else returns 0.
*/
GetCondition(record: RecordHandle, value: string): Zeroable<ElementHandle>;
/**
* Adds an item to the `Conditions` array on `record`,
* setting `CTDA\Function` to `value`,
* `CTDA\Type` to `value2`,
* `CTDA\Comparison Value` to `value3`,
* and `CTDA\Parameter #1` to `value4`.
* @returns Handle to the added Condition element.
*/
AddCondition(record: RecordHandle, value: string, value2: string, value3: string, value4: string): ElementHandle;
/**
* Removes the first item in the `Conditions` array on `record` matching `value` at `CTDA\Function`.
*/
RemoveCondition(record: RecordHandle, value: string): void;
/**
* @returns Value at `DATA\Value` on `record`.
*/
GetGoldValue(record: RecordHandle): number;
/**
* Sets the value at `DATA\Value` on `record` to `value`.
*/
SetGoldValue(record: RecordHandle, value: number): void;
/**
* @returns Value at `DATA\Weight` on `record`.
*/
GetWeight(record: RecordHandle): number;
/**
* Sets the value at `DATA\Weight` on `record` to `value`.
*/
SetWeight(record: RecordHandle, value: number): void;
/**
* @returns Value at `DATA\Damage` on `record`.
*/
GetDamage(record: RecordHandle): number;
/**
* Sets the value at `DATA\Damage` on `record` to `value`.
*/
SetDamage(record: RecordHandle, value: number): void;
/**
* @returns Value at `DNAM` on `record`.
*/
GetArmorRating(record: RecordHandle): number;
/**
* Sets the value at `DNAM` on `record` to `value`.
*/
SetArmorRating(record: RecordHandle, value: number): void;
/**
* @returns Value at `[BODT|BOD2]\Armor Type` on `record`.
*/
GetArmorType(record: RecordHandle): string;
/**
* Sets the value at `[BODT|BOD2]\Armor Type` on `record` to `armorType`.
*/
SetArmorType(record: RecordHandle, armorType: string): void;
/**
* @returns State of flag Female at `ACBS\Flags` on `record`.
*/
GetIsFemale(record: RecordHandle): boolean;
/**
* Sets flag Female at `ACBS\Flags` on `record` to `state`.
*/
SetIsFemale(record: RecordHandle, state: boolean): void;
/**
* @returns State of flag Essential at `ACBS\Flags` on `record`.
*/
GetIsEssential(record: RecordHandle): boolean;
/**
* Sets flag Essential at `ACBS\Flags` on `record` to `state`.
*/
SetIsEssential(record: RecordHandle, state: boolean): void;
/**
* @returns State of flag Unique at `ACBS\Flags` on `record`.
*/
GetIsUnique(record: RecordHandle): boolean;
/**
* Sets flag Unique at `ACBS\Flags` on `record` to `state`.
*/
SetIsUnique(record: RecordHandle, state: boolean): void;
/**
* Masters functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FMasters}
*/
/**
* Removes unnecessary masters from file `id`.
*/
CleanMasters(id: FileHandle): void;
/**
* Orders the masters in file `id` based on the order in which they are loaded.
*/
SortMasters(id: FileHandle): void;
/**
* Adds master `filename` to file `id` if missing.
*/
AddMaster(id: FileHandle, filename: string): void;
/**
* Adds masters to file `id2` which are required when copying element `id` to it.
* Set `asNew` to true when copying `id` as a new record.
*/
AddRequiredMasters(
id: ElementHandle,
id2: FileHandle,
/**
* @default false
*/
asNew?: boolean,
): void;
/**
* @returns Array of handles for the master files of file `id`.
*/
GetMasters(id: FileHandle): FileHandle[];
/**
* @returns Array of the master filenames of the file `id`.
*/
GetMasterNames(id: FileHandle): string[];
/**
* Adds all files loaded before file `id` as masters to it.
*/
AddAllMasters(id: FileHandle): void;
/**
* @returns Array of the filenames of files loaded before file `id` that aren't already masters for it.
*/
GetAvailableMasters(id: FileHandle): string[];
/**
* Group functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FGroups}
*/
/**
* @returns true if group `signature` is present in file `id`.
*/
HasGroup(id: FileHandle, signature: string): boolean;
/**
* Adds the group `signature` to file `id` if missing and returns a handle to it.
*/
AddGroup(id: FileHandle, signature: string): Handle;
/**
* @returns Handle to the child group of id.
* @returns 0 if id does not have a child group.
*/
GetChildGroup(id: Handle): Zeroable<Handle>;
/**
* Serialization functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FSerialization}
*/
/**
* @returns Element `id` as a JSON string.
*/
ElementToJSON(id: ElementHandle): string;
/**
* @returns Element `id` as a JavaScript object.
*/
ElementToObject(id: ElementHandle): object;
/**
* Creates elements by deserializing `json` in the context of `id` at `path`.
*/
ElementFromJSON(id: Zeroable<Handle>, path: string, json: string): void;
/**
* Creates elements from `obj` in the context of `id` at `path`.
*/
ElementFromObject(id: Zeroable<Handle>, path: string, obj: object): void;
/**
* Plugin Error functions
*/
/**
* Starts a background thread which checks for errors in `id`.
*/
CheckForErrors(id: FileHandle): void;
/**
* @returns true if the error thread started by `CheckForErrors` is done.
* @see CheckForErrors
*/
GetErrorThreadDone(): boolean;
/**
* @returns Errors found by `CheckForErrors` as an array of error objects.
* @see CheckForErrors
*/
GetErrors(): Array<{
group: number;
handle: Handle;
signature: string;
form_id: number;
path: string;
data: string;
}>;
/**
* Utils functions
* @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2Fxelib%2FUtils}
*/
/**
* Converts `n` to a hexadecimal string and pads it with zeros until it has a length equal to `padding`.
* @param n unsigned integer
* @param padding integer
*/
Hex(n: number, padding: number): string;
/**
* Passes `handle` to `callback`, executes it, and then releases `handle`.
* Uses a try-finally to ensure the handle gets released
* regardless of any exceptions that occur in `callback`.
*/
WithHandle(handle: Handle, callback: (handle: Handle) => void): void;
/**
* Passes `handles` to `callback`, executes it, and then releases `handles`.
* Uses a try-finally to ensure the handles get released
* regardless of any exceptions that occur in `callback`.
*/
WithHandles(handles: Handle[], callback: (handle: Handle[]) => void): void;
/**
* Creates an array in xelib at `xelib.HandleGroup`.
* All handles retrieved from `xelib` functions will be appended to this array.
* @see HandleGroup
*/
CreateHandleGroup(): void;
/**
* @see CreateHandleGroup
*/
HandleGroup?: Handle[] | undefined;
/**
* Releases all handles in `xelib.HandleGroup`.
* After calling this, handles retrieved from xelib
* will no longer be appended to the `xelib.HandleGroup` array.
* @see HandleGroup
*/
FreeHandleGroup(): void;
/**
* Executes `callback`.
* Any handles retrieved from `xelib` in `callback` will not be added to the active handle group.
*/
OutsideHandleGroup(callback: () => void): void;
/**
* Executes `callback` in a handle group.
* Any handles retrieved from `xelib` in `callback` will be automatically released
* once it finishes executing.
*/
WithHandleGroup(callback: () => void): void;
/**
* Extracts a signature from a string.
* E.g. extracts `ARMO`, from `ArmorIronCuirass "Iron Armor" [ARMO:00012E49]`.
*/
ExtractSignature(str: string): string;
/**
* Gets all records matching `search` found in `id`
* and returns an object with properties corresponding to each record found.
* The object's properties have keys produced by calling `keyFn` on the record
* and values produced by calling `valueFn` on the record.
* If `valueFn` is falsy, the record's handle is used as the value.
*/
BuildReferenceMap<V = RecordHandle>(
id: Handle,
/**
* @default ''
*/
search?: string,
/**
* @default xelib.EditorID
* @see EditorID
*/
keyFn?: (rec: RecordHandle) => string,
/**
* @default null
*/
valueFn?: (rec: RecordHandle) => V,
): { [k: string]: V };
/**
* @returns object constructed by mapping each value in the `paths` object
* to an element resolved relative to `id`.
*/
ResolveElements<P extends { [k: string]: string }>(
id: Handle,
paths: P,
): {
[K in keyof P]: Zeroable<ElementHandle>;
};
/**
* Raises an exception if any element fails to resolve.
* @returns object constructed by mapping each value in the `paths` object
* to an element resolved relative to `id`.
*/
ResolveElementsEx<P extends { [k: string]: string }>(
id: Handle,
paths: P,
): {
[K in keyof P]: ElementHandle;
};
} | the_stack |
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[
dataViewTag
] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[
float64Tag
] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[
numberTag
] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[
stringTag
] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[
uint16Tag
] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array ? array.length : 0;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array ? array.length : 0;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec((coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO) || '');
return uid ? 'Symbol(src)_1.' + uid : '';
})();
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp(
'^' +
funcToString
.call(hasOwnProperty)
.replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') +
'$',
);
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeKeys = overArg(Object.keys, Object);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
return this.has(key) && delete this.__data__[key];
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.__data__ = {
hash: new Hash(),
map: new (Map || ListCache)(),
string: new Hash(),
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
return getMapData(this, key)['delete'](key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
getMapData(this, key).set(key, value);
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
this.__data__ = new ListCache(entries);
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache();
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
return this.__data__['delete'](key);
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var cache = this.__data__;
if (cache instanceof ListCache) {
var pairs = cache.__data__;
if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
pairs.push([key, value]);
return this;
}
cache = this.__data__ = new MapCache(pairs);
}
cache.set(key, value);
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
// Safari 9 makes `arguments.length` enumerable in strict mode.
var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
var length = result.length,
skipIndexes = !!length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
result.push(key);
}
}
return result;
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) {
object[key] = value;
}
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {boolean} [isFull] Specify a clone including symbols.
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
var result;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
if (isHostObject(value)) {
return object ? value : {};
}
result = initCloneObject(isFunc ? {} : value);
if (!isDeep) {
return copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack());
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (!isArr) {
var props = isFull ? getAllKeys(value) : keys(value);
}
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
function baseCreate(proto) {
return isObject(proto) ? objectCreate(proto) : {};
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
return objectToString.call(value);
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var result = new buffer.constructor(buffer.length);
buffer.copy(result);
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor());
}
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor());
}
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;
assignValue(object, key, newValue === undefined ? source[key] : newValue);
}
return object;
}
/**
* Copies own symbol properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* Creates an array of the own enumerable symbol properties of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11,
// for data views in Edge < 14, and promises in Node.js.
if (
(DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map()) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set()) != setTag) ||
(WeakMap && getTag(new WeakMap()) != weakMapTag)
) {
getTag = function(value) {
var result = objectToString.call(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : undefined;
if (ctorString) {
switch (ctorString) {
case dataViewCtorString:
return dataViewTag;
case mapCtorString:
return mapTag;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag;
case weakMapCtorString:
return weakMapTag;
}
}
return result;
};
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return typeof object.constructor == 'function' && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag:
case float64Tag:
case int8Tag:
case int16Tag:
case int32Tag:
case uint8Tag:
case uint8ClampedTag:
case uint16Tag:
case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return (
!!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length
);
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean'
? value !== '__proto__'
: value === null;
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return func + '';
} catch (e) {}
}
return '';
}
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, true, true);
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return (
isArrayLikeObject(value) &&
hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag)
);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8-9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
export default cloneDeep; | the_stack |
import 'source-map-support/register'
import { RelayProvider, GSNConfig } from '@opengsn/provider'
import { decodeRevertReason, getEip712Signature } from '@opengsn/common'
import { Address } from '@opengsn/common/dist/types/Aliases'
import {
TypedRequestData,
GsnDomainSeparatorType,
GsnRequestType
} from '@opengsn/common/dist/EIP712/TypedRequestData'
import { RelayRequest, cloneRelayRequest } from '@opengsn/common/dist/EIP712/RelayRequest'
import { defaultEnvironment } from '@opengsn/common/dist/Environments'
import { GsnTestEnvironment } from '@opengsn/cli/dist/GsnTestEnvironment'
import { deployHub } from '@opengsn/dev/dist/test/TestUtils'
import { constants, expectEvent } from '@openzeppelin/test-helpers'
import { PrefixedHexString } from 'ethereumjs-util'
import { HttpProvider } from 'web3-core'
import { registerAsRelayServer, revertReason } from './TestUtils'
import {
IForwarderInstance,
TestProxyInstance,
TestTokenInstance,
TestUniswapInstance,
ProxyDeployingPaymasterInstance,
TestHubInstance,
TestCounterInstance,
ProxyFactoryInstance
} from '@opengsn/paymasters/types/truffle-contracts'
import {
StakeManagerInstance,
RelayHubInstance
} from '@opengsn/contracts/types/truffle-contracts'
import { transferErc20Error } from './TokenPaymaster.test'
const RelayHub = artifacts.require('RelayHub')
const TestHub = artifacts.require('TestHub')
const Forwarder = artifacts.require('Forwarder')
const TestProxy = artifacts.require('TestProxy')
const TestToken = artifacts.require('TestToken')
const TestCounter = artifacts.require('TestCounter')
const TestUniswap = artifacts.require('TestUniswap')
const ProxyFactory = artifacts.require('ProxyFactory')
const ProxyIdentity = artifacts.require('ProxyIdentity')
const StakeManager = artifacts.require('StakeManager')
const ProxyDeployingPaymaster = artifacts.require('ProxyDeployingPaymaster')
// these are no longer exported
export async function snapshot (): Promise<{ id: number, jsonrpc: string, result: string }> {
return await new Promise((resolve, reject) => {
// @ts-ignore
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_snapshot',
id: Date.now()
}, (err: Error | null, snapshotId: { id: number, jsonrpc: string, result: string }) => {
if (err != null) { return reject(err) }
return resolve(snapshotId)
})
})
}
export async function revert (id: string): Promise<void> {
return await new Promise((resolve, reject) => {
// @ts-ignore
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_revert',
params: [id],
id: Date.now()
}, (err: Error | null, result: any) => {
if (err != null) { return reject(err) }
return resolve(result)
})
})
}
contract('ProxyDeployingPaymaster', ([senderAddress, relayWorker, burnAddress]) => {
const tokensPerEther = 2
let paymaster: ProxyDeployingPaymasterInstance
let relayHub: RelayHubInstance
let testHub: TestHubInstance
let proxyAddress: Address
let token: TestTokenInstance
let relayRequest: RelayRequest
let recipient: TestProxyInstance
let stakeManager: StakeManagerInstance
let signature: PrefixedHexString
let uniswap: TestUniswapInstance
let forwarder: IForwarderInstance
let proxyFactory: ProxyFactoryInstance
let paymasterData: any
async function assertDeployed (address: Address, deployed: boolean): Promise<void> {
const code = await web3.eth.getCode(address)
const assertion = deployed ? assert.notStrictEqual : assert.strictEqual
assertion(code, '0x')
}
const gasData = {
pctRelayFee: '0',
baseRelayFee: '0',
maxFeePerGas: '1',
maxPriorityFeePerGas: '1',
gasLimit: 1e6.toString()
}
before(async function () {
uniswap = await TestUniswap.new(tokensPerEther, 1, {
value: (5e18).toString(),
gas: 1e7
})
proxyFactory = await ProxyFactory.new()
token = await TestToken.at(await uniswap.tokenAddress())
paymaster = await ProxyDeployingPaymaster.new([uniswap.address], proxyFactory.address)
forwarder = await Forwarder.new({ gas: 1e7 })
recipient = await TestProxy.new(forwarder.address, { gas: 1e7 })
stakeManager = await StakeManager.new(defaultEnvironment.maxUnstakeDelay, 0, 0, burnAddress, burnAddress)
testHub = await TestHub.new(
stakeManager.address,
constants.ZERO_ADDRESS,
constants.ZERO_ADDRESS,
constants.ZERO_ADDRESS,
defaultEnvironment.relayHubConfiguration,
{ gas: 10000000 })
relayHub = await deployHub(stakeManager.address, constants.ZERO_ADDRESS, constants.ZERO_ADDRESS, constants.ZERO_ADDRESS, '0')
await paymaster.setRelayHub(relayHub.address)
await forwarder.registerRequestType(GsnRequestType.typeName, GsnRequestType.typeSuffix)
await forwarder.registerDomainSeparator(GsnDomainSeparatorType.name, GsnDomainSeparatorType.version)
await paymaster.setTrustedForwarder(forwarder.address)
paymasterData = web3.eth.abi.encodeParameter('address', uniswap.address)
relayRequest = {
request: {
from: senderAddress,
to: recipient.address,
nonce: '0',
value: '0',
validUntilTime: '0',
gas: 1e6.toString(),
data: recipient.contract.methods.test().encodeABI()
},
relayData: {
...gasData,
transactionCalldataGasUsed: '0',
relayWorker,
paymaster: paymaster.address,
paymasterData,
clientId: '2',
forwarder: forwarder.address
}
}
proxyAddress = await paymaster.getPayer(relayRequest)
signature = await getEip712Signature(
web3,
new TypedRequestData(
defaultEnvironment.chainId,
forwarder.address,
relayRequest
)
)
})
after(async function () {
await GsnTestEnvironment.stopGsn()
})
context('#preRelayedCall()', function () {
before(async function () {
await paymaster.setRelayHub(testHub.address)
})
it('should reject if not enough balance', async () => {
assert.match(await revertReason(testHub.callPreRC(relayRequest, signature, '0x', 1e6)), /ERC20: transfer amount exceeds balance/)
})
context('with token balance at identity address', function () {
before(async function () {
await token.mint(1e18.toString())
await token.transfer(proxyAddress, 1e18.toString())
})
it('should reject if not enough balance for value transfer', async () => {
const relayRequestX = cloneRelayRequest(relayRequest)
relayRequestX.request.value = 1e18.toString()
const signatureX = await getEip712Signature(
web3,
new TypedRequestData(
defaultEnvironment.chainId,
forwarder.address,
relayRequestX
)
)
assert.match(await revertReason(testHub.callPreRC(relayRequestX, signatureX, '0x', 1e6)), /ERC20: transfer amount exceeds balance/)
})
context('with identity deployed', function () {
let id: string
before(async function () {
id = (await snapshot()).result
await paymaster.deployProxy(senderAddress)
await registerAsRelayServer(token, stakeManager, relayWorker, senderAddress, relayHub)
await relayHub.depositFor(paymaster.address, { value: 1e18.toString() })
})
after(async function () {
// tests need to deploy the same proxy again
await revert(id)
})
it('should accept if payer is an identity that was not deployed yet', async function () {
await testHub.callPreRC(relayRequest, signature, '0x', 1e6)
})
it('should reject if incorrect signature', async () => {
await paymaster.setRelayHub(relayHub.address)
const wrongSignature = await getEip712Signature(
web3,
new TypedRequestData(
222,
forwarder.address,
relayRequest
)
)
const gas = 5000000
const relayCall: any = await relayHub.relayCall.call(10e6, relayRequest, wrongSignature, '0x', {
from: relayWorker,
gas
})
assert.equal(decodeRevertReason(relayCall.returnValue), 'FWD: signature mismatch')
})
it('should accept because identity gave approval to the paymaster', async function () {
await paymaster.setRelayHub(testHub.address)
await testHub.callPreRC(relayRequest, signature, '0x', 1e6)
})
context('with token approval withdrawn', function () {
before(async function () {
const proxy = await ProxyIdentity.at(proxyAddress)
const data = token.contract.methods.approve(paymaster.address, 0).encodeABI()
await proxy.execute(0, token.address, 0, data)
})
it('should reject if payer is an already deployed identity and approval is insufficient', async function () {
await paymaster.setRelayHub(testHub.address)
assert.equal(await revertReason(testHub.callPreRC(relayRequest, signature, '0x', 1e6)), transferErc20Error)
})
})
})
})
})
context('#preRelayCall()', function () {
// With GasPrice set to 1 and fees set to 0
const preChargeEth = 7777
let id: string
before(async function () {
id = (await snapshot()).result
await token.mint(1e18.toString())
await token.transfer(proxyAddress, 1e18.toString())
await paymaster.setRelayHub(relayHub.address)
})
after(async function () {
// tests need to deploy the same proxy again
await revert(id)
})
it('should deploy new identity contract if does not exist, and pre-charge it', async function () {
await assertDeployed(proxyAddress, false)
await paymaster.setRelayHub(testHub.address)
const tx = await testHub.callPreRC(relayRequest, signature, '0x', preChargeEth)
await assertDeployed(proxyAddress, true)
await expectEvent.inTransaction(tx.tx, ProxyFactory, 'ProxyDeployed', { proxyAddress })
await expectEvent.inTransaction(tx.tx, TestToken, 'Transfer', {
from: proxyAddress,
to: paymaster.address,
value: (preChargeEth * tokensPerEther).toString()
})
})
it('should not deploy new identity contract if exists, only pre-charge', async function () {
const code = await web3.eth.getCode(proxyAddress)
assert.notStrictEqual(code, '0x')
await paymaster.setRelayHub(testHub.address)
const tx = await testHub.callPreRC(relayRequest, signature, '0x', preChargeEth)
await expectEvent.not.inTransaction(tx.tx, ProxyFactory, 'ProxyDeployed', { proxyAddress })
await expectEvent.inTransaction(tx.tx, TestToken, 'Transfer', {
from: proxyAddress,
to: paymaster.address,
value: (preChargeEth * tokensPerEther).toString()
})
})
})
context('#postRelayedCall()', function () {
const preCharge = '3000000'
const gasUsedByPost = 10000
let context: string
before(async function () {
await token.mint(1e18.toString())
await token.transfer(paymaster.address, 1e18.toString())
await paymaster.setRelayHub(relayHub.address)
await paymaster.setPostGasUsage(gasUsedByPost)
context = web3.eth.abi.encodeParameters(
['address', 'address', 'uint256', 'uint256', 'address', 'address', 'address'],
[proxyAddress, senderAddress, preCharge, 0, constants.ZERO_ADDRESS, token.address, uniswap.address])
})
it('should refund the proxy with the overcharged tokens', async function () {
const gasUseWithoutPost = 1000000
await paymaster.setRelayHub(testHub.address)
const tx = await testHub.callPostRC(paymaster.address, context, gasUseWithoutPost, relayRequest.relayData)
const gasUsedWithPost = gasUseWithoutPost + gasUsedByPost
// Repeat on-chain calculation here for sanity
const actualEtherCharge = (100 + parseInt(relayRequest.relayData.pctRelayFee)) / 100 * gasUsedWithPost
const actualTokenCharge = actualEtherCharge * tokensPerEther
const refund = parseInt(preCharge) - actualTokenCharge
await expectEvent.inTransaction(tx.tx, TestToken, 'Transfer', {
from: paymaster.address,
to: proxyAddress,
value: refund.toString()
})
await expectEvent.inTransaction(tx.tx, TestToken, 'Transfer', {
from: paymaster.address,
to: uniswap.address,
value: actualTokenCharge.toString()
})
// note that here 'Deposited' is actually emitted by TestHub, beware of API change
await expectEvent.inTransaction(tx.tx, RelayHub, 'Deposited', {
paymaster: paymaster.address,
from: paymaster.address,
amount: actualEtherCharge.toString()
})
})
})
// now test for the real flow
context('#relayedCall()', function () {
let hub: RelayHubInstance
let paymaster: ProxyDeployingPaymasterInstance
let counter: TestCounterInstance
let proxy: any
let encodedCall: string
let relayProvider: RelayProvider
before(async function () {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const proxyIdentityArtifact = require('../build/contracts/ProxyIdentity')
// start the GSN
const host = (web3.currentProvider as HttpProvider).host
const testEnv = await GsnTestEnvironment.startGsn(host)
// TODO: fix
// @ts-ignore
testEnv.httpServer.relayService?.config.maxAcceptanceBudget = 1e15.toString()
// deposit Ether to the RelayHub for paymaster
// need to convert to any because of namespace collision
hub = (await RelayHub.at(testEnv.contractsDeployment.relayHubAddress!)) as any as RelayHubInstance
paymaster = await ProxyDeployingPaymaster.new([uniswap.address], proxyFactory.address)
await paymaster.setRelayHub(hub.address)
await paymaster.setTrustedForwarder(testEnv.contractsDeployment.forwarderAddress!)
await hub.depositFor(paymaster.address, {
value: 1e18.toString()
})
// get some tokens for our future proxy. Proxy address only depends on the addresses sender, paymaster and token.
const relayRequest: RelayRequest = {
request: {
to: constants.ZERO_ADDRESS,
from: senderAddress,
nonce: '0',
value: '0',
data: '0x',
validUntilTime: '0',
gas: 1e6.toString()
},
relayData: {
...gasData,
transactionCalldataGasUsed: '0',
relayWorker,
paymaster: paymaster.address,
paymasterData: '0x',
clientId: '2',
forwarder: testEnv.contractsDeployment.forwarderAddress!
}
}
proxyAddress = await paymaster.getPayer(relayRequest)
await token.mint(1e18.toString())
await token.transfer(proxyAddress, 1e18.toString())
// deploy test target contract
counter = await TestCounter.new()
// create Web3 Contract instance for ProxyIdentity (cannot use truffle artifact if no code deployed)
await assertDeployed(proxyAddress, false)
proxy = new web3.eth.Contract(proxyIdentityArtifact.abi, proxyAddress)
const gsnConfig: Partial<GSNConfig> = {
loggerConfiguration: {
logLevel: 'error'
},
maxPaymasterDataLength: 32,
paymasterAddress: paymaster.address
}
encodedCall = counter.contract.methods.increment().encodeABI()
relayProvider = await RelayProvider.newProvider({
provider: web3.currentProvider as HttpProvider,
overrideDependencies: {
asyncPaymasterData: async () => {
return paymasterData
}
},
config: gsnConfig
}).init()
proxy.setProvider(relayProvider)
})
it('should deploy proxy contract as part of a relay call transaction and charge it with tokens', async function () {
// Counter should be 0 initially
const counter1 = await counter.get()
assert.equal(counter1.toString(), '0')
// Call counter.increment from identity
const { maxFeePerGas, maxPriorityFeePerGas } = await relayProvider.calculateGasFees()
const tx = await proxy.methods.execute(0, counter.address, 0, encodedCall).send({
from: senderAddress,
gas: 5000000,
maxFeePerGas,
maxPriorityFeePerGas
})
// Check that increment was called
const counter2 = await counter.get()
assert.equal(counter2.toString(), '1')
await expectEvent.inTransaction(tx.actualTransactionHash, ProxyFactory, 'ProxyDeployed', { proxyAddress })
})
it('should pay with token to make a call if proxy is deployed', async function () {
const counter1 = await counter.get()
assert.equal(counter1.toString(), '1')
const { maxFeePerGas, maxPriorityFeePerGas } = await relayProvider.calculateGasFees()
const tx = await proxy.methods.execute(0, counter.address, 0, encodedCall).send({
from: senderAddress,
gas: 5000000,
maxFeePerGas,
maxPriorityFeePerGas
})
const counter2 = await counter.get()
assert.equal(counter2.toString(), '2')
await expectEvent.not.inTransaction(tx.actualTransactionHash, ProxyFactory, 'ProxyDeployed', { proxyAddress })
})
it('should convert tokens to ETH and send to Proxy if \'value\' is specified', async function () {
const counter1 = await counter.get()
assert.strictEqual(counter1.toString(), '2')
const balance1 = await web3.eth.getBalance(counter.address)
assert.strictEqual(balance1, '0')
const value = 1e16
const { maxFeePerGas } = await relayProvider.calculateGasFees()
await proxy.methods.execute(0, counter.address, value.toString(), encodedCall).send({
from: senderAddress,
gas: 5000000,
value,
gasPrice: maxFeePerGas
})
const counter2 = await counter.get()
assert.strictEqual(counter2.toString(), '3')
const balance2 = await web3.eth.getBalance(counter.address)
assert.strictEqual(balance2, value.toString(), 'counter did not receive money')
})
})
}) | the_stack |
import { Vue, Component, Prop, Emit } from 'vue-property-decorator'
import type { ProgressInfo } from 'mishiro-core'
import ProgressBar from '../../vue/component/ProgressBar.vue'
import check from './check'
import { setLatestResVer, setMaster, setResVer } from './store'
import MishiroIdol from './mishiro-idol'
// import { bgmList } from './the-player'
// import { unpackTexture2D } from './unpack-texture-2d'
// import { Client } from './typings/main'
import getPath from '../common/get-path'
import configurer from './config'
import { getMasterHash, openManifestDatabase, readMasterData } from './ipc-back'
import type { MishiroConfig } from '../main/config'
import { readAcb } from './audio'
import type { BGM } from './back/resolve-audio-manifest'
import { error } from './log'
const fs = window.node.fs
// const path = window.node.path
const { manifestPath, masterPath, bgmDir/* , iconDir */ } = getPath
// const ipcRenderer = window.node.electron.ipcRenderer
@Component({
components: {
ProgressBar
}
})
export default class extends Vue {
dler = new this.core.Downloader()
loading: number = 0
isReady: boolean = false
text: string = ''
// appData: { resVer: number | string; latestResVer: number | string; master: MasterData | any} = {
// resVer: 'Unknown',
// latestResVer: 'Unknown',
// master: {}
// }
get wavProgress (): boolean {
return this.core.config.getProgressCallback()
}
// @Prop() value!: { resVer: number | string, latestResVer: number | string, master: MasterData | any }
@Prop() isTouched!: boolean
onOptionSaved = (options: MishiroConfig): void => {
this.dler.setProxy(options.proxy ?? '')
}
created (): void {
this.dler.setProxy(configurer.get('proxy') ?? '')
this.event.$on('optionSaved', this.onOptionSaved)
}
beforeDestroy (): void {
this.event.$off('optionSaved', this.onOptionSaved)
}
getEventCardId (eventAvailable: any[], eventData: any): number[] {
if (!eventAvailable.length) return (eventData.bg_id as string).split(',').map((id: string) => (Number(id) - 1))
eventAvailable.sort(function (a, b) {
return a.recommend_order - b.recommend_order
})
// console.log(eventAvailable)
return [eventAvailable[0].reward_id, eventAvailable[eventAvailable.length - 1].reward_id]
}
@Emit('ready')
emitReady (): void {
this.event.$emit('play-studio-bgm')
}
async getResVer (): Promise<number> {
const resVer = await check()
return resVer
}
async getManifest (resVer: number): Promise<string> {
this.loading = 0
this.text = this.$t('update.manifest') as string
let manifestFile = ''
if (fs.existsSync(manifestPath(resVer, '.db'))) {
this.loading = 100
manifestFile = manifestPath(resVer, '.db')
return manifestFile
}
try {
const manifestFile = await this.dler.downloadManifest(resVer, manifestPath(resVer), prog => {
this.text = (this.$t('update.manifest') as string) + `${Math.ceil(prog.current / 1024)}/${Math.ceil(prog.max / 1024)} KB`
this.loading = prog.loading
})
if (manifestFile) {
fs.unlinkSync(manifestPath(resVer))
return manifestFile
} else throw new Error('Download failed.')
} catch (errorPath) {
this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string))
return ''
}
}
downloadMaster (resVer: number, hash: string, progressing: (prog: ProgressInfo) => void): Promise<string> {
const downloader = new this.core.Downloader()
downloader.setProxy(configurer.get('proxy') ?? '')
return downloader.downloadDatabase(hash, masterPath(resVer), progressing, '.db')
// return downloader.downloadOne(
// `http://storage.game.starlight-stage.jp/dl/resources/Generic/${hash}`,
// masterPath(resVer),
// progressing
// )
}
async getMaster (resVer: number, masterHash: string): Promise<string> {
this.loading = 0
this.text = this.$t('update.master') as string
let masterFile = ''
if (fs.existsSync(masterPath(resVer, '.db'))) {
this.loading = 100
masterFile = masterPath(resVer, '.db')
return masterFile
}
try {
const masterFile = await this.downloadMaster(resVer, masterHash, prog => {
this.text = (this.$t('update.master') as string) + `${Math.ceil(prog.current / 1024)}/${Math.ceil(prog.max / 1024)} KB`
this.loading = prog.loading
})
if (masterFile) {
// masterFile = this.core.util.lz4dec(masterLz4File, '.db')
fs.unlinkSync(masterPath(resVer))
// return masterFile
return masterFile
} else throw new Error('Download master.mdb failed.')
} catch (errorPath) {
this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string))
throw errorPath
}
}
// sleep (ms: number): Promise<undefined> {
// return new Promise(resolve => {
// setTimeout(() => {
// resolve()
// }, ms)
// })
// }
// async getGachaIcon (icons: { name: string; hash: string; [x: string]: any }[]) {
// const card = configurer.get('card')
// for (let i = 0; i < icons.length; i++) {
// let cacheName = iconDir(path.parse(icons[i].name).name)
// this.text = ((!card || card === 'default') ? icons[i].name : path.basename(cacheName + '.png')) + ' ' + i + '/' + icons.length
// this.loading = 100 * i / icons.length
// if (!fs.existsSync(cacheName + '.png')) {
// try {
// if (!card || card === 'default') {
// let asset = await this.dler.downloadAsset(icons[i].hash, cacheName)
// if (asset) {
// fs.removeSync(cacheName)
// await unpackTexture2D(asset)
// }
// } else {
// await this.dler.downloadIcon(icons[i].name.slice(5, 5 + 6), cacheName + '.png')
// }
// } catch (err) {
// console.log(err)
// continue
// }
// }
// }
// }
async afterMasterRead (masterData: import('./back/on-master-read').MasterData): Promise<void> {
// console.log(masterData);
const downloader = new this.core.Downloader()
downloader.setProxy(configurer.get('proxy') ?? '')
// const toName = (p: string) => path.parse(p).name
setMaster(masterData)
setLatestResVer(configurer.get('latestResVer') || -1)
const bgmManifest = masterData.bgmManifest
// for (let k in bgmList) {
// if (!fs.existsSync(path.join(getPath('./public'), bgmList[k].src))) {
// let acbName = `b/${toName(bgmList[k].src)}.acb`
// let hash: string = bgmManifest.filter(row => row.name === acbName)[0].hash
// try {
// this.text = path.basename(`${toName(bgmList[k].src)}.acb`)
// this.loading = 0
// let result = await downloader.downloadSound(
// 'b',
// hash,
// bgmDir(`${toName(bgmList[k].src)}.acb`),
// prog => {
// this.text = prog.name + ' ' + Math.ceil(prog.current / 1024) + '/' + Math.ceil(prog.max / 1024) + ' KB'
// this.loading = prog.loading / (this.wavProgress ? 2 : 1)
// }
// )
// if (result) {
// await this.acb2mp3(bgmDir(`${toName(bgmList[k].src)}.acb`), void 0, (_current, _total, prog) => {
// this.text = prog.name + ' ' + this.$t('live.decoding')
// this.loading = 50 + prog.loading / 2
// })
// }
// } catch (errorPath) {
// this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.downloadFailed') + '<br/>' + errorPath)
// }
// }
// }
if (masterData.eventHappening) {
const eventHca = bgmDir(`bgm_event_${masterData.eventData.id}.hca`)
if (Number(masterData.eventData.type) !== 2 && Number(masterData.eventData.type) !== 6 && !fs.existsSync(eventHca)) {
const eventBgmHash = bgmManifest.filter(row => row.name === `b/bgm_event_${masterData.eventData.id}.acb`)[0].hash
try {
// let result = await downloader.download(
// this.getBgmUrl(eventBgmHash),
// bgmDir(`bgm_event_${masterData.eventData.id}.acb`),
// (prog: ProgressInfo) => {
// this.text = prog.name + ' ' + Math.ceil(prog.current / 1024) + '/' + Math.ceil(prog.max / 1024) + ' KB'
// this.loading = prog.loading
// }
// )
this.text = `bgm_event_${masterData.eventData.id}.acb`
this.loading = 0
const eventAcb = bgmDir(this.text)
const result = await downloader.downloadSound(
'b',
eventBgmHash,
eventAcb,
prog => {
this.text = (prog.name || '') + ' ' + `${Math.ceil(prog.current / 1024)}/${Math.ceil(prog.max / 1024)} KB`
this.loading = prog.loading /* / (this.wavProgress ? 2 : 1) */
}
)
if (result) {
const acbEntries = readAcb(eventAcb)
if (!acbEntries.length) {
this.event.$emit('alert', this.$t('home.errorTitle'), 'Invalid acb')
return
}
await fs.promises.writeFile(eventHca, acbEntries[0].buffer)
await fs.remove(eventAcb)
const audio = this.$store.state.master.bgmManifest.filter((b: BGM) => b.hash === eventBgmHash)[0]
this.$set(audio, '_canplay', true)
// await this.acb2mp3(eventAcb, undefined, (_current, _total, prog) => {
// this.text = (prog.name || '') + ' ' + (this.$t('live.decoding') as string)
// this.loading = 50 + prog.loading / 2
// })
}
} catch (errorPath) {
this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string))
}
}
}
const cardId = this.getEventCardId(masterData.eventAvailable, masterData.eventData)
if (masterData.eventHappening) {
const storageCardId: number = Number(cardId[0]) + 1
if (!isNaN(storageCardId)) {
localStorage.setItem('msrEvent', `{"id":${masterData.eventData.id},"card":${storageCardId}}`)
}
} else {
localStorage.removeItem('msrEvent')
}
const downloadCard = new MishiroIdol().downloadCard
// const tmpawait = () => new Promise((resolve) => {
// this.event.$once('_eventBgReady', () => {
// resolve()
// })
// })
let getBackgroundResult: string = ''
const getBackground = async (id: string | number): Promise<void> => {
try {
this.text = `Download card_bg_${id}`
this.loading = 0
getBackgroundResult = await downloadCard.call(this, id, 'eventBgReady', (prog: ProgressInfo) => {
this.text = (prog.name || '') + ' ' + `${Math.ceil(prog.current / 1024)}/${Math.ceil(prog.max / 1024)} KB`
this.loading = prog.loading
})
this.loading = 99.99
if (getBackgroundResult/* && getBackgroundResult !== 'await ipc' */) {
this.event.$emit('eventBgReady', id)
}
} catch (err) {
this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (err.toString() as string))
}
}
const background = configurer.get('background')
if (background) {
await getBackground(background)
} else {
// const cardIdEvolution = [(Number(cardId[0]) + 1), (Number(cardId[1]) + 1)];
if (masterData.eventHappening) {
await getBackground(Number(cardId[0]) + 1)
}
}
// if (getBackgroundResult === 'await ipc') await tmpawait()
if (masterData.eventHappening) this.event.$emit('eventRewardCard', cardId)
/* let iconId = []
for (let index = 0; index < masterData.gachaAvailable.length; index++) {
iconId.push(masterData.gachaAvailable[index].reward_id)
}
const iconTask = this.createCardIconTask(iconId)
await downloader.download(iconTask, ([_url, filepath]) => {
const name = path.basename(filepath)
this.text = name + ' ' + downloader.index + '/' + iconTask.length
this.loading = 100 * downloader.index / iconTask.length
}, prog => {
this.loading = 100 * downloader.index / iconTask.length + prog.loading / iconTask.length
}) */
// await this.getGachaIcon(masterData.gachaIcon)
// console.log(failedList)
this.emitReady()
}
mounted (): void {
this.$nextTick(() => {
this.event.$on('enter', async ($resver?: number) => {
// ipcRenderer.on('readManifest', async (_event: Event, masterHash: string, resVer: number) => {
// const masterFile = await this.getMaster(resVer, masterHash)
// if (masterFile) ipcRenderer.send('readMaster', masterFile, resVer)
// })
// ipcRenderer.once('readMaster', async (_event: Event, masterData: MasterData) => {
// await this.afterMasterRead(masterData)
// })
// if (!client.user) {
// try {
// this.text = 'Loading...'
// this.loading = 0
// const acc = await client.signup((step) => {
// this.loading = step
// })
// if (acc !== '') {
// configurer.set('account', acc)
// } else {
// throw new Error('')
// }
// } catch (err) {
// console.log(err)
// }
// }
if (navigator.onLine) {
let resVer: number
if ($resver) {
resVer = $resver
} else {
try {
this.text = this.$t('update.check') as string
this.loading = 0
resVer = await this.getResVer()
} catch (err) {
console.error(err)
error(`UPDATE getResVer: ${err.stack}`)
if (Number(err.message) === 203) {
this.event.$emit('alert', this.$t('home.errorTitle'), 'Current account has been banned. Please use another account.')
return
}
resVer = configurer.get('latestResVer')!
}
}
setResVer(Number(resVer))
const manifestFile = await this.getManifest(resVer)
if (manifestFile) {
await openManifestDatabase(manifestFile)
const masterHash = await getMasterHash()
const masterFile = await this.getMaster(resVer, masterHash)
if (masterFile) {
// ipcRenderer.send('readMaster', masterFile, resVer)
const data = await readMasterData(masterFile)
await this.afterMasterRead(data)
}
// const masterData = await window.preload.readMaster(masterFile)
// await this.afterMasterRead(masterData)
}
} else {
const resVer = configurer.get('latestResVer')!
setResVer(Number(resVer))
if (fs.existsSync(manifestPath(resVer, '.db')) && fs.existsSync(masterPath(resVer, '.db'))) {
const manifestFile = manifestPath(resVer, '.db')
if (manifestFile) {
await openManifestDatabase(manifestFile)
const masterHash = await getMasterHash()
const masterFile = await this.getMaster(resVer, masterHash)
if (masterFile) {
// ipcRenderer.send('readMaster', masterFile, resVer)
const data = await readMasterData(masterFile)
await this.afterMasterRead(data)
}
// const masterData = await window.preload.readMaster(masterFile)
// await this.afterMasterRead(masterData)
}
} else {
this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noNetwork'))
}
}
})
})
}
} | the_stack |
* This is a fork of the Karpathy's TSNE.js (original license below).
* This fork implements Barnes-Hut approximation and runs in O(NlogN)
* time, as opposed to the Karpathy's O(N^2) version.
*
* @author smilkov@google.com (Daniel Smilkov)
*/
/**
* The MIT License (MIT)
* Copyright (c) 2015 Andrej Karpathy
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 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.
*/
import {SPNode, SPTree} from './sptree';
type AugmSPNode = SPNode&{numCells: number, yCell: number[], rCell: number};
/**
* Barnes-hut approximation level. Higher means more approximation and faster
* results. Recommended value mentioned in the paper is 0.8.
*/
const THETA = 0.8;
const MIN_POSSIBLE_PROB = 1E-9;
// Variables used for memorizing the second random number since running
// gaussRandom() generates two random numbers at the cost of 1 atomic
// computation. This optimization results in 2X speed-up of the generator.
let return_v = false;
let v_val = 0.0;
/** Returns the square euclidean distance between two vectors. */
export function dist2(a: number[], b: number[]): number {
if (a.length !== b.length) {
throw new Error('Vectors a and b must be of same length');
}
let result = 0;
for (let i = 0; i < a.length; ++i) {
let diff = a[i] - b[i];
result += diff * diff;
}
return result;
}
/** Returns the square euclidean distance between two 2D points. */
export function dist2_2D(a: number[], b: number[]): number {
let dX = a[0] - b[0];
let dY = a[1] - b[1];
return dX * dX + dY * dY;
}
/** Returns the square euclidean distance between two 3D points. */
export function dist2_3D(a: number[], b: number[]): number {
let dX = a[0] - b[0];
let dY = a[1] - b[1];
let dZ = a[2] - b[2];
return dX * dX + dY * dY + dZ * dZ;
}
function gaussRandom(rng: () => number): number {
if (return_v) {
return_v = false;
return v_val;
}
let u = 2 * rng() - 1;
let v = 2 * rng() - 1;
let r = u * u + v * v;
if (r === 0 || r > 1) {
return gaussRandom(rng);
}
let c = Math.sqrt(-2 * Math.log(r) / r);
v_val = v * c; // cache this for next function call for efficiency
return_v = true;
return u * c;
};
// return random normal number
function randn(rng: () => number, mu: number, std: number) {
return mu + gaussRandom(rng) * std;
};
// utilitity that creates contiguous vector of zeros of size n
function zeros(n: number): Float64Array {
return new Float64Array(n);
};
// utility that returns a matrix filled with random numbers
// generated by the provided generator.
function randnMatrix(n: number, d: number, rng: () => number) {
let nd = n * d;
let x = zeros(nd);
for (let i = 0; i < nd; ++i) {
x[i] = randn(rng, 0.0, 1E-4);
}
return x;
};
// utility that returns a matrix filled with the provided value.
function arrayofs(n: number, d: number, val: number) {
let x: number[][] = [];
for (let i = 0; i < n; ++i) {
x.push(d === 3 ? [val, val, val] : [val, val]);
}
return x;
};
// compute (p_{i|j} + p_{j|i})/(2n)
function nearest2P(
nearest: {index: number, dist: number}[][], perplexity: number,
tol: number) {
let N = nearest.length;
let Htarget = Math.log(perplexity); // target entropy of distribution
let P = zeros(N * N); // temporary probability matrix
let K = nearest[0].length;
let pRow: number[] = new Array(K); // pij[].
for (let i = 0; i < N; ++i) {
let neighbors = nearest[i];
let betaMin = -Infinity;
let betaMax = Infinity;
let beta = 1; // initial value of precision
let maxTries = 50;
// perform binary search to find a suitable precision beta
// so that the entropy of the distribution is appropriate
let numTries = 0;
while (true) {
// compute entropy and kernel row with beta precision
let psum = 0.0;
for (let k = 0; k < neighbors.length; ++k) {
let neighbor = neighbors[k];
let pij = (i === neighbor.index) ? 0 : Math.exp(-neighbor.dist * beta);
pij = Math.max(pij, MIN_POSSIBLE_PROB);
pRow[k] = pij;
psum += pij;
}
// normalize p and compute entropy
let Hhere = 0.0;
for (let k = 0; k < pRow.length; ++k) {
pRow[k] /= psum;
let pij = pRow[k];
if (pij > 1E-7) {
Hhere -= pij * Math.log(pij);
};
}
// adjust beta based on result
if (Hhere > Htarget) {
// entropy was too high (distribution too diffuse)
// so we need to increase the precision for more peaky distribution
betaMin = beta; // move up the bounds
if (betaMax === Infinity) {
beta = beta * 2;
} else {
beta = (beta + betaMax) / 2;
}
} else {
// converse case. make distrubtion less peaky
betaMax = beta;
if (betaMin === -Infinity) {
beta = beta / 2;
} else {
beta = (beta + betaMin) / 2;
}
}
numTries++;
// stopping conditions: too many tries or got a good precision
if (numTries >= maxTries || Math.abs(Hhere - Htarget) < tol) {
break;
}
}
// copy over the final prow to P at row i
for (let k = 0; k < pRow.length; ++k) {
let pij = pRow[k];
let j = neighbors[k].index;
P[i * N + j] = pij;
}
} // end loop over examples i
// symmetrize P and normalize it to sum to 1 over all ij
let N2 = N * 2;
for (let i = 0; i < N; ++i) {
for (let j = i + 1; j < N; ++j) {
let i_j = i * N + j;
let j_i = j * N + i;
let value = (P[i_j] + P[j_i]) / N2;
P[i_j] = value;
P[j_i] = value;
}
}
return P;
};
// helper function
function sign(x: number) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}
function computeForce_2d(
force: number[], mult: number, pointA: number[], pointB: number[]) {
force[0] += mult * (pointA[0] - pointB[0]);
force[1] += mult * (pointA[1] - pointB[1]);
}
function computeForce_3d(
force: number[], mult: number, pointA: number[], pointB: number[]) {
force[0] += mult * (pointA[0] - pointB[0]);
force[1] += mult * (pointA[1] - pointB[1]);
force[2] += mult * (pointA[2] - pointB[2]);
}
export interface TSNEOptions {
/** How many dimensions. */
dim: number;
/** Roughly how many neighbors each point influences. */
perplexity?: number;
/** Learning rate. */
epsilon?: number;
/** A random number generator. */
rng?: () => number;
}
export class TSNE {
private perplexity: number;
private epsilon: number;
/** Random generator */
private rng: () => number;
private iter = 0;
private Y: Float64Array;
private N: number;
private P: Float64Array;
private gains: number[][];
private ystep: number[][];
private nearest: {index: number, dist: number}[][];
private dim: number;
private dist2: (a: number[], b: number[]) => number;
private computeForce:
(force: number[], mult: number, pointA: number[],
pointB: number[]) => void;
constructor(opt: TSNEOptions) {
opt = opt || {dim: 2};
this.perplexity = opt.perplexity || 30;
this.epsilon = opt.epsilon || 10;
this.rng = opt.rng || Math.random;
this.dim = opt.dim;
if (opt.dim === 2) {
this.dist2 = dist2_2D;
this.computeForce = computeForce_2d;
} else if (opt.dim === 3) {
this.dist2 = dist2_3D;
this.computeForce = computeForce_3d;
} else {
throw new Error('Only 2D and 3D is supported');
}
}
// this function takes a fattened distance matrix and creates
// matrix P from them.
// D is assumed to be provided as an array of size N^2.
initDataDist(nearest: {index: number, dist: number}[][]) {
let N = nearest.length;
this.nearest = nearest;
this.P = nearest2P(nearest, this.perplexity, 1E-4);
this.N = N;
this.initSolution(); // refresh this
}
// (re)initializes the solution to random
initSolution() {
// generate random solution to t-SNE
this.Y = randnMatrix(this.N, this.dim, this.rng); // the solution
this.gains = arrayofs(this.N, this.dim, 1.0); // step gains
// to accelerate progress in unchanging directions
this.ystep = arrayofs(this.N, this.dim, 0.0); // momentum accumulator
this.iter = 0;
}
// return pointer to current solution
getSolution() { return this.Y; }
// perform a single step of optimization to improve the embedding
step() {
this.iter += 1;
let N = this.N;
let grad = this.costGrad(this.Y); // evaluate gradient
// perform gradient step
let ymean = this.dim === 3 ? [0, 0, 0] : [0, 0];
for (let i = 0; i < N; ++i) {
for (let d = 0; d < this.dim; ++d) {
let gid = grad[i][d];
let sid = this.ystep[i][d];
let gainid = this.gains[i][d];
// compute gain update
let newgain = sign(gid) === sign(sid) ? gainid * 0.8 : gainid + 0.2;
if (newgain < 0.01) {
newgain = 0.01; // clamp
}
this.gains[i][d] = newgain; // store for next turn
// compute momentum step direction
let momval = this.iter < 250 ? 0.5 : 0.8;
let newsid = momval * sid - this.epsilon * newgain * grad[i][d];
this.ystep[i][d] = newsid; // remember the step we took
// step!
let i_d = i * this.dim + d;
this.Y[i_d] += newsid;
ymean[d] += this.Y[i_d]; // accumulate mean so that we
// can center later
}
}
// reproject Y to be zero mean
for (let i = 0; i < N; ++i) {
for (let d = 0; d < this.dim; ++d) {
this.Y[i * this.dim + d] -= ymean[d] / N;
}
}
}
// return cost and gradient, given an arrangement
costGrad(Y: Float64Array): number[][] {
let N = this.N;
let P = this.P;
// Trick that helps with local optima.
let alpha = this.iter < 100 ? 4 : 1;
// Make data for the SP tree.
let points: number[][] = new Array(N); // (x, y)[]
for (let i = 0; i < N; ++i) {
let iTimesD = i * this.dim;
let row = new Array(this.dim);
for (let d = 0; d < this.dim; ++d) {
row[d] = Y[iTimesD + d];
}
points[i] = row;
}
// Make a tree.
let tree = new SPTree(points);
let root = tree.root as AugmSPNode;
// Annotate the tree.
let annotateTree =
(node: AugmSPNode): {numCells: number, yCell: number[]} => {
let numCells = 1;
if (node.children == null) {
// Update the current node and tell the parent.
node.numCells = numCells;
node.yCell = node.point;
return {numCells, yCell: node.yCell};
}
// node.point is a 2 or 3-dim number[], so slice() makes a copy.
let yCell = node.point.slice();
for (let i = 0; i < node.children.length; ++i) {
let child = node.children[i];
if (child == null) {
continue;
}
let result = annotateTree(child as AugmSPNode);
numCells += result.numCells;
for (let d = 0; d < this.dim; ++d) {
yCell[d] += result.yCell[d];
}
}
// Update the node and tell the parent.
node.numCells = numCells;
node.yCell = yCell.map(v => v / numCells);
return {numCells, yCell};
};
// Augment the tree with more info.
annotateTree(root);
tree.visit((node: AugmSPNode, low: number[], high: number[]) => {
node.rCell = high[0] - low[0];
return false;
});
// compute current Q distribution, unnormalized first
let grad: number[][] = [];
let Z = 0;
let forces: [number[], number[]][] = new Array(N);
for (let i = 0; i < N; ++i) {
let pointI = points[i];
// Compute the positive forces for the i-th node.
let Fpos = this.dim === 3 ? [0, 0, 0] : [0, 0];
let neighbors = this.nearest[i];
for (let k = 0; k < neighbors.length; ++k) {
let j = neighbors[k].index;
let pij = P[i * N + j];
let pointJ = points[j];
let squaredDistItoJ = this.dist2(pointI, pointJ);
let premult = pij / (1 + squaredDistItoJ);
this.computeForce(Fpos, premult, pointI, pointJ);
}
// Compute the negative forces for the i-th node.
let FnegZ = this.dim === 3 ? [0, 0, 0] : [0, 0];
tree.visit((node: AugmSPNode) => {
let squaredDistToCell = this.dist2(pointI, node.yCell);
// Squared distance from point i to cell.
if (node.children == null ||
(squaredDistToCell > 0 &&
node.rCell / Math.sqrt(squaredDistToCell) < THETA)) {
let qijZ = 1 / (1 + squaredDistToCell);
let dZ = node.numCells * qijZ;
Z += dZ;
dZ *= qijZ;
this.computeForce(FnegZ, dZ, pointI, node.yCell);
return true;
}
// Cell is too close to approximate.
let squaredDistToPoint = this.dist2(pointI, node.point);
let qijZ = 1 / (1 + squaredDistToPoint);
Z += qijZ;
qijZ *= qijZ;
this.computeForce(FnegZ, qijZ, pointI, node.point);
return false;
}, true);
forces[i] = [Fpos, FnegZ];
}
// Normalize the negative forces and compute the gradient.
const A = 4 * alpha;
const B = 4 / Z;
for (let i = 0; i < N; ++i) {
let [FPos, FNegZ] = forces[i];
let gsum = new Array(this.dim);
for (let d = 0; d < this.dim; ++d) {
gsum[d] = A * FPos[d] - B * FNegZ[d];
}
grad.push(gsum);
}
return grad;
}
} | the_stack |
import { expect } from 'chai';
import { of, Observable } from 'rxjs';
import { concatWith, mergeMap, take } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { NO_SUBS } from '../helpers/test-helper';
import { observableMatcher } from '../helpers/observableMatcher';
/** @test {concat} */
describe('concat operator', () => {
let rxTest: TestScheduler;
beforeEach(() => {
rxTest = new TestScheduler(observableMatcher);
});
it('should concatenate two cold observables', () => {
rxTest.run(({ cold, expectObservable }) => {
const e1 = cold(' --a--b-|');
const e2 = cold(' --x---y--|');
const expected = '--a--b---x---y--|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
});
});
it('should work properly with scalar observables', (done) => {
const results: string[] = [];
const s1 = new Observable<number>(observer => {
setTimeout(() => {
observer.next(1);
observer.complete();
});
}).pipe(concatWith(of(2)));
s1.subscribe(
x => {
results.push('Next: ' + x);
},
x => {
done(new Error('should not be called'));
},
() => {
results.push('Completed');
expect(results).to.deep.equal(['Next: 1', 'Next: 2', 'Completed']);
done();
}
);
});
it('should complete without emit if both sources are empty', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --|');
const e1subs = ' ^-!';
const e2 = cold(' ----|');
const e2subs = ' --^---!';
const expected = '------|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should not complete if first source does not completes', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---');
const e1subs = ' ^--';
const e2 = cold(' --|');
const e2subs = NO_SUBS;
const expected = '---';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should not complete if second source does not completes', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --|');
const e1subs = ' ^-!';
const e2 = cold(' ---');
const e2subs = ' --^--';
const expected = '-----';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should not complete if both sources do not complete', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---');
const e1subs = ' ^--';
const e2 = cold(' ---');
const e2subs = NO_SUBS;
const expected = '---';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should raise error when first source is empty, second source raises error', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --|');
const e1subs = ' ^-!';
const e2 = cold(' ----#');
const e2subs = ' --^---!';
const expected = '------#';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should raise error when first source raises error, second source is empty', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---#');
const e1subs = ' ^--!';
const e2 = cold(' ----|');
const expected = '---#';
const e2subs = NO_SUBS;
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should raise first error when both source raise error', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---#');
const e1subs = ' ^--!';
const e2 = cold(' ------#');
const expected = '---#';
const e2subs = NO_SUBS;
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should concat if first source emits once, second source is empty', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --a--|');
const e1subs = ' ^----!';
const e2 = cold(' --------|');
const e2subs = ' -----^-------!';
const expected = '--a----------|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should concat if first source is empty, second source emits once', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --|');
const e1subs = ' ^-!';
const e2 = cold(' --a--|');
const e2subs = ' --^----!';
const expected = '----a--|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should emit element from first source, and should not complete if second ' + 'source does not completes', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --a--|');
const e1subs = ' ^----!';
const e2 = cold(' ---');
const e2subs = ' -----^--';
const expected = '--a-----';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should not complete if first source does not complete', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---');
const e1subs = ' ^--';
const e2 = cold(' --a--|');
const e2subs = NO_SUBS;
const expected = '---';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should emit elements from each source when source emit once', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---a|');
const e1subs = ' ^---!';
const e2 = cold(' -----b--|');
const e2subs = ' ----^-------!';
const expected = '---a-----b--|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should unsubscribe to inner source if outer is unsubscribed early', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---a-a--a| ');
const e1subs = ' ^--------! ';
const e2 = cold(' -----b-b--b-|');
const e2subs = ' ---------^-------!';
const unsub = ' -----------------! ';
const expected = ' ---a-a--a-----b-b ';
expectObservable(e1.pipe(concatWith(e2)), unsub).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should not break unsubscription chains when result is unsubscribed explicitly', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---a-a--a| ');
const e1subs = ' ^--------! ';
const e2 = cold(' -----b-b--b-|');
const e2subs = ' ---------^--------! ';
const expected = '---a-a--a-----b-b- ';
const unsub = ' ------------------! ';
const result = e1.pipe(
mergeMap(x => of(x)),
concatWith(e2),
mergeMap(x => of(x))
);
expectObservable(result, unsub).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should raise error from first source and does not emit from second source', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --#');
const e1subs = ' ^-!';
const e2 = cold(' ----a--|');
const e2subs = NO_SUBS;
const expected = '--#';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should emit element from first source then raise error from second source', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' --a--|');
const e1subs = ' ^----!';
const e2 = cold(' -------#');
const e2subs = ' -----^------!';
const expected = '--a---------#';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it(
'should emit all elements from both hot observable sources if first source ' +
'completes before second source starts emit',
() => {
rxTest.run(({ hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b-|');
const e1subs = ' ^------!';
const e2 = hot(' --------x--y--|');
const e2subs = ' -------^------!';
const expected = '--a--b--x--y--|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
}
);
it(
'should emit elements from second source regardless of completion time ' + 'when second source is cold observable',
() => {
rxTest.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--c---|');
const e1subs = ' ^-----------!';
const e2 = cold(' -x-y-z-|');
const e2subs = ' ------------^------!';
const expected = '--a--b--c----x-y-z-|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
}
);
it('should not emit collapsing element from second source', () => {
rxTest.run(({ hot, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --a--b--c--|');
const e1subs = ' ^----------!';
const e2 = hot(' --------x--y--z--|');
const e2subs = ' -----------^-----!';
const expected = '--a--b--c--y--z--|';
expectObservable(e1.pipe(concatWith(e2))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
});
});
it('should emit self without parameters', () => {
rxTest.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' ---a-|');
const e1subs = ' ^----!';
const expected = '---a-|';
expectObservable(e1.pipe(concatWith())).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should stop listening to a synchronous observable when unsubscribed', () => {
const sideEffects: number[] = [];
const synchronousObservable = new Observable(subscriber => {
// This will check to see if the subscriber was closed on each loop
// when the unsubscribe hits (from the `take`), it should be closed
for (let i = 0; !subscriber.closed && i < 10; i++) {
sideEffects.push(i);
subscriber.next(i);
}
});
synchronousObservable.pipe(
concatWith(of(0)),
take(3),
).subscribe(() => { /* noop */ });
expect(sideEffects).to.deep.equal([0, 1, 2]);
});
}); | the_stack |
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type Artwork_artworkBelowTheFold = {
readonly additional_information: string | null;
readonly description: string | null;
readonly provenance: string | null;
readonly exhibition_history: string | null;
readonly literature: string | null;
readonly partner: {
readonly type: string | null;
readonly id: string;
} | null;
readonly artist: {
readonly biography_blurb: {
readonly text: string | null;
} | null;
readonly artistSeriesConnection: {
readonly totalCount: number;
} | null;
readonly " $fragmentRefs": FragmentRefs<"ArtistSeriesMoreSeries_artist">;
} | null;
readonly sale: {
readonly id: string;
readonly isBenefit: boolean | null;
readonly isGalleryAuction: boolean | null;
} | null;
readonly category: string | null;
readonly canRequestLotConditionsReport: boolean | null;
readonly conditionDescription: {
readonly details: string | null;
} | null;
readonly signature: string | null;
readonly signatureInfo: {
readonly details: string | null;
} | null;
readonly certificateOfAuthenticity: {
readonly details: string | null;
} | null;
readonly framed: {
readonly details: string | null;
} | null;
readonly series: string | null;
readonly publisher: string | null;
readonly manufacturer: string | null;
readonly image_rights: string | null;
readonly context: ({
readonly __typename: "Sale";
readonly isAuction: boolean | null;
} | {
/*This will never be '%other', but we need some
value in case none of the concrete values match.*/
readonly __typename: "%other";
}) | null;
readonly contextGrids: ReadonlyArray<{
readonly artworks: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly id: string;
} | null;
} | null> | null;
} | null;
} | null> | null;
readonly artistSeriesConnection: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly filterArtworksConnection: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly id: string;
} | null;
} | null> | null;
} | null;
} | null;
} | null> | null;
} | null;
readonly " $fragmentRefs": FragmentRefs<"PartnerCard_artwork" | "AboutWork_artwork" | "OtherWorks_artwork" | "AboutArtist_artwork" | "ArtworkDetails_artwork" | "ContextCard_artwork" | "ArtworkHistory_artwork" | "ArtworksInSeriesRail_artwork">;
readonly " $refType": "Artwork_artworkBelowTheFold";
};
export type Artwork_artworkBelowTheFold$data = Artwork_artworkBelowTheFold;
export type Artwork_artworkBelowTheFold$key = {
readonly " $data"?: Artwork_artworkBelowTheFold$data | undefined;
readonly " $fragmentRefs": FragmentRefs<"Artwork_artworkBelowTheFold">;
};
const node: ReaderFragment = (function(){
var v0 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v1 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "details",
"storageKey": null
}
],
v2 = [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v0/*: any*/)
],
"storageKey": null
}
];
return {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "Artwork_artworkBelowTheFold",
"selections": [
{
"alias": "additional_information",
"args": null,
"kind": "ScalarField",
"name": "additionalInformation",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "description",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "provenance",
"storageKey": null
},
{
"alias": "exhibition_history",
"args": null,
"kind": "ScalarField",
"name": "exhibitionHistory",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "literature",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "type",
"storageKey": null
},
(v0/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Artist",
"kind": "LinkedField",
"name": "artist",
"plural": false,
"selections": [
{
"alias": "biography_blurb",
"args": null,
"concreteType": "ArtistBlurb",
"kind": "LinkedField",
"name": "biographyBlurb",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "text",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 4
}
],
"concreteType": "ArtistSeriesConnection",
"kind": "LinkedField",
"name": "artistSeriesConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "totalCount",
"storageKey": null
}
],
"storageKey": "artistSeriesConnection(first:4)"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ArtistSeriesMoreSeries_artist"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
(v0/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isBenefit",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isGalleryAuction",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "category",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "canRequestLotConditionsReport",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "conditionDescription",
"plural": false,
"selections": (v1/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "signature",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "signatureInfo",
"plural": false,
"selections": (v1/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "certificateOfAuthenticity",
"plural": false,
"selections": (v1/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "framed",
"plural": false,
"selections": (v1/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "series",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "publisher",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "manufacturer",
"storageKey": null
},
{
"alias": "image_rights",
"args": null,
"kind": "ScalarField",
"name": "imageRights",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "context",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isAuction",
"storageKey": null
}
],
"type": "Sale",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "contextGrids",
"plural": true,
"selections": [
{
"alias": "artworks",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 6
}
],
"concreteType": "ArtworkConnection",
"kind": "LinkedField",
"name": "artworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtworkEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": (v2/*: any*/),
"storageKey": null
}
],
"storageKey": "artworksConnection(first:6)"
}
],
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 1
}
],
"concreteType": "ArtistSeriesConnection",
"kind": "LinkedField",
"name": "artistSeriesConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtistSeriesEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtistSeries",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 20
},
{
"kind": "Literal",
"name": "input",
"value": {
"sort": "-decayed_merch"
}
}
],
"concreteType": "FilterArtworksConnection",
"kind": "LinkedField",
"name": "filterArtworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "FilterArtworksEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": (v2/*: any*/),
"storageKey": null
}
],
"storageKey": "filterArtworksConnection(first:20,input:{\"sort\":\"-decayed_merch\"})"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "artistSeriesConnection(first:1)"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "PartnerCard_artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "AboutWork_artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "OtherWorks_artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "AboutArtist_artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ArtworkDetails_artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ContextCard_artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ArtworkHistory_artwork"
},
{
"args": null,
"kind": "FragmentSpread",
"name": "ArtworksInSeriesRail_artwork"
}
],
"type": "Artwork",
"abstractKey": null
};
})();
(node as any).hash = '30f25615a303c3c2dde099834bad0a23';
export default node; | the_stack |
import * as jwt from 'jsonwebtoken';
import {
usGovernmentAuthentication,
authentication,
v32Authentication,
v31Authentication,
} from '../../utils/constants';
import { createBotFrameworkAuthenticationMiddleware } from '../createBotFrameworkAuthentication';
const mockGetKey = jest.fn().mockResolvedValue(`openIdMetadataKey`);
jest.mock('../../utils/openIdMetaData', () => ({
OpenIdMetadata: jest.fn().mockImplementation(() => ({
getKey: mockGetKey,
})),
}));
jest.mock('jsonwebtoken', () => ({
decode: jest.fn(),
verify: jest.fn(),
}));
describe('botFrameworkAuthenticationMiddleware', () => {
const authMiddleware = createBotFrameworkAuthenticationMiddleware();
const mockNext: any = jest.fn(() => null);
const mockEnd = jest.fn(() => null);
const mockStatus = jest.fn(() => {
return { end: mockEnd };
});
let mockPayload;
beforeEach(() => {
mockNext.mockClear();
mockEnd.mockClear();
mockStatus.mockClear();
(jwt.decode as jest.Mock).mockClear();
(jwt.verify as jest.Mock).mockClear();
(jwt.decode as jest.Mock).mockImplementation(() => ({
header: {
kid: 'someKeyId',
},
payload: mockPayload,
}));
(jwt.verify as jest.Mock).mockReturnValue('verifiedJwt');
mockGetKey.mockClear();
});
it('should call the next middleware and return if there is no auth header', async () => {
const mockHeader = jest.fn(() => false);
const req: any = {
get: mockHeader,
};
const res: any = jest.fn();
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(mockHeader).toHaveBeenCalled();
expect(mockNext).toHaveBeenCalled();
});
it('should return a 401 if the token is not provided in the header', async () => {
(jwt.decode as jest.Mock).mockReturnValue(null);
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(mockHeader).toHaveBeenCalled();
expect(jwt.decode).toHaveBeenCalledWith('someToken', { complete: true });
expect(mockStatus).toHaveBeenCalledWith(401);
expect(mockEnd).toHaveBeenCalled();
});
it('should return a 401 if a government bot provides a token in an unknown format', async () => {
mockPayload = {
aud: usGovernmentAuthentication.botTokenAudience,
ver: '99.9',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(mockStatus).toHaveBeenCalledWith(401);
expect(mockEnd).toHaveBeenCalled();
});
it('should authenticate with a v1.0 gov token', async () => {
mockPayload = {
aud: usGovernmentAuthentication.botTokenAudience,
ver: '1.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: usGovernmentAuthentication.botTokenAudience,
clockTolerance: 300,
issuer: usGovernmentAuthentication.tokenIssuerV1,
});
expect(req.jwt).toBe('verifiedJwt');
expect(mockNext).toHaveBeenCalled();
});
it('should authenticate with a v2.0 gov token', async () => {
mockPayload = {
aud: usGovernmentAuthentication.botTokenAudience,
ver: '2.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: usGovernmentAuthentication.botTokenAudience,
clockTolerance: 300,
issuer: usGovernmentAuthentication.tokenIssuerV2,
});
expect(req.jwt).toBe('verifiedJwt');
expect(mockNext).toHaveBeenCalled();
});
it('should return a 401 if verifying a gov jwt token fails', async () => {
mockPayload = {
aud: usGovernmentAuthentication.botTokenAudience,
ver: '1.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
(jwt.verify as jest.Mock).mockImplementation(() => {
throw new Error('unverifiedJwt');
});
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: usGovernmentAuthentication.botTokenAudience,
clockTolerance: 300,
issuer: usGovernmentAuthentication.tokenIssuerV1,
});
expect(req.jwt).toBeUndefined();
expect(mockNext).not.toHaveBeenCalled();
expect(mockStatus).toHaveBeenCalledWith(401);
expect(mockEnd).toHaveBeenCalled();
});
it(`should return a 500 if a bot's token can't be retrieved from openId metadata`, async () => {
mockPayload = {
aud: 'not gov',
ver: '1.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
// key should come back as falsy
mockGetKey.mockResolvedValueOnce(null);
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(mockStatus).toHaveBeenCalledWith(500);
expect(mockEnd).toHaveBeenCalled();
});
it('should return a 401 if a bot provides a token in an unknown format', async () => {
mockPayload = {
aud: 'not gov',
ver: '99.9',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(mockStatus).toHaveBeenCalledWith(401);
expect(mockEnd).toHaveBeenCalled();
expect(mockNext).not.toHaveBeenCalled();
});
it('should authenticate with a v1.0 token', async () => {
mockPayload = {
aud: 'not gov',
ver: '1.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: authentication.botTokenAudience,
clockTolerance: 300,
issuer: v32Authentication.tokenIssuerV1,
});
expect(req.jwt).toBe('verifiedJwt');
expect(mockNext).toHaveBeenCalled();
});
it('should authenticate with a v2.0 token', async () => {
mockPayload = {
aud: 'not gov',
ver: '2.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: authentication.botTokenAudience,
clockTolerance: 300,
issuer: v32Authentication.tokenIssuerV2,
});
expect(req.jwt).toBe('verifiedJwt');
expect(mockNext).toHaveBeenCalled();
});
it('should attempt authentication with v3.1 characteristics if v3.2 auth fails', async () => {
mockPayload = {
aud: 'not gov',
ver: '1.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
// verification attempt with v3.2 token characteristics should fail
(jwt.verify as jest.Mock).mockImplementationOnce(() => {
throw new Error('unverifiedJwt');
});
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(jwt.verify).toHaveBeenCalledTimes(2);
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: authentication.botTokenAudience,
clockTolerance: 300,
issuer: v32Authentication.tokenIssuerV1,
});
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: authentication.botTokenAudience,
clockTolerance: 300,
issuer: v31Authentication.tokenIssuer,
});
expect(req.jwt).toBe('verifiedJwt');
expect(mockNext).toHaveBeenCalled();
});
it('should return a 401 if auth with both v3.1 & v3.2 token characteristics fail', async () => {
mockPayload = {
aud: 'not gov',
ver: '1.0',
};
const mockHeader = jest.fn(() => 'Bearer someToken');
const req: any = {
get: mockHeader,
};
const res: any = {
status: mockStatus,
end: mockEnd,
};
(jwt.verify as jest.Mock)
// verification attempt with v3.2 token characteristics should fail
.mockImplementationOnce(() => {
throw new Error('unverifiedJwt');
})
// second attempt with v3.1 token characteristics should also fail
.mockImplementationOnce(() => {
throw new Error('unverifiedJwt');
});
const result = await authMiddleware(req, res, mockNext);
expect(result).toBeUndefined();
expect(jwt.verify).toHaveBeenCalledTimes(2);
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: authentication.botTokenAudience,
clockTolerance: 300,
issuer: v32Authentication.tokenIssuerV1,
});
expect(jwt.verify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', {
audience: authentication.botTokenAudience,
clockTolerance: 300,
issuer: v31Authentication.tokenIssuer,
});
expect(mockStatus).toHaveBeenCalledWith(401);
expect(mockEnd).toHaveBeenCalled();
expect(req.jwt).toBeUndefined();
expect(mockNext).not.toHaveBeenCalled();
});
}); | the_stack |
// -----------------------------------------------------------------------------
interface AnimationList
{
[name: string]: Animation;
};
class AnimationManager
{
/* tslint:disable:no-unused-variable */
static version = 1;
/* tslint:enable:no-unused-variable */
mathDevice: MathDevice;
// Methods
loadFile(path: string, callback: any)
{ debug.abort("abstract method"); }
loadData(data: any, prefix?: string)
{ debug.abort("abstract method"); }
get(name: string): Animation
{ debug.abort("abstract method"); return null; }
remove(name: string)
{ debug.abort("abstract method"); }
nodeHasSkeleton(node: Node): Skeleton
{ debug.abort("abstract method"); return null; }
getAll(): AnimationList
{ debug.abort("abstract method"); return null; }
setPathRemapping(prm: any, assetUrl: string)
{ debug.abort("abstract method"); }
static create(errorCallback?: { (msg: string): void; },
log?: HTMLElement): AnimationManager
{
if (!errorCallback)
{
/* tslint:disable:no-empty */
errorCallback = function (msg) {};
/* tslint:enable:no-empty */
}
var animations : AnimationList = {};
var pathRemapping = null;
var pathPrefix = "";
var loadAnimationData = function loadAnimationDataFn(data, prefix?)
{
var fileAnimations = data.animations;
var a;
for (a in fileAnimations)
{
if (fileAnimations.hasOwnProperty(a))
{
var name = prefix ? prefix + a : a;
if (animations[name])
{
fileAnimations[a] = animations[name];
continue;
}
var anim = fileAnimations[a];
var numNodes = anim.numNodes;
var nodeDataArray = anim.nodeData;
var n;
for (n = 0; n < numNodes; n += 1)
{
var nodeData = nodeDataArray[n];
var baseframe = nodeData.baseframe;
if (baseframe)
{
if (baseframe.rotation)
{
baseframe.rotation = this.mathDevice.quatBuild(baseframe.rotation[0],
baseframe.rotation[1],
baseframe.rotation[2],
baseframe.rotation[3]);
}
if (baseframe.translation)
{
baseframe.translation = this.mathDevice.v3Build(baseframe.translation[0],
baseframe.translation[1],
baseframe.translation[2]);
}
if (baseframe.scale)
{
baseframe.scale = this.mathDevice.v3Build(baseframe.scale[0],
baseframe.scale[1],
baseframe.scale[2]);
}
}
var keyframes = nodeData.keyframes;
if (keyframes && keyframes[0].hasOwnProperty('time'))
{
var numKeys = keyframes.length;
var k, keyframe;
var channels = {};
var channel, value, values, index;
var i;
nodeData.channels = channels;
for (k = 0; k < numKeys; k += 1)
{
keyframe = keyframes[k];
for (value in keyframe)
{
if (keyframe.hasOwnProperty(value) && value !== "time")
{
channel = channels[value];
if (!channel)
{
channel = {
count: 0,
offset: 0,
stride: keyframe[value].length + 1
};
channels[value] = channel;
channel.firstKey = k;
}
channel.lastKey = k;
channel.count += 1;
}
}
}
var numberOfValues = 0;
for (value in channels)
{
if (channels.hasOwnProperty(value))
{
channel = channels[value];
// TODO: For now we repeate values for intermediate keyframes
channel.count = 1 + channel.lastKey - channel.firstKey;
if (channel.firstKey)
{
channel.count += 1;
}
if (channel.lastKey !== numKeys - 1)
{
channel.count += 1;
}
channel.offset = numberOfValues;
channel.writeIndex = numberOfValues;
numberOfValues += channel.stride * channel.count;
}
}
var keyframeArray = null;
if (numberOfValues)
{
keyframeArray = new Float32Array(numberOfValues);
}
for (value in channels)
{
if (channels.hasOwnProperty(value))
{
channel = channels[value];
if (channel.firstKey)
{
keyframeArray[channel.writeIndex] = keyframes[channel.firstKey - 1].time;
values = baseframe[value];
for (i = 0; i < channel.stride - 1; i += 1)
{
keyframeArray[channel.writeIndex + 1 + i] = values[i];
}
channel.writeIndex += channel.stride;
}
if (channel.lastKey !== numKeys - 1)
{
index = channel.offset + (channel.count - 1) * channel.stride;
keyframeArray[index] = keyframes[channel.lastKey + 1].time;
values = baseframe[value];
for (i = 0; i < channel.stride - 1; i += 1)
{
keyframeArray[index + 1 + i] = values[i];
}
}
}
}
for (k = 0; k < numKeys; k += 1)
{
keyframe = keyframes[k];
for (value in channels)
{
if (channels.hasOwnProperty(value))
{
channel = channels[value];
if (k >= channel.firstKey && k <= channel.lastKey)
{
if (keyframe[value])
{
values = keyframe[value];
}
else
{
values = baseframe[value];
}
keyframeArray[channel.writeIndex] = keyframe.time;
for (i = 0; i < channel.stride - 1; i += 1)
{
keyframeArray[channel.writeIndex + 1 + i] = values[i];
}
channel.writeIndex += channel.stride;
}
}
}
}
for (value in channels)
{
if (channels.hasOwnProperty(value))
{
delete channel.writeIndex;
}
}
nodeData.keyframes = keyframeArray;
}
else if (keyframes)
{
nodeData.keyframes = new Float32Array(keyframes);
}
}
var bounds = anim.bounds;
var numFrames = bounds.length;
var f;
for (f = 0; f < numFrames; f += 1)
{
var bound = bounds[f];
bound.center = this.mathDevice.v3Build(bound.center[0],
bound.center[1],
bound.center[2]);
bound.halfExtent = this.mathDevice.v3Build(bound.halfExtent[0],
bound.halfExtent[1],
bound.halfExtent[2]);
}
animations[name] = anim;
}
}
};
/* tslint:disable:no-empty */
var loadAnimationFile = function loadAnimationFileFn(path, onload)
{
};
/* tslint:enable:no-empty */
var getAnimation = function getAnimationFn(name)
{
var animation = animations[name];
return animation;
};
var removeAnimation = function removeAnimationFn(name)
{
if (typeof animations[name] !== 'undefined')
{
delete animations[name];
}
};
var nodeHasSkeleton = function nodeHasSkeletonFn(node) : Skeleton
{
var renderables = node.renderables;
if (renderables)
{
var skeleton;
var numRenderables = renderables.length;
var r;
for (r = 0; r < numRenderables; r += 1)
{
if (renderables[r].geometry)
{
skeleton = renderables[r].geometry.skeleton;
if (skeleton)
{
return skeleton;
}
}
}
}
var children = node.children;
if (children)
{
var numChildren = children.length;
var c;
for (c = 0; c < numChildren; c += 1)
{
var childSkel = nodeHasSkeleton(children[c]);
if (childSkel)
{
return childSkel;
}
}
}
return undefined;
};
var animationManager = new AnimationManager();
animationManager.mathDevice = TurbulenzEngine.getMathDevice();
if (log)
{
animationManager.loadFile = function loadAnimationFileLogFn(path, callback)
{
log.innerHTML += "AnimationManager.loadFile: '" + path + "'";
return loadAnimationFile(path, callback);
};
animationManager.loadData =
function loadAnimationDataLogFn(data, prefix?)
{
log.innerHTML += "AnimationManager.loadData";
return loadAnimationData(data, prefix);
};
animationManager.get = function getAnimationLogFn(name)
{
log.innerHTML += "AnimationManager.get: '" + name + "'";
return getAnimation(name);
};
animationManager.remove = function removeAnimationLogFn(name)
{
log.innerHTML += "AnimationManager.remove: '" + name + "'";
removeAnimation(name);
};
}
else
{
animationManager.loadFile = loadAnimationFile;
animationManager.loadData = loadAnimationData;
animationManager.get = getAnimation;
animationManager.remove = removeAnimation;
animationManager.nodeHasSkeleton = nodeHasSkeleton;
}
animationManager.getAll = function getAllAnimationsFn()
{
return animations;
};
animationManager.setPathRemapping = function setPathRemappingFn(prm, assetUrl)
{
pathRemapping = prm;
pathPrefix = assetUrl;
};
return animationManager;
}
} | the_stack |
import { workspace, Selection } from 'vscode';
import { resetConfiguration, updateConfiguration } from "../util/configuration";
import { testCommand } from "../util/generic";
suite("Ordered list renumbering.", () => {
suiteSetup(async () => {
await resetConfiguration();
});
suiteTeardown(async () => {
await resetConfiguration();
});
test("Enter key. Fix ordered marker", () => {
return testCommand('markdown.extension.onEnterKey',
[
'1. one',
'2. two'
],
new Selection(0, 6, 0, 6),
[
'1. one',
'2. ',
'3. two'
],
new Selection(1, 3, 1, 3));
});
test("Backspace key. Fix ordered marker. 1", () => {
return testCommand('markdown.extension.onBackspaceKey',
[
' 1. item1'
],
new Selection(0, 7, 0, 7),
[
'1. item1'
],
new Selection(0, 3, 0, 3));
});
test("Backspace key. Fix ordered marker. 2", () => {
return testCommand('markdown.extension.onBackspaceKey',
[
'1. item1',
' 5. item2'
],
new Selection(1, 6, 1, 6),
[
'1. item1',
'2. item2'
],
new Selection(1, 3, 1, 3));
});
test("Backspace key. Fix ordered marker. 3", () => {
return testCommand('markdown.extension.onBackspaceKey',
[
'1. item1',
' 1. item1-1',
' 2. item1-2',
' 3. item1-3',
' 4. item1-4'
],
new Selection(3, 6, 3, 6),
[
'1. item1',
' 1. item1-1',
' 2. item1-2',
'2. item1-3',
' 1. item1-4'
],
new Selection(3, 3, 3, 3));
});
test("Backspace key. Fix ordered marker. 4: Multi-line list item", () => {
return testCommand('markdown.extension.onBackspaceKey',
[
'1. item1',
' 1. item1-1',
' item1-2',
' 2. item1-3',
' 3. item1-4'
],
new Selection(3, 6, 3, 6),
[
'1. item1',
' 1. item1-1',
' item1-2',
'2. item1-3',
' 1. item1-4'
],
new Selection(3, 3, 3, 3));
});
test("Backspace key. Fix ordered marker. 5: Selection range", () => {
return testCommand('markdown.extension.onBackspaceKey',
[
'1. item1',
'2. item2',
' 1. item1-1',
' 2. item1-2',
' 3. item1-3',
'3. item3'
],
new Selection(1, 0, 3, 0),
[
'1. item1',
' 1. item1-2',
' 2. item1-3',
'2. item3'
],
new Selection(1, 0, 1, 0));
});
test("Backspace key. github#411", () => {
return testCommand('markdown.extension.onBackspaceKey',
[
'1. one',
'2. ',
'',
'# Heading',
'',
'3. three'
],
new Selection(1, 3, 1, 3),
[
'1. one',
' ',
'',
'# Heading',
'',
'3. three'
],
new Selection(1, 3, 1, 3));
});
test("Tab key. Fix ordered marker. 1", () => {
return testCommand('markdown.extension.onTabKey',
[
'2. item1'
],
new Selection(0, 3, 0, 3),
[
' 1. item1'
],
new Selection(0, 7, 0, 7));
});
test("Tab key. Fix ordered marker. 2", () => {
return testCommand('markdown.extension.onTabKey',
[
'2. [ ] item1'
],
new Selection(0, 7, 0, 7),
[
' 1. [ ] item1'
],
new Selection(0, 11, 0, 11));
});
test("Tab key. Fix ordered marker. 3", () => {
return testCommand('markdown.extension.onTabKey',
[
'1. test',
' 1. test',
' 2. test',
'2. test',
' 1. test'
],
new Selection(3, 3, 3, 3),
[
'1. test',
' 1. test',
' 2. test',
' 3. test',
' 4. test'
],
new Selection(3, 6, 3, 6));
});
test("Tab key. Fix ordered marker. 4: Multi-line list item", () => {
return testCommand('markdown.extension.onTabKey',
[
'1. test',
' 1. test',
' test',
'2. test',
' 1. test'
],
new Selection(3, 3, 3, 3),
[
'1. test',
' 1. test',
' test',
' 2. test',
' 3. test'
],
new Selection(3, 6, 3, 6));
});
test("Tab key. Fix ordered marker. 5: Selection range", () => {
return testCommand('markdown.extension.onTabKey',
[
'1. test',
'2. test',
' 1. test',
' 2. test',
'3. test'
],
new Selection(1, 0, 3, 0),
[
'1. test',
' 1. test',
' 1. test',
' 2. test',
'2. test'
],
// Should have been (1, 0, 3, 0) if we want to accurately mimic `editor.action.indentLines`
new Selection(1, 3, 3, 0));
});
test("Move Line Up. 1: '2. |'", () => {
return testCommand('markdown.extension.onMoveLineUp',
[
'1. item1',
'2. item2'
],
new Selection(1, 3, 1, 3),
[
'1. item2',
'2. item1'
],
new Selection(0, 3, 0, 3));
});
test("Move Line Up. 2: '2. |'", () => {
return testCommand('markdown.extension.onMoveLineUp',
[
'1. item1',
'2. item2'
],
new Selection(1, 3, 1, 3),
[
'1. item2',
'2. item1'
],
new Selection(0, 3, 0, 3));
});
test("Move Line Up. 3: '2. [ ] |'", () => {
return testCommand('markdown.extension.onMoveLineUp',
[
'1. [ ] item1',
'2. [ ] item2'
],
new Selection(1, 0, 1, 0),
[
'1. [ ] item2',
'2. [ ] item1'
],
new Selection(0, 0, 0, 0));
});
test("Move Line Down. 1: '1. |'", () => {
return testCommand('markdown.extension.onMoveLineDown',
[
'1. item1',
'2. item2'
],
new Selection(0, 3, 0, 3),
[
'1. item2',
'2. item1'
],
new Selection(1, 3, 1, 3));
});
test("Move Line Down. 2: '1. |'", () => {
return testCommand('markdown.extension.onMoveLineDown',
[
'1. item1',
'2. item2'
],
new Selection(0, 3, 0, 3),
[
'1. item2',
'2. item1'
],
new Selection(1, 3, 1, 3));
});
test("Move Line Down. 3: '1. [ ] |'", () => {
return testCommand('markdown.extension.onMoveLineDown',
[
'1. [ ] item1',
'2. [ ] item2'
],
new Selection(0, 0, 0, 0),
[
'1. [ ] item2',
'2. [ ] item1'
],
new Selection(1, 0, 1, 0));
});
test("Copy Line Up. 1: '2. |'", () => {
return testCommand('markdown.extension.onCopyLineUp',
[
'1. item1',
'2. item2'
],
new Selection(1, 3, 1, 3),
[
'1. item1',
'2. item2',
'3. item2'
],
new Selection(1, 3, 1, 3));
});
test("Copy Line Up. 2: '2. |'", () => {
return testCommand('markdown.extension.onCopyLineUp',
[
'1. item1',
'2. item2'
],
new Selection(1, 3, 1, 3),
[
'1. item1',
'2. item2',
'3. item2'
],
new Selection(1, 3, 1, 3));
});
test("Copy Line Up. 3: '2. [ ] |'", () => {
return testCommand('markdown.extension.onCopyLineUp',
[
'1. [ ] item1',
'2. [x] item2'
],
new Selection(1, 0, 1, 0),
[
'1. [ ] item1',
'2. [x] item2',
'3. [x] item2'
],
new Selection(1, 0, 1, 0));
});
test("Copy Line Down. 1: '1. |'", () => {
return testCommand('markdown.extension.onCopyLineDown',
[
'1. item1',
'2. item2'
],
new Selection(0, 3, 0, 3),
[
'1. item1',
'2. item1',
'3. item2'
],
new Selection(1, 3, 1, 3));
});
test("Copy Line Down. 2: '1. |'", () => {
return testCommand('markdown.extension.onCopyLineDown',
[
'1. item1',
'2. item2'
],
new Selection(0, 3, 0, 3),
[
'1. item1',
'2. item1',
'3. item2'
],
new Selection(1, 3, 1, 3));
});
test("Copy Line Down. 3: '1. [ ] |'", () => {
return testCommand('markdown.extension.onCopyLineDown',
[
'1. [x] item1',
'2. [ ] item2'
],
new Selection(0, 0, 0, 0),
[
'1. [x] item1',
'2. [x] item1',
'3. [ ] item2'
],
new Selection(1, 0, 1, 0));
});
test("Indent Lines. 1: No selection range", () => {
return testCommand('markdown.extension.onIndentLines',
[
'1. test',
'2. test',
' 1. test',
'3. test'
],
new Selection(1, 5, 1, 5),
[
'1. test',
' 1. test',
' 2. test',
'2. test'
],
new Selection(1, 8, 1, 8));
});
test("Indent Lines. 2: Selection range", () => {
return testCommand('markdown.extension.onIndentLines',
[
'1. test',
'2. test',
'3. test',
' 1. test',
'4. test'
],
new Selection(1, 0, 3, 0),
[
'1. test',
' 1. test',
' 2. test',
' 3. test',
'2. test'
],
// Should have been (1, 0, 3, 0) if we want to accurately mimic `editor.action.indentLines`
new Selection(1, 3, 3, 0));
});
test("Outdent Lines. 1: No selection range", () => {
return testCommand('markdown.extension.onOutdentLines',
[
'1. test',
' 1. test',
' 2. test',
'2. test'
],
new Selection(1, 0, 1, 0),
[
'1. test',
'2. test',
' 1. test',
'3. test'
],
new Selection(1, 0, 1, 0));
});
test("Outdent Lines. 2: Selection range", () => {
return testCommand('markdown.extension.onOutdentLines',
[
'1. test',
' 1. test',
' 2. test',
' 3. test',
'2. test'
],
new Selection(1, 0, 3, 0),
[
'1. test',
'2. test',
'3. test',
' 1. test',
'4. test'
],
new Selection(1, 0, 3, 0));
});
}); | the_stack |
import { MongoClient, ObjectId, WithID } from "../deps.ts";
export type DBModule = Omit<Module, "name"> & { _id: string };
export type ScoredModule = DBModule & { search_score: number };
export interface Module {
name: string;
type: string;
repo_id: number;
owner: string;
repo: string;
description: string;
star_count: number;
is_unlisted: boolean;
created_at: Date;
}
export interface SearchOptions {
limit: number;
page: number;
query?: string;
sort?: Sort | "random" | "search_order";
}
export type ListModuleResult = [SearchOptions, ScoredModule[]];
export type Sort = "stars" | "newest" | "oldest";
export type BuildStatus =
| "queued"
| "success"
| "error"
| "publishing"
| "analyzing_dependencies";
const sort = {
stars: { "star_count": -1 },
newest: { "created_at": -1 },
oldest: { "created_at": 1 },
random: null,
// deno-lint-ignore camelcase
search_order: null,
};
export const SortValues = Object.keys(sort);
export interface SearchResult {
name: string;
description: string;
star_count: number;
search_score: number;
}
export interface RecentlyAddedModuleResult {
name: string;
description: string;
star_count: number;
created_at: Date;
}
export interface RecentlyAddedUploadedVersions {
name: string;
version: string;
created_at: Date;
}
export interface Build {
id: string;
created_at: Date;
options: {
moduleName: string;
type: string;
repository: string;
ref: string;
version: string;
subdir?: string;
};
status: BuildStatus;
message?: string;
stats?: BuildStats;
}
export interface BuildStats {
total_files: number;
total_size: number;
}
export interface OwnerQuota {
owner: string;
type: string;
max_modules: number;
max_total_size?: number;
blocked: boolean;
}
export type DBOwnerQuota = Omit<OwnerQuota, "owner"> & {
_id: string;
};
export class Database {
private mongo = new MongoClient();
protected db = this.mongo.database("production");
_modules = this.db.collection<DBModule>("modules");
_builds = this.db.collection<Omit<Build, "id"> & { _id: ObjectId }>("builds");
_owner_quotas = this.db.collection<DBOwnerQuota>("owner_quotas");
constructor(mongoUri: string) {
this.mongo.connectWithUri(mongoUri);
if (this.mongo.clientId === null || this.mongo.clientId === undefined) {
throw new Error("Could not connect to database.");
}
}
_entryToModule(entry: DBModule): Module {
return {
name: entry._id,
type: entry.type,
repo_id: entry.repo_id,
owner: entry.owner,
repo: entry.repo,
description: entry.description,
star_count: entry.star_count,
is_unlisted: entry.is_unlisted ?? false,
created_at: entry.created_at,
};
}
async getModule(name: string): Promise<Module | null> {
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
// deno-lint-ignore no-explicit-any
const entry = await this._modules.findOne({ _id: name.toString() } as any);
if (entry === null) return null;
return this._entryToModule(entry);
}
async saveModule(module: Module): Promise<void> {
await this._modules.updateOne(
{
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
// deno-lint-ignore no-explicit-any
_id: module.name as any,
},
{
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
// deno-lint-ignore no-explicit-any
_id: module.name as any,
type: module.type,
repo_id: module.repo_id,
owner: module.owner,
repo: module.repo,
description: module.description,
star_count: module.star_count,
is_unlisted: module.is_unlisted,
created_at: module.created_at ?? new Date(),
},
{ upsert: true },
);
}
async listModules(options: SearchOptions): Promise<ListModuleResult> {
if (typeof options.limit !== "number") {
throw new Error("limit must be a number");
}
if (typeof options.page !== "number") {
throw new Error("page must be a number");
}
if (options.page <= 0) {
throw new Error("page must be 1 or larger");
}
if (options.sort === undefined) {
options.sort = "stars";
}
// The random sort option is not compatible with the 'search' and 'page'
// options.
if (options.sort === "random") {
options.page = 1;
options.query = undefined;
return [
options,
(await this._modules.aggregate([
{
$match: {
is_unlisted: { $not: { $eq: true } },
},
},
{
$sample: {
size: options.limit,
},
},
]) as ScoredModule[]),
];
}
// If search is present, add a search step to the aggregation pipeline
let searchAggregation;
if (options.query) {
options.sort = "search_order";
searchAggregation = [
{
$search: {
text: {
query: options.query,
path: ["_id", "description"],
fuzzy: {},
},
},
},
{
$match: {
is_unlisted: { $not: { $eq: true } },
},
},
{
$addFields: {
search_score: {
$meta: "searchScore",
},
},
},
{
$sort: {
search_score: -1,
},
},
];
} else {
searchAggregation = [
{
$match: {
is_unlisted: { $not: { $eq: true } },
},
},
{
$sort: sort[options.sort],
},
];
}
// Query the database
const docs = (await this._modules.aggregate([
...searchAggregation,
{
$skip: (options.page - 1) * options.limit,
},
{
$limit: options.limit,
},
])) as ScoredModule[];
return [options, docs];
}
async listAllModules(): Promise<Module[]> {
const entries = await this._modules.find({});
return entries.map(this._entryToModule);
}
async listAllModuleNames(): Promise<string[]> {
const results = await this._modules.aggregate([
{
$match: {
is_unlisted: { $not: { $eq: true } },
},
},
{
$project: {
_id: 1,
},
},
]) as { _id: string }[];
return results.map((o) => o._id);
}
countModules(): Promise<number> {
return this._modules.count({
is_unlisted: { $not: { $eq: true } },
});
}
async countModulesForRepository(
repoId: number,
): Promise<number> {
const modules = await this._modules.find({ repo_id: repoId });
return modules.length;
}
async countModulesForOwner(owner: string): Promise<number> {
const modules = await this._modules.find({ owner });
return modules.length;
}
async deleteModule(name: string): Promise<void> {
const resp = await this._modules.deleteOne({
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
// deno-lint-ignore no-explicit-any
_id: name as any,
});
if (!resp) {
throw new Error(`Failed to delete module [ ${name} ]`);
}
return;
}
async getBuild(id: string): Promise<Build | null> {
const build = await this._builds.findOne({ _id: ObjectId(id) });
if (build === null) return null;
return {
id: build._id.$oid,
created_at: build.created_at,
options: build.options,
status: build.status,
message: build.message,
stats: build.stats,
};
}
async listSuccessfulBuilds(name: string): Promise<Build[]> {
const builds = await this._builds.aggregate([
{
$match: {
"options.moduleName": { $eq: name },
status: { $eq: "success" },
},
},
]) as (Build & WithID)[];
return builds.map((b) => {
return {
id: b._id.$oid,
created_at: b.created_at,
options: b.options,
status: b.status,
message: b.message,
stats: b.stats,
};
});
}
async getBuildForVersion(
name: string,
version: string,
): Promise<Build | null> {
const build = await this._builds.findOne({
// @ts-ignore because the deno_mongo typings are incorrect
"options.moduleName": name,
"options.version": version,
});
if (build === null) return null;
return {
id: build._id.$oid,
created_at: build.created_at,
options: build.options,
status: build.status,
message: build.message,
stats: build.stats,
};
}
countAllVersions(): Promise<number> {
return this._builds.count({});
}
async createBuild(
build: Omit<Omit<Build, "id">, "created_at">,
): Promise<string> {
const id = await this._builds.insertOne({
created_at: new Date(),
options: build.options,
status: build.status,
message: build.message,
stats: build.stats,
});
return id.$oid;
}
async saveBuild(build: Build): Promise<void> {
await this._builds.updateOne(
{
_id: ObjectId(build.id),
},
{
_id: ObjectId(build.id),
created_at: build.created_at,
options: build.options,
status: build.status,
message: build.message,
stats: build.stats,
},
{ upsert: true },
);
}
async getOwnerQuota(
owner: string,
): Promise<OwnerQuota | null> {
const ownerQuota = await this._owner_quotas.findOne({
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
// deno-lint-ignore no-explicit-any
_id: owner as any,
});
if (ownerQuota === null) return null;
return {
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
owner: ownerQuota._id as string,
type: ownerQuota.type,
max_modules: ownerQuota.max_modules,
max_total_size: ownerQuota.max_total_size,
blocked: ownerQuota.blocked,
};
}
async saveOwnerQuota(
ownerQuota: OwnerQuota,
): Promise<void> {
await this._owner_quotas.updateOne(
{
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
// deno-lint-ignore no-explicit-any
_id: ownerQuota.owner as any,
},
{
// TODO: https://github.com/manyuanrong/deno_mongo/issues/76
// deno-lint-ignore no-explicit-any
_id: ownerQuota.owner as any,
type: ownerQuota.type,
max_modules: ownerQuota.max_modules,
max_total_size: ownerQuota.max_total_size,
blocked: ownerQuota.blocked,
},
{ upsert: true },
);
}
async listRecentlyAddedModules(): Promise<RecentlyAddedModuleResult[]> {
const results = await this._modules.aggregate([
{
$match: {
is_unlisted: { $not: { $eq: true } },
},
},
{
$sort: {
created_at: -1,
},
},
{
$limit: 10,
},
]) as DBModule[];
return results.map((doc) => ({
name: doc._id,
description: doc.description,
star_count: doc.star_count,
created_at: doc.created_at,
}));
}
async listRecentlyUploadedVersions(): Promise<
RecentlyAddedUploadedVersions[]
> {
const results = await this._builds.aggregate([
{
$sort: {
created_at: -1,
},
},
{
$limit: 10,
},
]) as Build[];
return results.map((doc) => ({
name: doc.options.moduleName,
version: doc.options.version,
created_at: doc.created_at,
}));
}
} | the_stack |
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, run "npm run codegen" to regenerate this file.
*/
export interface CensysCertificatesData {
validation?: {
nss?: {
paths?: {
path?: string;
[k: string]: unknown;
};
/**
* True if the certificate is explicitly blacklisted by some method than OneCRL/CRLSet. For example, a set of certificates revoked by Cloudflare are blacklisted by SPKI hash in Chrome.
*/
blacklisted?: boolean;
/**
* True if now or at some point in the past there existed a path from the certificate to the root store.
*/
had_trusted_path?: boolean;
/**
* True if the certificate is explicitly whitelisted, e.g. the set of trusted WoSign certificates Apple uses.
*/
whitelisted?: boolean;
/**
* True if the certificate is in the revocation set (e.g. OneCRL) associated with this root store.
*/
in_revocation_set?: boolean;
/**
* True if the certificate is valid now or was ever valid in the past.
*/
was_valid?: boolean;
/**
* ((has_trusted_path && !revoked && !blacklisted) || whitelisted) && !expired
*/
valid?: boolean;
parents?: string;
/**
* True if there exists a path from the certificate to the root store.
*/
trusted_path?: boolean;
/**
* Indicates if the certificate is a root, intermediate, or leaf.
*/
type?: string;
[k: string]: unknown;
};
google_ct_primary?: {
paths?: {
path?: string;
[k: string]: unknown;
};
/**
* True if the certificate is explicitly blacklisted by some method than OneCRL/CRLSet. For example, a set of certificates revoked by Cloudflare are blacklisted by SPKI hash in Chrome.
*/
blacklisted?: boolean;
/**
* True if now or at some point in the past there existed a path from the certificate to the root store.
*/
had_trusted_path?: boolean;
/**
* True if the certificate is explicitly whitelisted, e.g. the set of trusted WoSign certificates Apple uses.
*/
whitelisted?: boolean;
/**
* True if the certificate is in the revocation set (e.g. OneCRL) associated with this root store.
*/
in_revocation_set?: boolean;
/**
* True if the certificate is valid now or was ever valid in the past.
*/
was_valid?: boolean;
/**
* ((has_trusted_path && !revoked && !blacklisted) || whitelisted) && !expired
*/
valid?: boolean;
parents?: string;
/**
* True if there exists a path from the certificate to the root store.
*/
trusted_path?: boolean;
/**
* Indicates if the certificate is a root, intermediate, or leaf.
*/
type?: string;
[k: string]: unknown;
};
apple?: {
paths?: {
path?: string;
[k: string]: unknown;
};
/**
* True if the certificate is explicitly blacklisted by some method than OneCRL/CRLSet. For example, a set of certificates revoked by Cloudflare are blacklisted by SPKI hash in Chrome.
*/
blacklisted?: boolean;
/**
* True if now or at some point in the past there existed a path from the certificate to the root store.
*/
had_trusted_path?: boolean;
/**
* True if the certificate is explicitly whitelisted, e.g. the set of trusted WoSign certificates Apple uses.
*/
whitelisted?: boolean;
/**
* True if the certificate is in the revocation set (e.g. OneCRL) associated with this root store.
*/
in_revocation_set?: boolean;
/**
* True if the certificate is valid now or was ever valid in the past.
*/
was_valid?: boolean;
/**
* ((has_trusted_path && !revoked && !blacklisted) || whitelisted) && !expired
*/
valid?: boolean;
parents?: string;
/**
* True if there exists a path from the certificate to the root store.
*/
trusted_path?: boolean;
/**
* Indicates if the certificate is a root, intermediate, or leaf.
*/
type?: string;
[k: string]: unknown;
};
microsoft?: {
paths?: {
path?: string;
[k: string]: unknown;
};
/**
* True if the certificate is explicitly blacklisted by some method than OneCRL/CRLSet. For example, a set of certificates revoked by Cloudflare are blacklisted by SPKI hash in Chrome.
*/
blacklisted?: boolean;
/**
* True if now or at some point in the past there existed a path from the certificate to the root store.
*/
had_trusted_path?: boolean;
/**
* True if the certificate is explicitly whitelisted, e.g. the set of trusted WoSign certificates Apple uses.
*/
whitelisted?: boolean;
/**
* True if the certificate is in the revocation set (e.g. OneCRL) associated with this root store.
*/
in_revocation_set?: boolean;
/**
* True if the certificate is valid now or was ever valid in the past.
*/
was_valid?: boolean;
/**
* ((has_trusted_path && !revoked && !blacklisted) || whitelisted) && !expired
*/
valid?: boolean;
parents?: string;
/**
* True if there exists a path from the certificate to the root store.
*/
trusted_path?: boolean;
/**
* Indicates if the certificate is a root, intermediate, or leaf.
*/
type?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
parent_spki_subject_fingerprint?: string;
tags?: string;
added_at?: string;
fingerprint_sha256?: string;
raw?: string;
parents?: string;
zlint?: {
version?: string;
errors_present?: boolean;
fatals_present?: boolean;
warnings_present?: boolean;
lints?: {
e_name_constraint_empty?: string;
e_ev_valid_time_too_long?: string;
e_sub_ca_must_not_contain_any_policy?: string;
e_root_ca_extended_key_usage_present?: string;
e_ext_ian_uri_format_invalid?: string;
e_rsa_mod_less_than_2048_bits?: string;
e_ext_san_missing?: string;
e_sub_cert_cert_policy_empty?: string;
e_sub_ca_crl_distribution_points_does_not_contain_url?: string;
e_sub_cert_postal_code_must_not_appear?: string;
e_ext_cert_policy_disallowed_any_policy_qualifier?: string;
e_ext_san_not_critical_without_subject?: string;
e_sub_ca_crl_distribution_points_missing?: string;
e_cert_policy_ov_requires_country?: string;
w_name_constraint_on_x400?: string;
w_multiple_subject_rdn?: string;
e_ian_dns_name_includes_null_char?: string;
e_ext_name_constraints_not_in_ca?: string;
e_subject_locality_name_max_length?: string;
n_contains_redacted_dnsname?: string;
e_international_dns_name_not_unicode?: string;
e_sub_cert_locality_name_must_not_appear?: string;
w_ext_cert_policy_contains_noticeref?: string;
e_sub_cert_country_name_must_appear?: string;
e_ext_key_usage_cert_sign_without_ca?: string;
w_root_ca_basic_constraints_path_len_constraint_field_present?: string;
e_cab_dv_conflicts_with_street?: string;
e_ext_subject_key_identifier_missing_ca?: string;
e_sub_cert_aia_marked_critical?: string;
w_sub_cert_aia_does_not_contain_issuing_ca_url?: string;
e_san_dns_name_includes_null_char?: string;
e_subject_common_name_max_length?: string;
e_ext_key_usage_without_bits?: string;
e_utc_time_not_in_zulu?: string;
e_ext_freshest_crl_marked_critical?: string;
e_international_dns_name_not_nfkc?: string;
e_ext_san_empty_name?: string;
e_sub_cert_key_usage_cert_sign_bit_set?: string;
w_ext_san_critical_with_subject_dn?: string;
w_sub_ca_aia_does_not_contain_issuing_ca_url?: string;
e_subject_state_name_max_length?: string;
w_san_iana_pub_suffix_empty?: string;
e_ext_authority_key_identifier_missing?: string;
e_ext_san_contains_reserved_ip?: string;
e_ext_san_directory_name_present?: string;
e_distribution_point_incomplete?: string;
e_dsa_params_missing?: string;
e_dnsname_underscore_in_sld?: string;
e_cab_dv_conflicts_with_province?: string;
e_ian_wildcard_not_first?: string;
n_ca_digital_signature_not_set?: string;
e_dnsname_not_valid_tld?: string;
e_issuer_field_empty?: string;
e_sub_ca_crl_distribution_points_marked_critical?: string;
e_cab_dv_conflicts_with_org?: string;
e_ca_key_usage_missing?: string;
e_ext_san_uniform_resource_identifier_present?: string;
e_ext_subject_directory_attr_critical?: string;
e_name_constraint_maximum_not_absent?: string;
e_cert_policy_iv_requires_country?: string;
e_cab_dv_conflicts_with_postal?: string;
e_inhibit_any_policy_not_critical?: string;
e_ev_organization_name_missing?: string;
e_public_key_type_not_allowed?: string;
e_old_sub_ca_rsa_mod_less_than_1024_bits?: string;
e_ext_san_uri_not_ia5?: string;
e_sub_cert_key_usage_crl_sign_bit_set?: string;
e_ext_policy_constraints_not_critical?: string;
e_subject_country_not_iso?: string;
e_signature_algorithm_not_supported?: string;
e_cab_iv_requires_personal_name?: string;
e_san_dns_name_starts_with_period?: string;
e_ext_policy_map_any_policy?: string;
e_subject_not_dn?: string;
e_ext_policy_constraints_empty?: string;
e_san_bare_wildcard?: string;
e_ext_san_uri_host_not_fqdn_or_ip?: string;
e_ian_dns_name_starts_with_period?: string;
e_ca_key_usage_not_critical?: string;
w_root_ca_contains_cert_policy?: string;
w_sub_cert_certificate_policies_marked_critical?: string;
w_name_constraint_on_edi_party_name?: string;
e_ext_san_edi_party_name_present?: string;
e_generalized_time_includes_fraction_seconds?: string;
e_dnsname_left_label_wildcard_correct?: string;
n_subject_common_name_included?: string;
w_multiple_issuer_rdn?: string;
e_subject_empty_without_san?: string;
w_sub_ca_name_constraints_not_critical?: string;
e_dsa_correct_order_in_subgroup?: string;
w_dnsname_underscore_in_trd?: string;
e_sub_cert_aia_missing?: string;
e_root_ca_key_usage_present?: string;
e_utc_time_does_not_include_seconds?: string;
w_name_constraint_on_registered_id?: string;
e_serial_number_longer_than_20_octets?: string;
e_sub_cert_valid_time_too_long?: string;
w_ext_key_usage_not_critical?: string;
e_sub_cert_crl_distribution_points_marked_critical?: string;
w_ext_aia_access_location_missing?: string;
e_generalized_time_not_in_zulu?: string;
e_ca_key_cert_sign_not_set?: string;
e_dsa_improper_modulus_or_divisor_size?: string;
e_serial_number_not_positive?: string;
w_ext_policy_map_not_in_cert_policy?: string;
e_sub_cert_or_sub_ca_using_sha1?: string;
e_ext_name_constraints_not_critical?: string;
e_validity_time_not_positive?: string;
e_ext_san_dns_name_too_long?: string;
e_sub_cert_eku_missing?: string;
w_eku_critical_improperly?: string;
w_subject_dn_trailing_whitespace?: string;
e_dnsname_empty_label?: string;
w_sub_cert_sha1_expiration_too_long?: string;
e_sub_cert_not_is_ca?: string;
e_name_constraint_minimum_non_zero?: string;
e_ev_locality_name_missing?: string;
e_ext_ian_uri_host_not_fqdn_or_ip?: string;
e_cert_unique_identifier_version_not_2_or_3?: string;
e_generalized_time_does_not_include_seconds?: string;
e_ev_country_name_missing?: string;
e_cab_dv_conflicts_with_locality?: string;
e_path_len_constraint_improperly_included?: string;
e_sub_ca_eku_name_constraints?: string;
e_sub_ca_aia_marked_critical?: string;
w_rsa_mod_not_odd?: string;
e_sub_cert_aia_does_not_contain_ocsp_url?: string;
e_ev_business_category_missing?: string;
e_sub_ca_eku_missing?: string;
e_sub_cert_locality_name_must_appear?: string;
e_sub_cert_given_name_surname_contains_correct_policy?: string;
e_cab_ov_requires_org?: string;
e_sub_cert_street_address_should_not_exist?: string;
e_ext_aia_marked_critical?: string;
e_sub_ca_certificate_policies_missing?: string;
w_issuer_dn_leading_whitespace?: string;
w_ext_policy_map_not_critical?: string;
e_ext_authority_key_identifier_no_key_identifier?: string;
e_cert_policy_ov_requires_province_or_locality?: string;
e_ec_improper_curves?: string;
e_dnsname_wildcard_only_in_left_label?: string;
e_rsa_public_exponent_too_small?: string;
w_ext_crl_distribution_marked_critical?: string;
e_rsa_exp_negative?: string;
e_subject_common_name_not_from_san?: string;
e_subject_organizational_unit_name_max_length?: string;
n_sub_ca_eku_not_technically_constrained?: string;
e_ca_subject_field_empty?: string;
e_root_ca_key_usage_must_be_critical?: string;
e_ext_ian_dns_not_ia5_string?: string;
w_ext_cert_policy_explicit_text_includes_control?: string;
w_ext_ian_critical?: string;
e_sub_cert_certificate_policies_missing?: string;
w_rsa_mod_factors_smaller_than_752?: string;
e_ian_bare_wildcard?: string;
w_serial_number_low_entropy?: string;
e_ext_san_no_entries?: string;
e_sub_ca_aia_does_not_contain_ocsp_url?: string;
w_sub_ca_eku_critical?: string;
w_ext_subject_key_identifier_missing_sub_cert?: string;
e_rsa_no_public_key?: string;
e_dnsname_hyphen_in_sld?: string;
e_cert_policy_iv_requires_province_or_locality?: string;
e_subject_contains_noninformational_value?: string;
w_dnsname_wildcard_left_of_public_suffix?: string;
e_ext_ian_uri_not_ia5?: string;
w_sub_ca_certificate_policies_marked_critical?: string;
e_sub_ca_aia_missing?: string;
e_basic_constraints_not_critical?: string;
w_rsa_public_exponent_not_in_range?: string;
e_ext_cert_policy_duplicate?: string;
e_ext_cert_policy_explicit_text_too_long?: string;
w_issuer_dn_trailing_whitespace?: string;
e_ext_san_dns_not_ia5_string?: string;
e_sub_cert_province_must_not_appear?: string;
e_subject_contains_reserved_ip?: string;
e_dsa_shorter_than_2048_bits?: string;
e_dnsname_bad_character_in_label?: string;
e_san_wildcard_not_first?: string;
e_ext_ian_empty_name?: string;
w_ext_cert_policy_explicit_text_not_nfc?: string;
e_ca_country_name_invalid?: string;
e_ca_country_name_missing?: string;
w_sub_cert_eku_extra_values?: string;
e_dnsname_contains_bare_iana_suffix?: string;
w_ian_iana_pub_suffix_empty?: string;
e_old_root_ca_rsa_mod_less_than_2048_bits?: string;
e_ca_is_ca?: string;
e_sub_cert_province_must_appear?: string;
e_ca_common_name_missing?: string;
e_path_len_constraint_zero_or_less?: string;
e_ext_san_uri_relative?: string;
e_ext_subject_key_identifier_critical?: string;
e_sub_cert_eku_server_auth_client_auth_missing?: string;
e_wrong_time_format_pre2050?: string;
e_dsa_unique_correct_representation?: string;
e_ext_ian_uri_relative?: string;
e_ext_cert_policy_explicit_text_ia5_string?: string;
w_distribution_point_missing_ldap_or_uri?: string;
e_subject_info_access_marked_critical?: string;
e_ext_san_other_name_present?: string;
e_ca_crl_sign_not_set?: string;
e_ev_serial_number_missing?: string;
e_ext_san_registered_id_present?: string;
e_ext_san_uri_format_invalid?: string;
e_ext_ian_space_dns_name?: string;
e_dnsname_label_too_long?: string;
e_ext_san_rfc822_name_present?: string;
e_sub_cert_crl_distribution_points_does_not_contain_url?: string;
e_ca_organization_name_missing?: string;
w_subject_dn_leading_whitespace?: string;
e_ext_ian_rfc822_format_invalid?: string;
e_subject_organization_name_max_length?: string;
e_cert_contains_unique_identifier?: string;
e_ext_duplicate_extension?: string;
e_invalid_certificate_version?: string;
e_ext_ian_no_entries?: string;
e_cert_extensions_version_not_3?: string;
e_old_sub_cert_rsa_mod_less_than_1024_bits?: string;
e_ext_san_space_dns_name?: string;
e_ext_authority_key_identifier_critical?: string;
e_ext_san_rfc822_format_invalid?: string;
e_rsa_public_exponent_not_odd?: string;
w_ext_cert_policy_explicit_text_not_utf8?: string;
[k: string]: unknown;
};
notices_present?: boolean;
[k: string]: unknown;
};
precert?: boolean;
ct?: {
certificatetransparency_cn_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_argon_2017?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
sheca_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_nessie_2019?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_nessie_2018?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_pilot?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_xenon_2019?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
comodo_mammoth?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
akamai_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
behind_the_sofa?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_argon_2018?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_argon_2019?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
wosign_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_xenon_2021?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_faux?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
comodo_dodo?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
venafi_api_ctlog?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
wosign_ctlog2?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
izenpe_eus_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
wotrus_ctlog?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
gdca_log2?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
wosign_ctlog3?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_oak_2021?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_golem?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_skydiver?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_oak_2022?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_aviator?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
gdca_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_rocketeer?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
izenpe_com_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
cloudflare_nimbus_2021?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
cloudflare_nimbus_2020?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
symantec_ws_deneb?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_daedalus?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_xenon_2018?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
izenpe_com_pilot?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_yeti_2022?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_xenon_2022?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_yeti_2020?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_yeti_2021?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
symantec_ws_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_argon_2020?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_nessie_2020?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_nessie_2021?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_nessie_2022?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_oak?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_xenon_2020?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
comodo_sabre?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_argon_2021?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
gdca_ctlog?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
nordu_ct_flimsy?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_testtube?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_yeti_2019?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_yeti_2018?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
nordu_ct_plausible?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
startssl_ct?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
symantec_ws_vega?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
wotrus_ctlog3?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
ctlogs_alpha?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
wosign_ctlog?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
cloudflare_nimbus_2017?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
symantec_ws_sirius?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_icarus?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_ct1?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_oak_2020?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
gdca_log?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
digicert_ct2?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_oak_2019?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
cloudflare_nimbus_2018?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
cloudflare_nimbus_2019?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
cnnic_ctserver?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
certly_log?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
sheca_ctlog?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_clicky?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
google_submariner?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
venafi_api_ctlog_gen2?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
letsencrypt_ct_birch?: {
index?: string;
censys_to_ct_at?: string;
ct_to_censys_at?: string;
added_to_ct_at?: string;
sct?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
/**
* The certificate's public key. Only one of the *_public_key fields will be set.
*/
subject_key_info?: {
/**
* The SHA2-256 digest calculated over the certificate's DER-encoded SubjectPublicKeyInfo field.
*/
fingerprint_sha256?: string;
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_public_key?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
/**
* Identifies the type of key and any relevant parameters.
*/
key_algorithm?: {
/**
* OID of the public key on the certificate. This is helpful when an unknown type is present. This field is reserved and not currently populated.
*/
oid?: string;
/**
* Name of public key type, e.g., RSA or ECDSA. More information is available the named SubRecord (e.g., RSAPublicKey()).
*/
name?: string;
[k: string]: unknown;
};
/**
* The public portion of an ECDSA asymmetric key.
*/
ecdsa_public_key?: {
b?: string;
curve?: string;
gy?: string;
n?: string;
p?: string;
length?: string;
pub?: string;
y?: string;
x?: string;
gx?: string;
[k: string]: unknown;
};
/**
* The public portion of a DSA asymmetric key.
*/
dsa_public_key?: {
q?: string;
p?: string;
y?: string;
g?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The x.509 certificate version number.
*/
version?: string;
/**
* A canonical string representation of the subject name.
*/
subject_dn?: string;
/**
* List of raw extensions that were not recognized by the application.
*/
unknown_extensions?: {
/**
* Certificates should be rejected if they have critical extensions the validator does not recognize.
*/
critical?: boolean;
/**
* The OBJECT IDENTIFIER identifying the extension.
*/
id?: string;
/**
* The raw value of the extnValue OCTET STREAM.
*/
value?: string;
[k: string]: unknown;
};
/**
* Identifies the algorithm used by the CA to sign the certificate.
*/
signature_algorithm?: {
/**
* The OBJECT IDENTIFIER of the signature algorithm, in dotted-decimal notation.
*/
oid?: string;
/**
* Name of signature algorithm, e.g., SHA1-RSA or ECDSA-SHA512. Unknown algorithms get an integer id.
*/
name?: string;
[k: string]: unknown;
};
/**
* This is set if any of the certificate's names contain redacted fields.
*/
redacted?: boolean;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct_fingerprint?: string;
/**
* A canonical string representation of the issuer name.
*/
issuer_dn?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs_fingerprint?: string;
extensions?: {
/**
* The parsed id-ce-nameConstraints extension (2.5.29.30). Specifies a name space within which all child certificates' subject names MUST be located.
*/
name_constraints?: {
/**
* Permitted names of type directoryName.
*/
permitted_directory_names?: {
/**
* jurisdictionCountry elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.3)
*/
jurisdiction_country?: string;
/**
* stateOrProviceName (ST) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.8)
*/
province?: string;
/**
* surname (SN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.4)
*/
surname?: string;
/**
* localityName (L) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.7)
*/
locality?: string;
/**
* domainComponent (DC) elements of the distinguished name (OBJECT IDENTIFIER 0.9.2342.19200300.100.1.25)
*/
domain_component?: string;
/**
* countryName (C) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.6)
*/
country?: string;
/**
* jurisdictionStateOrProvice elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.2)
*/
jurisdiction_province?: string;
/**
* jurisdictionLocality elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.1)
*/
jurisdiction_locality?: string;
/**
* postalCode elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.17)
*/
postal_code?: string;
/**
* organizationId elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.97)
*/
organization_id?: string;
/**
* organizationalUnit (OU) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.11)
*/
organizational_unit?: string;
/**
* givenName (G) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.42)
*/
given_name?: string;
/**
* serialNumber elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.5)
*/
serial_number?: string;
/**
* commonName (CN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.3)
*/
common_name?: string;
/**
* organizationName (O) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.10)
*/
organization?: string;
/**
* emailAddress (E) elements of the distinguished name (OBJECT IDENTIFIER 1.2.840.113549.1.9.1)
*/
email_address?: string;
/**
* streetAddress (STREET) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.9)
*/
street_address?: string;
[k: string]: unknown;
};
/**
* Permitted names of type rfc822Name.
*/
permitted_email_addresses?: string;
/**
* Excluded names of type ediPartyName.
*/
excluded_edi_party_names?: {
/**
* The partyName (a DirectoryString)
*/
party_name?: string;
/**
* The nameAssigner (a DirectoryString)
*/
name_assigner?: string;
[k: string]: unknown;
};
/**
* Permitted names of type registeredID.
*/
permitted_registered_ids?: string;
/**
* Excluded names of type rfc822Name.
*/
excluded_email_addresses?: string;
/**
* Excluded names of type registeredID.
*/
excluded_registered_ids?: string;
/**
* Excluded names of type dNSName.
*/
excluded_names?: string;
/**
* If set, clients unable to understand this extension must reject this certificate.
*/
critical?: boolean;
/**
* Permitted names of type ediPartyName
*/
permitted_edi_party_names?: {
/**
* The partyName (a DirectoryString)
*/
party_name?: string;
/**
* The nameAssigner (a DirectoryString)
*/
name_assigner?: string;
[k: string]: unknown;
};
/**
* Excluded names of type directoryName.
*/
excluded_directory_names?: {
/**
* jurisdictionCountry elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.3)
*/
jurisdiction_country?: string;
/**
* stateOrProviceName (ST) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.8)
*/
province?: string;
/**
* surname (SN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.4)
*/
surname?: string;
/**
* localityName (L) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.7)
*/
locality?: string;
/**
* domainComponent (DC) elements of the distinguished name (OBJECT IDENTIFIER 0.9.2342.19200300.100.1.25)
*/
domain_component?: string;
/**
* countryName (C) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.6)
*/
country?: string;
/**
* jurisdictionStateOrProvice elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.2)
*/
jurisdiction_province?: string;
/**
* jurisdictionLocality elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.1)
*/
jurisdiction_locality?: string;
/**
* postalCode elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.17)
*/
postal_code?: string;
/**
* organizationId elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.97)
*/
organization_id?: string;
/**
* organizationalUnit (OU) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.11)
*/
organizational_unit?: string;
/**
* givenName (G) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.42)
*/
given_name?: string;
/**
* serialNumber elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.5)
*/
serial_number?: string;
/**
* commonName (CN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.3)
*/
common_name?: string;
/**
* organizationName (O) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.10)
*/
organization?: string;
/**
* emailAddress (E) elements of the distinguished name (OBJECT IDENTIFIER 1.2.840.113549.1.9.1)
*/
email_address?: string;
/**
* streetAddress (STREET) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.9)
*/
street_address?: string;
[k: string]: unknown;
};
/**
* Permitted names of type dNSName.
*/
permitted_names?: string;
[k: string]: unknown;
};
/**
* A key identifier, usually a digest of the DER encoding of a SubjectPublicKeyInfo. This is the hex encoding of the OCTET STRING value.
*/
authority_key_id?: string;
/**
* The CA/BF organization ID extensions (2.23.140.3.1)
*/
cabf_organization_id?: {
country?: string;
state?: string;
scheme?: string;
reference?: string;
[k: string]: unknown;
};
/**
* The parsed Subject Alternative Name extension (id-ce-subjectAltName, 2.5.29.17).
*/
subject_alt_name?: {
/**
* uniformResourceIdentifier entries in the GeneralName (CHOICE tag 6).
*/
uniform_resource_identifiers?: string;
/**
* Parsed directoryName entries in the GeneralName (CHOICE tag 4).
*/
directory_names?: {
/**
* jurisdictionCountry elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.3)
*/
jurisdiction_country?: string;
/**
* stateOrProviceName (ST) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.8)
*/
province?: string;
/**
* surname (SN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.4)
*/
surname?: string;
/**
* localityName (L) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.7)
*/
locality?: string;
/**
* domainComponent (DC) elements of the distinguished name (OBJECT IDENTIFIER 0.9.2342.19200300.100.1.25)
*/
domain_component?: string;
/**
* countryName (C) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.6)
*/
country?: string;
/**
* jurisdictionStateOrProvice elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.2)
*/
jurisdiction_province?: string;
/**
* jurisdictionLocality elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.1)
*/
jurisdiction_locality?: string;
/**
* postalCode elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.17)
*/
postal_code?: string;
/**
* organizationId elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.97)
*/
organization_id?: string;
/**
* organizationalUnit (OU) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.11)
*/
organizational_unit?: string;
/**
* givenName (G) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.42)
*/
given_name?: string;
/**
* serialNumber elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.5)
*/
serial_number?: string;
/**
* commonName (CN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.3)
*/
common_name?: string;
/**
* organizationName (O) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.10)
*/
organization?: string;
/**
* emailAddress (E) elements of the distinguished name (OBJECT IDENTIFIER 1.2.840.113549.1.9.1)
*/
email_address?: string;
/**
* streetAddress (STREET) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.9)
*/
street_address?: string;
[k: string]: unknown;
};
/**
* iPAddress entries in the GeneralName (CHOICE tag 7).
*/
ip_addresses?: string;
/**
* otherName entries in the GeneralName (CHOICE tag 0). An arbitrary binary value identified by an OBJECT IDENTIFIER.
*/
other_names?: {
/**
* The OBJECT IDENTIFIER identifying the syntax of the otherName value.
*/
id?: string;
/**
* The raw otherName value.
*/
value?: string;
[k: string]: unknown;
};
/**
* registeredID entries in the GeneralName (OBJECT IDENTIFIER, CHOICE tag 8). Stored in dotted-decimal format.
*/
registered_ids?: string;
/**
* Parsed eDIPartyName entries in the GeneralName (CHOICE tag 5)
*/
edi_party_names?: {
/**
* The partyName (a DirectoryString)
*/
party_name?: string;
/**
* The nameAssigner (a DirectoryString)
*/
name_assigner?: string;
[k: string]: unknown;
};
/**
* dNSName entries in the GeneralName (IA5String, CHOICE tag 2).
*/
dns_names?: string;
/**
* rfc822Name entries in the GeneralName (IA5String, CHOICE tag 1).
*/
email_addresses?: string;
[k: string]: unknown;
};
/**
* The parsed id-pe-authorityInfoAccess extension (1.3.6.1.5.7.1.1). Only id-ad-caIssuers and id-ad-ocsp accessMethods are supported; others are omitted.
*/
authority_info_access?: {
/**
* URLs of accessLocations with accessMethod of id-ad-ocsp, pointing to OCSP servers that can be used to check this certificate's revocation status. Only uniformResourceIdentifier accessLocations are supported; others are omitted.
*/
ocsp_urls?: string;
/**
* URLs of accessLocations with accessMethod of id-ad-caIssuers, pointing to locations where this certificate's issuers can be downloaded. Only uniformResourceIdentifier accessLocations are supported; others are omitted.
*/
issuer_urls?: string;
[k: string]: unknown;
};
/**
* The parsed id-ce-basicConstraints extension (2.5.29.19); see RFC 5280.
*/
basic_constraints?: {
/**
* When present, gives the maximum number of non-self-issued intermediate certificates that may follow this certificate in a valid certification path.
*/
max_path_len?: string;
/**
* Indicates that the certificate is permitted to sign other certificates.
*/
is_ca?: boolean;
[k: string]: unknown;
};
/**
* IDs and parsed statements for qualified certificates (1.3.6.1.5.5.7.1.3)
*/
qc_statements?: {
/**
* All included statement OIDs
*/
ids?: string;
/**
* Contains known QCStatements. Each field is repeated to handle the case where a single statement appears more than once.
*/
parsed?: {
/**
* Statement ID 0.4.0.1862.1.7
*/
legislation?: {
/**
* Country codes for the set of countries where this certificate issued as a qualified certificate
*/
country_codes?: string;
[k: string]: unknown;
};
/**
* Statement ID 0.4.0.1862.1.3
*/
retention_period?: string;
/**
* Statement ID 0.4.0.1862.1.5
*/
pds_locations?: {
/**
* Included PDS locations
*/
locations?: {
/**
* Location of the PDS
*/
url?: string;
/**
* Locale code
*/
language?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Statement ID 0.4.0.1862.1.2
*/
limit?: {
/**
* Currency, if provided as an integer
*/
currency_number?: string;
/**
* Currency, if provided as a string
*/
currency?: string;
/**
* Value in currency
*/
amount?: string;
/**
* Total is amount times 10 raised to the exponent
*/
exponent?: string;
[k: string]: unknown;
};
/**
* True if present (Statement ID 0.4.0.1862.1.4
*/
sscd?: boolean;
/**
* True if present (Statement ID 0.4.0.1862.1.1)
*/
etsi_compliance?: boolean;
/**
* Statement ID 0.4.0.1862.1.6
*/
types?: {
/**
* Included QC type OIDs
*/
ids?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The parsed id-ce-certificatePolicies extension (2.5.29.32).
*/
certificate_policies?: {
/**
* List of URIs to the policies
*/
cps?: string;
/**
* The OBJECT IDENTIFIER identifying the policy.
*/
id?: string;
/**
* List of textual notices to display relying parties.
*/
user_notice?: {
/**
* Names an organization and identifies, by number, a particular textual statement prepared by that organization.
*/
notice_reference?: {
/**
* The numeric identifier(s) of the notice.
*/
notice_numbers?: string;
/**
* The organization that prepared the notice.
*/
organization?: string;
[k: string]: unknown;
};
/**
* Textual statement with a maximum size of 200 characters. Should be a UTF8String or IA5String.
*/
explicit_text?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The parsed id-ce-cRLDistributionPoints extension (2.5.29.31). Contents are a list of distributionPoint URLs (other distributionPoint types are omitted).
*/
crl_distribution_points?: string;
/**
* The parsed id-ce-keyUsage extension (2.5.29.15); see RFC 5280.
*/
key_usage?: {
/**
* Indicates if the keyEncipherment bit(2) is set.
*/
key_encipherment?: boolean;
/**
* Indicates if the digitalSignature bit(0) is set.
*/
digital_signature?: boolean;
/**
* Indicates if the encipherOnly bit(7) is set.
*/
decipher_only?: boolean;
/**
* Indicates if the keyAgreement bit(4) is set.
*/
key_agreement?: boolean;
/**
* Indicates if the dataEncipherment bit(3) is set.
*/
data_encipherment?: boolean;
/**
* Integer value of the bitmask in the extension
*/
value?: string;
/**
* Indicates if the decipherOnly bit(8) is set.
*/
encipher_only?: boolean;
/**
* Indicates if the keyCertSign bit(5) is set.
*/
certificate_sign?: boolean;
/**
* Indicates if the contentCommitment bit(1) (formerly called nonRepudiation) is set.
*/
content_commitment?: boolean;
/**
* Indicates if the cRLSign bit(6) is set.
*/
crl_sign?: boolean;
[k: string]: unknown;
};
/**
* The parsed Certificate Transparency SignedCertificateTimestampsList extension (1.3.6.1.4.1.11129.2.4.2); see RFC 6962.
*/
signed_certificate_timestamps?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
/**
* This is true if the certificate possesses the Certificate Transparency Precertificate Poison extension (1.3.6.1.4.1.11129.2.4.3).
*/
ct_poison?: boolean;
/**
* A key identifier, usually a digest of the DER encoding of a SubjectPublicKeyInfo. This is the hex encoding of the OCTET STRING value.
*/
subject_key_id?: string;
/**
* The parsed Issuer Alternative Name extension (id-ce-issuerAltName, 2.5.29.18).
*/
issuer_alt_name?: {
/**
* uniformResourceIdentifier entries in the GeneralName (CHOICE tag 6).
*/
uniform_resource_identifiers?: string;
/**
* Parsed directoryName entries in the GeneralName (CHOICE tag 4).
*/
directory_names?: {
/**
* jurisdictionCountry elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.3)
*/
jurisdiction_country?: string;
/**
* stateOrProviceName (ST) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.8)
*/
province?: string;
/**
* surname (SN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.4)
*/
surname?: string;
/**
* localityName (L) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.7)
*/
locality?: string;
/**
* domainComponent (DC) elements of the distinguished name (OBJECT IDENTIFIER 0.9.2342.19200300.100.1.25)
*/
domain_component?: string;
/**
* countryName (C) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.6)
*/
country?: string;
/**
* jurisdictionStateOrProvice elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.2)
*/
jurisdiction_province?: string;
/**
* jurisdictionLocality elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.1)
*/
jurisdiction_locality?: string;
/**
* postalCode elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.17)
*/
postal_code?: string;
/**
* organizationId elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.97)
*/
organization_id?: string;
/**
* organizationalUnit (OU) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.11)
*/
organizational_unit?: string;
/**
* givenName (G) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.42)
*/
given_name?: string;
/**
* serialNumber elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.5)
*/
serial_number?: string;
/**
* commonName (CN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.3)
*/
common_name?: string;
/**
* organizationName (O) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.10)
*/
organization?: string;
/**
* emailAddress (E) elements of the distinguished name (OBJECT IDENTIFIER 1.2.840.113549.1.9.1)
*/
email_address?: string;
/**
* streetAddress (STREET) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.9)
*/
street_address?: string;
[k: string]: unknown;
};
/**
* iPAddress entries in the GeneralName (CHOICE tag 7).
*/
ip_addresses?: string;
/**
* otherName entries in the GeneralName (CHOICE tag 0). An arbitrary binary value identified by an OBJECT IDENTIFIER.
*/
other_names?: {
/**
* The OBJECT IDENTIFIER identifying the syntax of the otherName value.
*/
id?: string;
/**
* The raw otherName value.
*/
value?: string;
[k: string]: unknown;
};
/**
* registeredID entries in the GeneralName (OBJECT IDENTIFIER, CHOICE tag 8). Stored in dotted-decimal format.
*/
registered_ids?: string;
/**
* Parsed eDIPartyName entries in the GeneralName (CHOICE tag 5)
*/
edi_party_names?: {
/**
* The partyName (a DirectoryString)
*/
party_name?: string;
/**
* The nameAssigner (a DirectoryString)
*/
name_assigner?: string;
[k: string]: unknown;
};
/**
* dNSName entries in the GeneralName (IA5String, CHOICE tag 2).
*/
dns_names?: string;
/**
* rfc822Name entries in the GeneralName (IA5String, CHOICE tag 1).
*/
email_addresses?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* A list of subject names in the certificate, including the Subject CommonName and SubjectAltName DNSNames, IPAddresses and URIs.
*/
names?: string;
signature?: {
/**
* Indicates whether the subject key was also used to sign the certificate.
*/
self_signed?: boolean;
valid?: boolean;
/**
* Contents of the signature BIT STRING.
*/
value?: string;
signature_algorithm?: {
/**
* The OBJECT IDENTIFIER of the signature algorithm, in dotted-decimal notation.
*/
oid?: string;
/**
* Name of signature algorithm, e.g., SHA1-RSA or ECDSA-SHA512. Unknown algorithms get an integer id.
*/
name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* How the certificate is validated -- Domain validated (DV), Organization Validated (OV), Extended Validation (EV), or unknown.
*/
validation_level?: string;
/**
* Serial number as an signed decimal integer. Stored as string to support >uint lengths. Negative values are allowed.
*/
serial_number?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_md5?: string;
/**
* The parsed subject name.
*/
subject?: {
/**
* jurisdictionCountry elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.3)
*/
jurisdiction_country?: string;
/**
* stateOrProviceName (ST) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.8)
*/
province?: string;
/**
* surname (SN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.4)
*/
surname?: string;
/**
* localityName (L) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.7)
*/
locality?: string;
/**
* domainComponent (DC) elements of the distinguished name (OBJECT IDENTIFIER 0.9.2342.19200300.100.1.25)
*/
domain_component?: string;
/**
* countryName (C) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.6)
*/
country?: string;
/**
* jurisdictionStateOrProvice elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.2)
*/
jurisdiction_province?: string;
/**
* jurisdictionLocality elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.1)
*/
jurisdiction_locality?: string;
/**
* postalCode elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.17)
*/
postal_code?: string;
/**
* organizationId elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.97)
*/
organization_id?: string;
/**
* organizationalUnit (OU) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.11)
*/
organizational_unit?: string;
/**
* givenName (G) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.42)
*/
given_name?: string;
/**
* serialNumber elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.5)
*/
serial_number?: string;
/**
* commonName (CN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.3)
*/
common_name?: string;
/**
* organizationName (O) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.10)
*/
organization?: string;
/**
* emailAddress (E) elements of the distinguished name (OBJECT IDENTIFIER 1.2.840.113549.1.9.1)
*/
email_address?: string;
/**
* streetAddress (STREET) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.9)
*/
street_address?: string;
[k: string]: unknown;
};
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject_fingerprint?: string;
validity?: {
/**
* Timestamp of when certificate is first valid. Timezone is UTC.
*/
start?: string;
/**
* The length of time, in seconds, that the certificate is valid.
*/
length?: string;
/**
* Timestamp of when certificate expires. Timezone is UTC.
*/
end?: string;
[k: string]: unknown;
};
/**
* The parsed issuer name.
*/
issuer?: {
/**
* jurisdictionCountry elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.3)
*/
jurisdiction_country?: string;
/**
* stateOrProviceName (ST) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.8)
*/
province?: string;
/**
* surname (SN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.4)
*/
surname?: string;
/**
* localityName (L) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.7)
*/
locality?: string;
/**
* domainComponent (DC) elements of the distinguished name (OBJECT IDENTIFIER 0.9.2342.19200300.100.1.25)
*/
domain_component?: string;
/**
* countryName (C) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.6)
*/
country?: string;
/**
* jurisdictionStateOrProvice elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.2)
*/
jurisdiction_province?: string;
/**
* jurisdictionLocality elements of the distinguished name (OBJECT IDENTIFIER 1.3.6.1.4.1.311.60.2.1.1)
*/
jurisdiction_locality?: string;
/**
* postalCode elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.17)
*/
postal_code?: string;
/**
* organizationId elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.97)
*/
organization_id?: string;
/**
* organizationalUnit (OU) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.11)
*/
organizational_unit?: string;
/**
* givenName (G) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.42)
*/
given_name?: string;
/**
* serialNumber elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.5)
*/
serial_number?: string;
/**
* commonName (CN) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.3)
*/
common_name?: string;
/**
* organizationName (O) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.10)
*/
organization?: string;
/**
* emailAddress (E) elements of the distinguished name (OBJECT IDENTIFIER 1.2.840.113549.1.9.1)
*/
email_address?: string;
/**
* streetAddress (STREET) elements of the distinguished name (OBJECT IDENTIFIER 2.5.4.9)
*/
street_address?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
metadata?: {
post_processed_at?: string;
post_processed?: boolean;
parse_status?: string;
seen_in_scan?: boolean;
updated_at?: string;
added_at?: string;
source?: string;
parse_version?: string;
parse_error?: string;
[k: string]: unknown;
};
[k: string]: unknown;
} | the_stack |
import { Decoration } from './decoration'
import {
LUA_MULTRET,
LuaEventMasks,
LuaResumeResult,
LuaReturn,
LuaState,
LuaThreadRunOptions,
LuaTimeoutError,
LuaType,
PointerSize,
} from './types'
import { Pointer } from './pointer'
import LuaTypeExtension from './type-extension'
import MultiReturn from './multireturn'
import type LuaWasm from './luawasm'
export interface OrderedExtension {
// Bigger is more important
priority: number
extension: LuaTypeExtension<unknown>
}
// When the debug count hook is set, call it every X instructions.
const INSTRUCTION_HOOK_COUNT = 1000
export default class Thread {
public readonly address: LuaState = 0
public readonly lua: LuaWasm
protected readonly typeExtensions: OrderedExtension[]
private closed = false
private hookFunctionPointer: number | undefined
private timeout?: number
private readonly parent?: Thread
public constructor(lua: LuaWasm, typeExtensions: OrderedExtension[], address: number, parent?: Thread) {
this.lua = lua
this.typeExtensions = typeExtensions
this.address = address
this.parent = parent
}
public newThread(): Thread {
const address = this.lua.lua_newthread(this.address)
if (!address) {
throw new Error('lua_newthread returned a null pointer')
}
return new Thread(this.lua, this.typeExtensions, address)
}
public resetThread(): void {
this.assertOk(this.lua.lua_resetthread(this.address))
}
public loadString(luaCode: string): void {
this.assertOk(this.lua.luaL_loadstring(this.address, luaCode))
}
public loadFile(filename: string): void {
this.assertOk(this.lua.luaL_loadfilex(this.address, filename, null))
}
public resume(argCount = 0): LuaResumeResult {
const dataPointer = this.lua.module._malloc(PointerSize)
try {
this.lua.module.setValue(dataPointer, 0, 'i32')
const luaResult = this.lua.lua_resume(this.address, null, argCount, dataPointer)
return {
result: luaResult,
resultCount: this.lua.module.getValue(dataPointer, 'i32'),
}
} finally {
this.lua.module._free(dataPointer)
}
}
public getTop(): number {
return this.lua.lua_gettop(this.address)
}
public setTop(index: number): void {
this.lua.lua_settop(this.address, index)
}
public remove(index: number): void {
return this.lua.lua_remove(this.address, index)
}
public setField(index: number, name: string, value: unknown): void {
index = this.lua.lua_absindex(this.address, index)
this.pushValue(value)
this.lua.lua_setfield(this.address, index, name)
}
public async run(argCount = 0, options?: Partial<LuaThreadRunOptions>): Promise<MultiReturn> {
const originalTimeout = this.timeout
try {
if (options?.timeout !== undefined) {
this.setTimeout(Date.now() + options.timeout)
}
let resumeResult: LuaResumeResult = this.resume(argCount)
while (resumeResult.result === LuaReturn.Yield) {
// If it's yielded check the timeout. If it's completed no need to
// needlessly discard the output.
if (this.timeout && Date.now() > this.timeout) {
if (resumeResult.resultCount > 0) {
this.pop(resumeResult.resultCount)
}
throw new LuaTimeoutError(`thread timeout exceeded`)
}
if (resumeResult.resultCount > 0) {
const lastValue = this.getValue(-1)
this.pop(resumeResult.resultCount)
// If there's a result and it's a promise, then wait for it.
if (lastValue === Promise.resolve(lastValue)) {
await lastValue
} else {
// If it's a non-promise, then skip a tick to yield for promises, timers, etc.
await new Promise((resolve) => setImmediate(resolve))
}
} else {
// If there's nothing to yield, then skip a tick to yield for promises, timers, etc.
await new Promise((resolve) => setImmediate(resolve))
}
resumeResult = this.resume(0)
}
this.assertOk(resumeResult.result)
return this.getStackValues()
} finally {
if (options?.timeout !== undefined) {
this.setTimeout(originalTimeout)
}
}
}
public runSync(argCount = 0): MultiReturn {
this.assertOk(this.lua.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null) as LuaReturn)
return this.getStackValues()
}
public pop(count = 1): void {
this.lua.lua_pop(this.address, count)
}
public call(name: string, ...args: any[]): MultiReturn {
const type = this.lua.lua_getglobal(this.address, name)
if (type !== LuaType.Function) {
throw new Error(`A function of type '${type}' was pushed, expected is ${LuaType.Function}`)
}
for (const arg of args) {
this.pushValue(arg)
}
this.lua.lua_callk(this.address, args.length, LUA_MULTRET, 0, null)
return this.getStackValues()
}
public getStackValues(): MultiReturn {
const returns = this.getTop()
const returnValues = new MultiReturn(returns)
for (let i = 0; i < returns; i++) {
returnValues[i] = this.getValue(i + 1)
}
return returnValues
}
public stateToThread(L: LuaState): Thread {
return L === this.parent?.address ? this.parent : new Thread(this.lua, this.typeExtensions, L, this.parent || this)
}
public pushValue(rawValue: unknown, userdata?: unknown): void {
const decoratedValue = this.getValueDecorations(rawValue)
let target = decoratedValue.target
if (target instanceof Thread) {
const isMain = this.lua.lua_pushthread(target.address) === 1
if (!isMain) {
this.lua.lua_xmove(target.address, this.address, 1)
}
return
}
const startTop = this.getTop()
// First to allow overriding default behaviour, except for threads
if (!this.typeExtensions.find((wrapper) => wrapper.extension.pushValue(this, decoratedValue, userdata))) {
if (target === null) {
target = undefined
}
// Handle primitive types
switch (typeof target) {
case 'undefined':
this.lua.lua_pushnil(this.address)
break
case 'number':
if (Number.isInteger(target)) {
this.lua.lua_pushinteger(this.address, target)
} else {
this.lua.lua_pushnumber(this.address, target)
}
break
case 'string':
this.lua.lua_pushstring(this.address, target)
break
case 'boolean':
this.lua.lua_pushboolean(this.address, target ? 1 : 0)
break
default:
throw new Error(`The type '${typeof target}' is not supported by Lua`)
}
}
if (decoratedValue.options.metatable) {
this.setMetatable(decoratedValue.options.metatable, -1)
}
if (this.getTop() !== startTop + 1) {
throw new Error(`pushValue expected stack size ${startTop + 1}, got ${this.getTop()}`)
}
}
public setMetatable(metatable: Record<any, any>, index: number): void {
index = this.lua.lua_absindex(this.address, index)
if (this.lua.lua_getmetatable(this.address, index)) {
this.pop(1)
const name = this.getMetatableName(index)
throw new Error(`data already has associated metatable: ${name || 'unknown name'}`)
}
this.pushValue(metatable)
this.lua.lua_setmetatable(this.address, index)
}
public getMetatableName(index: number): string | undefined {
const metatableNameType = this.lua.luaL_getmetafield(this.address, index, '__name')
if (metatableNameType === LuaType.Nil) {
return undefined
}
if (metatableNameType !== LuaType.String) {
// Pop the metafield if it's not a string
this.pop(1)
return undefined
}
const name = this.lua.lua_tolstring(this.address, -1, null)
// This is popping the luaL_getmetafield result which only pushes with type is not nil.
this.pop(1)
return name
}
public getValue(idx: number, inputType: LuaType | undefined = undefined, userdata?: unknown): any {
idx = this.lua.lua_absindex(this.address, idx)
// Before the below to allow overriding default behaviour.
const metatableName = this.getMetatableName(idx)
const type: LuaType = inputType || this.lua.lua_type(this.address, idx)
const typeExtensionWrapper = this.typeExtensions.find((wrapper) => wrapper.extension.isType(this, idx, type, metatableName))
if (typeExtensionWrapper) {
return typeExtensionWrapper.extension.getValue(this, idx, userdata)
}
switch (type) {
case LuaType.None:
return undefined
case LuaType.Nil:
return null
case LuaType.Number:
return this.lua.lua_tonumberx(this.address, idx, null)
case LuaType.String:
return this.lua.lua_tolstring(this.address, idx, null)
case LuaType.Boolean:
return Boolean(this.lua.lua_toboolean(this.address, idx))
case LuaType.Thread: {
return this.stateToThread(this.lua.lua_tothread(this.address, idx))
}
// Fallthrough if unrecognised user data
default:
console.warn(`The type '${this.lua.lua_typename(this.address, type)}' returned is not supported on JS`)
return new Pointer(this.lua.lua_topointer(this.address, idx))
}
}
public close(): void {
if (this.isClosed()) {
return
}
if (this.hookFunctionPointer) {
this.lua.module.removeFunction(this.hookFunctionPointer)
}
this.closed = true
}
// Set to > 0 to enable, otherwise disable.
public setTimeout(timeout: number | undefined): void {
if (timeout && timeout > 0) {
if (!this.hookFunctionPointer) {
this.hookFunctionPointer = this.lua.module.addFunction((): void => {
if (Date.now() > timeout) {
this.pushValue(new LuaTimeoutError(`thread timeout exceeded`))
this.lua.lua_error(this.address)
}
}, 'vii')
}
this.lua.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, INSTRUCTION_HOOK_COUNT)
this.timeout = timeout
} else {
this.timeout = undefined
this.lua.lua_sethook(this.address, null, 0, 0)
}
}
public getTimeout(): number | undefined {
return this.timeout
}
public getPointer(index: number): Pointer {
return new Pointer(this.lua.lua_topointer(this.address, index))
}
public isClosed(): boolean {
return !this.address || this.closed || Boolean(this.parent?.isClosed())
}
public indexToString(index: number): string {
const str = this.lua.luaL_tolstring(this.address, index, null)
// Pops the string pushed by luaL_tolstring
this.pop()
return str
}
public dumpStack(log = console.log): void {
const top = this.getTop()
for (let i = 1; i <= top; i++) {
const type = this.lua.lua_type(this.address, i)
const typename = this.lua.lua_typename(this.address, type)
const pointer = this.getPointer(i)
const name = this.indexToString(i)
const value = this.getValue(i, type)
log(i, typename, pointer, name, value)
}
}
public assertOk(result: LuaReturn): void {
if (result !== LuaReturn.Ok && result !== LuaReturn.Yield) {
const resultString = LuaReturn[result]
// This is the default message if there's nothing on the stack.
const error = new Error(`Lua Error(${resultString}/${result})`)
if (this.getTop() > 0) {
if (result === LuaReturn.ErrorMem) {
// If there's no memory just do a normal to string.
error.message = this.lua.lua_tolstring(this.address, -1, null)
} else {
const luaError = this.getValue(-1)
if (luaError instanceof Error) {
error.stack = luaError.stack
}
// Calls __tostring if it exists and pushes onto the stack.
error.message = this.indexToString(-1)
}
}
throw error
}
}
private getValueDecorations(value: any): Decoration {
return value instanceof Decoration ? value : new Decoration(value, {})
}
} | the_stack |
import { DataObject } from "@fluidframework/aqueduct";
import {
IFluidObject,
IFluidHandle,
} from "@fluidframework/core-interfaces";
import { IEvent } from "@fluidframework/common-definitions";
import { SharedMap, ISharedMap } from "@fluidframework/map";
import type { IFluidDataStoreRuntime } from "@fluidframework/datastore-definitions";
import {
FluidObjectMap,
SyncedStateConfig,
ISyncedStateConfig,
IViewState,
IFluidState,
ISyncedState,
} from "./interface";
import {
generateFluidObjectSchema,
setSchema,
getSchema,
} from "./helpers";
/**
* SyncedDataObject is a base class for Fluid data objects with views. It extends DataObject.
* In addition to the root and task manager, the SyncedDataObject also provides a syncedStateConfig
* and assures that the syncedState will be initialized according the config by the time the view
* is rendered.
*/
export abstract class SyncedDataObject<
// eslint-disable-next-line @typescript-eslint/ban-types
P extends IFluidObject = object,
S = undefined,
E extends IEvent = IEvent
> extends DataObject<P, S, E> {
private readonly syncedStateConfig: SyncedStateConfig = new Map();
private readonly fluidObjectMap: FluidObjectMap = new Map();
private readonly syncedStateDirectoryId = "syncedState";
private internalSyncedState: ISharedMap | undefined;
/**
* Runs the first time the SyncedDataObject is generated and sets up all necessary data structures for the view
* To extend this function, please call super() prior to adding to functionality to ensure correct initializing
*/
protected async initializingFirstTime(): Promise<void> {
// Initialize our synced state map for the first time using our
// syncedStateConfig values
await this.initializeStateFirstTime();
}
/**
* Runs any time the SyncedDataObject is rendered again. It sets up all necessary data structures for the view,
* along with any additional ones that may have been added due to user behavior
* To extend this function, please call super() prior to adding to functionality to ensure correct initializing
*/
protected async initializingFromExisting(): Promise<void> {
// Load our existing state values to be ready for the render lifecycle
await this.initializeStateFromExisting();
}
/**
* Returns an interface to interact with the stored synced state for the SyncedDataObject.
* Views can get and fetch values from it based on their syncedStateId to retrieve their view-specific information.
* They can also attach listeners using the addValueChangedListener
*/
public get syncedState(): ISyncedState {
if (this.internalSyncedState === undefined) {
throw new Error(this.getUninitializedErrorString(`syncedState`));
}
return {
set: this.internalSyncedState.set.bind(this.internalSyncedState),
get: this.internalSyncedState.get.bind(this.internalSyncedState),
addValueChangedListener: (callback) => {
if (this.internalSyncedState === undefined) {
throw new Error(
this.getUninitializedErrorString(`syncedState`),
);
}
this.internalSyncedState.on("valueChanged", callback);
},
};
}
/**
* Returns the data props used by the view to manage the different DDSes and add any new ones
*/
public get dataProps() {
return {
// The return type is defined explicitly here to prevent TypeScript from generating dynamic imports
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
runtime: this.runtime as IFluidDataStoreRuntime,
fluidObjectMap: this.fluidObjectMap,
};
}
/**
* Set values to the syncedStateConfig where the view and Fluid states have the same values defined by S.
* Each view with a unique syncedStateId needs its own value in the syncedStateConfig.
* @param key - The syncedStateId that maps to the view that will be using these definitions
* @param value - The config value containing the syncedStateId and the fluidToView and viewToFluid maps
*/
// eslint-disable-next-line @typescript-eslint/no-shadow
public setConfig<S>(key: string, value: ISyncedStateConfig<S, S>) {
this.syncedStateConfig.set(key, value);
}
/**
* Set values to the syncedStateConfig with different view and Fluid state definitions.
* Each view with a unique syncedStateId needs its own value in the syncedStateConfig,
* with SV being the view state definition and SF being the Fluid state definition.
* @param key - The syncedStateId that maps to the view that will be using these definitions
* @param value - The config value containing the syncedStateId and the fluidToView and viewToFluid maps
* that establish the relationship between SV and SF
*/
public setFluidConfig<
SV extends IViewState,
SF extends IFluidState
>(key: string, value: ISyncedStateConfig<SV, SF>) {
this.syncedStateConfig.set(key, value);
}
/**
* Get a config for a specific view with the key as its syncedStateId
* @param key - The syncedStateId to get the config for
*/
public getConfig(key: string) {
return this.syncedStateConfig.get(key);
}
private async initializeStateFirstTime() {
this.internalSyncedState = SharedMap.create(
this.runtime,
this.syncedStateDirectoryId,
);
this.internalSyncedState.bindToContext();
for (const stateConfig of this.syncedStateConfig.values()) {
const {
syncedStateId,
fluidToView,
viewToFluid,
defaultViewState,
} = stateConfig;
// Add the SharedMap to store the Fluid state
const storedFluidState = SharedMap.create(this.runtime);
// Add it to the Fluid object map so that it will have a listener added to it once
// we enter the render lifecycle
this.fluidObjectMap.set(storedFluidState.handle.absolutePath, {
fluidObject: storedFluidState,
isRuntimeMap: true,
});
// Add the state to our map of synced states so that we can load it later for persistence
this.syncedState.set(
`syncedState-${syncedStateId}`,
storedFluidState.handle,
);
// Initialize any DDSes needed for the state or fetch any values from the root if they are stored
// on the root under a different key
for (const [key, value] of fluidToView.entries()) {
const fluidKey = key as string;
const rootKey = value.rootKey;
const createCallback = value.sharedObjectCreate;
if (createCallback !== undefined) {
const sharedObject = createCallback(this.runtime);
this.fluidObjectMap.set(sharedObject.handle.absolutePath, {
fluidObject: sharedObject,
listenedEvents: value.listenedEvents ?? ["valueChanged"],
});
storedFluidState.set(fluidKey, sharedObject.handle);
if (rootKey !== undefined) {
this.root.set(rootKey, sharedObject.handle);
}
} else if (rootKey !== undefined) {
storedFluidState.set(fluidKey, this.root.get(rootKey));
}
}
// Generate our schema and store it, so that we don't need to parse our maps each time
const schema = generateFluidObjectSchema(
this.runtime,
defaultViewState,
fluidToView,
viewToFluid,
);
const schemaHandles = {
fluidMatchingMapHandle: schema.fluidMatchingMap
.handle as IFluidHandle<SharedMap>,
viewMatchingMapHandle: schema.viewMatchingMap
.handle as IFluidHandle<SharedMap>,
storedHandleMapHandle: schema.storedHandleMap
.handle as IFluidHandle<SharedMap>,
};
this.fluidObjectMap.set(
schema.fluidMatchingMap.handle.absolutePath,
{
fluidObject: schema.fluidMatchingMap,
isRuntimeMap: true,
},
);
this.fluidObjectMap.set(
schema.viewMatchingMap.handle.absolutePath,
{
fluidObject: schema.viewMatchingMap,
isRuntimeMap: true,
},
);
this.fluidObjectMap.set(
schema.storedHandleMap.handle.absolutePath,
{
fluidObject: schema.storedHandleMap,
isRuntimeMap: true,
},
);
setSchema(
syncedStateId,
this.syncedState,
schemaHandles,
);
}
}
private async initializeStateFromExisting() {
// Fetch our synced state that stores all of our information to re-initialize the view state
this.internalSyncedState = (await this.runtime.getChannel(
this.syncedStateDirectoryId,
)) as ISharedMap;
// Reload the stored state for each config provided
for (const stateConfig of this.syncedStateConfig.values()) {
const { syncedStateId, fluidToView } = stateConfig;
// Fetch this specific view's state using the syncedStateId
const storedFluidStateHandle = this.syncedState.get<
IFluidHandle<ISharedMap>
>(`syncedState-${syncedStateId}`);
if (storedFluidStateHandle === undefined) {
throw new Error(
this.getUninitializedErrorString(
`syncedState-${syncedStateId}`,
),
);
}
const storedFluidState = await storedFluidStateHandle.get();
// Add it to the Fluid object map so that it will have a listener added to it once
// we enter the render lifecycle
this.fluidObjectMap.set(storedFluidStateHandle.absolutePath, {
fluidObject: storedFluidState,
isRuntimeMap: true,
});
// If the view is using any Fluid data stores or SharedObjects, asynchronously fetch them
// from their stored handles
for (const [key, value] of fluidToView.entries()) {
const fluidKey = key as string;
const rootKey = value.rootKey;
const createCallback = value.sharedObjectCreate;
if (createCallback !== undefined) {
const handle = rootKey !== undefined
? this.root.get(rootKey)
: storedFluidState.get(fluidKey);
if (handle === undefined) {
throw new Error(
`Failed to find ${fluidKey} in synced state`,
);
}
this.fluidObjectMap.set(handle.absolutePath, {
fluidObject: await handle.get(),
listenedEvents: value.listenedEvents ?? ["valueChanged"],
});
} else {
const storedValue = rootKey !== undefined
? this.root.get(rootKey)
: storedFluidState.get(fluidKey);
const handle = storedValue?.IFluidHandle;
if (handle !== undefined) {
this.fluidObjectMap.set(handle.absolutePath, {
fluidObject: await handle.get(),
listenedEvents: value.listenedEvents ?? [
"valueChanged",
],
});
}
}
}
const schemaHandles = getSchema(
syncedStateId,
this.syncedState,
);
if (schemaHandles === undefined) {
throw new Error(
this.getUninitializedErrorString(
`schema-${syncedStateId}`,
),
);
}
this.fluidObjectMap.set(
schemaHandles.fluidMatchingMapHandle.absolutePath,
{
fluidObject: await schemaHandles.fluidMatchingMapHandle.get(),
isRuntimeMap: true,
},
);
this.fluidObjectMap.set(
schemaHandles.viewMatchingMapHandle.absolutePath,
{
fluidObject: await schemaHandles.viewMatchingMapHandle.get(),
isRuntimeMap: true,
},
);
this.fluidObjectMap.set(
schemaHandles.storedHandleMapHandle.absolutePath,
{
fluidObject: await schemaHandles.storedHandleMapHandle.get(),
isRuntimeMap: true,
},
);
}
}
} | the_stack |
"use strict";
import { Range } from "vscode-languageserver";
import { Logger } from "../logger";
import {
CSCodeError,
CSCodemark,
CSLocationArray,
CSMarker,
CSMarkerLocation,
CSMarkerLocations,
CSMe,
CSMSTeamsProviderInfo,
CSProviderInfos,
CSReview,
CSSlackProviderInfo,
CSTeam,
CSTeamProviderInfos
} from "../protocol/api.protocol";
export interface MarkerLocationArraysById {
[id: string]: CSLocationArray;
}
export interface MarkerLocationsById {
[id: string]: CSMarkerLocation;
}
export namespace MarkerLocation {
export function empty(): CSMarkerLocation {
return {
id: "$transientLocation",
lineStart: 1,
colStart: 1,
lineEnd: 1,
colEnd: 1,
meta: {
startWasDeleted: true,
endWasDeleted: true,
entirelyDeleted: true
}
};
}
export function fromArray(array: CSLocationArray, id: string): CSMarkerLocation {
return {
id,
lineStart: array[0],
colStart: array[1],
lineEnd: array[2],
colEnd: array[3],
meta: array[4]
};
}
export function fromRange(range: Range): CSMarkerLocation {
return {
id: "$transientLocation",
lineStart: range.start.line + 1,
colStart: range.start.character + 1,
lineEnd: range.end.line + 1,
colEnd: range.end.character + 1
};
}
export function toArray(location: CSMarkerLocation): CSLocationArray {
return [
location.lineStart,
location.colStart,
location.lineEnd,
location.colEnd,
location.meta
];
}
export function toArrayFromRange(range: Range): CSLocationArray {
return [
range.start.line + 1,
range.start.character + 1,
range.end.line + 1,
range.end.character + 1,
undefined
];
}
export function toArraysById(locations: MarkerLocationsById): MarkerLocationArraysById {
return Object.entries(locations).reduce((m, [id, location]) => {
m[id] = toArray(location);
return m;
}, Object.create(null));
}
export function toLocationById(location: CSMarkerLocation): MarkerLocationsById {
return { [location.id]: location };
}
export function toLocationsById(
markerLocations: CSMarkerLocations | undefined
): MarkerLocationsById {
if (markerLocations == null || markerLocations.locations == null) return {};
return Object.entries(markerLocations.locations).reduce((m, [id, array]) => {
m[id] = fromArray(array, id);
return m;
}, Object.create(null));
}
export function toRange(location: CSMarkerLocation): Range {
return Range.create(
Math.max(location.lineStart - 1, 0),
Math.max(location.colStart - 1, 0),
Math.max(location.lineEnd - 1, 0),
Math.max(location.colEnd - 1, 0)
);
}
export function toRangeFromArray(locationLike: CSLocationArray): Range {
return Range.create(
Math.max(locationLike[0] - 1, 0),
Math.max(locationLike[1] - 1, 0),
Math.max(locationLike[2] - 1, 0),
Math.max(locationLike[3] - 1, 0)
);
}
}
const remoteProviders: [
string,
string,
RegExp,
(remote: string, ref: string, file: string, start: number, end: number) => string
][] = [
[
"github",
"GitHub",
/(?:^|\.)github\.com/i,
(remote: string, ref: string, file: string, start: number, end: number) =>
`https://${remote}/blob/${ref}/${file}#L${start}${start !== end ? `-L${end}` : ""}`
],
[
"gitlab",
"GitLab",
/(?:^|\.)gitlab\.com/i,
(remote: string, ref: string, file: string, start: number, end: number) =>
`https://${remote}/blob/${ref}/${file}#L${start}${start !== end ? `-${end}` : ""}`
],
[
"bitBucket",
"Bitbucket",
/(?:^|\.)bitbucket\.org/i,
(remote: string, ref: string, file: string, start: number, end: number) =>
`https://${remote}/src/${ref}/${file}#${file}-${start}${start !== end ? `:${end}` : ""}`
],
[
"azure-devops",
"Azure DevOps",
/(?:^|\.)dev\.azure\.com/i,
(remote: string, ref: string, file: string, start: number, end: number) =>
`https://${remote}/commit/${ref}/?_a=contents&path=%2F${file}&line=${start}${
start !== end ? `&lineEnd=${end}` : ""
}`
],
[
"vsts",
"Azure DevOps",
/(?:^|\.)?visualstudio\.com$/i,
(remote: string, ref: string, file: string, start: number, end: number) =>
`https://${remote}/commit/${ref}/?_a=contents&path=%2F${file}&line=${start}${
start !== end ? `&lineEnd=${end}` : ""
}`
]
];
export namespace Marker {
export function getProviderDisplayName(name: string): string | undefined {
const provider = remoteProviders.find(_ => _[0] === name);
return provider && provider[1];
}
export function getRemoteCodeUrl(
remote: string,
ref: string,
file: string,
startLine: number,
endLine: number
): { displayName: string; name: string; url: string } | undefined {
let url;
for (const [name, displayName, regex, fn] of remoteProviders) {
if (!regex.test(remote)) continue;
url = fn(remote, ref, file, startLine, endLine);
if (url !== undefined) {
return { displayName: displayName, name: name, url: url };
}
}
return undefined;
}
export function getMissingMarkerIds(
markers: CSMarker[],
locations: MarkerLocationsById
): Set<string> {
const missingMarkerIds = new Set<string>();
for (const m of markers) {
if (!locations[m.id]) {
missingMarkerIds.add(m.id);
}
}
return missingMarkerIds;
}
export function getMissingMarkersByCommit(markers: CSMarker[], locations: MarkerLocationsById) {
const missingMarkerIds = Marker.getMissingMarkerIds(markers, locations);
const missingMarkersByCommitHashWhenCreated = new Map<string, CSMarker[]>();
for (const m of markers) {
if (!missingMarkerIds.has(m.id)) {
continue;
}
let markersForCommitHash = missingMarkersByCommitHashWhenCreated.get(m.commitHashWhenCreated);
if (!markersForCommitHash) {
markersForCommitHash = [];
missingMarkersByCommitHashWhenCreated.set(m.commitHashWhenCreated, markersForCommitHash);
}
Logger.log(`Missing location for marker ${m.id} - will calculate`);
markersForCommitHash.push(m);
}
return missingMarkersByCommitHashWhenCreated;
}
}
export namespace Ranges {
export function ensureStartBeforeEnd(range: Range) {
if (
range.start.line > range.end.line ||
(range.start.line === range.end.line && range.start.character > range.end.character)
) {
return Range.create(range.end, range.start);
}
return range;
}
}
export namespace Team {
export function isProvider(team: CSTeam, provider: string) {
if (provider === "codestream") return isCodeStream(team);
return (
team.providerInfo != null &&
(team.providerInfo as { [key: string]: CSTeamProviderInfos })[provider] != null
);
}
export function isCodeStream(team: CSTeam) {
return team.providerInfo == null || Object.keys(team.providerInfo).length === 0;
}
export function isMSTeams(
team: CSTeam
): team is CSTeam & { providerInfo: { msteams: CSMSTeamsProviderInfo } } {
return team.providerInfo != null && team.providerInfo.msteams != null;
}
export function isSlack(
team: CSTeam
): team is CSTeam & { providerInfo: { slack: CSSlackProviderInfo } } {
return team.providerInfo != null && team.providerInfo.slack != null;
}
}
export namespace User {
export function isMSTeams(
me: CSMe
): me is CSMe & { providerInfo: { msteams: CSMSTeamsProviderInfo } } {
return (
me.providerInfo != null &&
(me.providerInfo.msteams != null ||
Object.values(me.providerInfo).some(provider => provider.msteams != null))
);
}
export function isSlack(me: CSMe): me is CSMe & { providerInfo: { slack: CSSlackProviderInfo } } {
return (
me.providerInfo != null &&
(me.providerInfo.slack != null ||
Object.values(me.providerInfo).some(provider => provider.slack != null))
);
}
export function getProviderInfo<T extends CSProviderInfos>(
me: CSMe,
teamId: string,
name: string,
host?: string
) {
if (me.providerInfo == null) {
return undefined;
}
const userProviderInfo = me.providerInfo[name];
const teamProviderInfo = me.providerInfo[teamId] && me.providerInfo[teamId][name];
const namedProvider = userProviderInfo || teamProviderInfo;
if (!namedProvider) {
return undefined;
}
const typedProvider = (namedProvider as any) as T;
if (!host) {
return typedProvider;
}
const starredHost = host.replace(/\./g, "*");
if (typedProvider.hosts && typedProvider.hosts[starredHost]) {
return typedProvider.hosts[starredHost] as T;
}
return undefined;
}
}
export interface ActionId {
id: number;
linkType: "web" | "ide" | "external" | "reply";
externalType?: "issue" | "code";
externalProvider?: string;
teamId: string;
codemarkId: string;
markerId?: string;
streamId?: string;
creatorId?: string;
parentPostId?: string;
}
export interface ReviewActionId {
id: number;
linkType: "web" | "ide" | "review-reply";
externalProvider?: string;
teamId: string;
reviewId: string;
streamId?: string;
creatorId?: string;
parentPostId?: string;
}
export interface CodeErrorActionId {
id: number;
linkType: "web" | "ide" | "code-error-reply";
externalProvider?: string;
codeErrorId: string;
streamId?: string;
creatorId?: string;
parentPostId?: string;
}
export interface ReplyActionId {
id: number;
linkType: "web" | "ide" | "external" | "reply" | "reply-disabled";
externalType?: "issue" | "code";
// codemarkId
cId: string;
// provider creator user id, a slack userId, for example
pcuId?: string;
}
export interface CodeErrorReplyActionId {
id: number;
linkType: "web" | "ide" | "review-reply" | "review-reply-disabled" | "code-error-reply";
// codeErrorId
ceId: string;
// provider creator user id, a slack userId, for example
pcuId?: string;
}
export interface ReviewReplyActionId {
id: number;
linkType: "web" | "ide" | "review-reply" | "review-reply-disabled";
// reviewId
rId: string;
// provider creator user id, a slack userId, for example
pcuId?: string;
}
export function toReviewActionId(
id: number,
linkType: "web" | "ide" | "review-reply",
review: CSReview
): string {
const actionId: ReviewActionId = {
id: id,
linkType: linkType,
teamId: review.teamId,
reviewId: review.id
};
return JSON.stringify(actionId);
}
export function toActionId(
id: number,
linkType: "web" | "ide" | "reply",
codemark: CSCodemark,
marker?: CSMarker
): string {
const actionId: ActionId = {
id: id,
linkType: linkType,
teamId: codemark.teamId,
codemarkId: codemark.id,
markerId: marker && marker.id
};
return JSON.stringify(actionId);
}
export function toCodeErrorActionId(
id: number,
linkType: "web" | "ide" | "code-error-reply",
codeError: CSCodeError
): string {
const actionId: CodeErrorActionId = {
id: id,
codeErrorId: codeError.id,
linkType: linkType
};
return JSON.stringify(actionId);
}
export function toExternalActionId(
id: number,
providerType: "issue" | "code",
provider: string,
codemark: CSCodemark,
marker?: CSMarker
): string {
const actionId: ActionId = {
id: id,
linkType: "external",
externalType: providerType,
externalProvider: provider,
teamId: codemark.teamId,
codemarkId: codemark.id,
markerId: marker && marker.id
};
return JSON.stringify(actionId);
}
export function toCodeErrorReplyActionId(
id: number,
codeError: CSCodeError,
providerCreatorUserId?: string
): string {
const actionId: CodeErrorReplyActionId = {
id: id,
linkType: "code-error-reply",
ceId: codeError.id,
pcuId: providerCreatorUserId
};
return JSON.stringify(actionId);
}
export function toReviewReplyActionId(
id: number,
review: CSReview,
providerCreatorUserId?: string
): string {
const actionId: ReviewReplyActionId = {
id: id,
linkType: "review-reply",
rId: review.id,
pcuId: providerCreatorUserId
};
return JSON.stringify(actionId);
}
export function toReplyActionId(
id: number,
codemark: CSCodemark,
providerCreatorUserId: string
): string {
const actionId: ReplyActionId = {
id: id,
linkType: "reply",
cId: codemark.id,
pcuId: providerCreatorUserId
};
return JSON.stringify(actionId);
}
export function toReplyDisabledActionId(
id: number,
codemark: CSCodemark,
providerCreatorUserId: string
): string {
const actionId: ReplyActionId = {
id: id,
linkType: "reply-disabled",
cId: codemark.id,
pcuId: providerCreatorUserId
};
return JSON.stringify(actionId);
} | the_stack |
import * as fs from "fs";
import { performance } from "perf_hooks";
import * as path from "path";
import chalk from "chalk";
import { TestContext, IWarning, IReporter } from "@as-pect/core";
import { IConfiguration, ICompilerFlags } from "./util/IConfiguration";
import glob from "glob";
import { collectReporter } from "./util/collectReporter";
import { getTestEntryFiles } from "./util/getTestEntryFiles";
import { Options } from "./util/CommandLineArg";
import { writeFile } from "./util/writeFile";
import { ICommand } from "./worklets/ICommand";
import { timeDifference } from "@as-pect/core/lib/util/timeDifference";
import { Snapshot, SnapshotDiffResultType } from "@as-pect/snapshots";
import { removeFile } from "./util/removeFile";
/**
* @ignore
* This method actually runs the test suites in sequential order synchronously.
*
* @param {Options} cliOptions - The command line arguments.
* @param {string[]} compilerArgs - The `asc` compiler arguments.
*/
export function run(cliOptions: Options, compilerArgs: string[]): void {
const start = performance.now();
const worklets: any[] = [];
/** Collect the assemblyscript module path. */
const assemblyScriptFolder = cliOptions.compiler.startsWith(".")
? path.join(process.cwd(), cliOptions.compiler)
: cliOptions.compiler;
/**
* Create the compiler worklets if the worker flag is not 0.
*/
if (cliOptions.workers !== 0) {
const Worker = require("worker_threads").Worker;
if (!isFinite(cliOptions.workers)) {
console.error(
chalk`{red [Error]} Invalid worker configuration: {yellow ${cliOptions.workers.toString()}}`,
);
process.exit(1);
}
const workletPath = require.resolve("./worklets/compiler");
for (let i = 0; i < cliOptions.workers; i++) {
const worklet = new Worker(workletPath, {
workerData: {
assemblyScriptFolder,
},
});
worklets.push(worklet);
}
console.log(
chalk`{bgWhite.black [Log]} Using experimental compiler worklets: {yellow ${worklets.length.toString()} worklets}`,
);
}
/**
* Instead of using `import`, the strategy is to encourage node to start the testing process
* as soon as possible. Calling require and measuring the performance of compiler loading shows
* developers a meaningful explaination of why it takes a few seconds for the software to start
* running.
*/
console.log(chalk`{bgWhite.black [Log]} Loading asc compiler`);
let asc: any;
let instantiateSync: any;
let parse: any;
let exportTable: boolean = false;
try {
let folderUsed = "cli";
try {
console.log("Assemblyscript Folder:" + assemblyScriptFolder);
/** Next, obtain the compiler, and assert it has a main function. */
asc = require(path.join(assemblyScriptFolder, "cli", "asc"));
} catch (ex) {
try {
folderUsed = "dist";
asc = require(path.join(assemblyScriptFolder, "dist", "asc"));
} catch (ex) {
throw ex;
}
}
if (!asc) {
throw new Error(
`${cliOptions.compiler}/${folderUsed}/asc has no exports.`,
);
}
if (!asc.main) {
throw new Error(
`${cliOptions.compiler}/${folderUsed}/asc does not export a main() function.`,
);
}
/** Next, collect the loader, and assert it has an instantiateSync method. */
let loader;
try {
loader = require(path.join(assemblyScriptFolder, "lib", "loader"));
} catch (ex) {
loader = require(path.join(assemblyScriptFolder, "lib", "loader", "umd"));
}
if (!loader) {
throw new Error(`${cliOptions.compiler}/lib/loader has no exports.`);
}
if (!loader.instantiateSync) {
throw new Error(
`${cliOptions.compiler}/lib/loader does not export an instantiateSync() method.`,
);
}
instantiateSync = loader.instantiateSync;
/** Finally, collect the cli options from assemblyscript. */
let options = require(path.join(
assemblyScriptFolder,
"cli",
"util",
"options",
));
if (!options) {
throw new Error(`${cliOptions.compiler}/cli/util/options exports null`);
}
if (!options.parse) {
throw new Error(
`${cliOptions.compiler}/cli/util/options does not export a parse() method.`,
);
}
if (asc.options.exportTable) {
exportTable = true;
}
parse = options.parse;
} catch (ex) {
console.error(
chalk`{bgRedBright.black [Error]} There was a problem loading {bold [${cliOptions.compiler}]}.`,
);
console.error(ex);
process.exit(1);
}
console.log(
chalk`{bgWhite.black [Log]} Compiler loaded in {yellow ${timeDifference(
performance.now(),
start,
).toString()}ms}.`,
);
// obtain the configuration file
const configurationPath = path.resolve(process.cwd(), cliOptions.config);
console.log(
chalk`{bgWhite.black [Log]} Using configuration {yellow ${configurationPath}}`,
);
let configuration: IConfiguration = {};
try {
configuration = require(configurationPath) || {};
} catch (ex) {
console.error("");
console.error(
chalk`{bgRedBright.black [Error]} There was a problem loading {bold [${configurationPath}]}.`,
);
console.error(ex);
process.exit(1);
}
// configuration must be an object
if (!configuration) {
console.error(
chalk`{bgRedBright.black [Error]} Configuration at {bold [${configurationPath}]} is null or not an object.`,
);
process.exit(1);
}
const include: string[] = configuration.include || [
"assembly/__tests__/**/*.spec.ts",
];
const add: string[] = configuration.add || [
"assembly/__tests__/**/*.include.ts",
];
// parse passed cli compiler arguments and determine if there are any bad arguments.
if (compilerArgs.length > 0) {
const output = parse(compilerArgs, asc.options);
// if there are any unknown flags, report them and exit 1
if (output.unknown.length > 0) {
console.error(
chalk`{bgRedBright.black [Error]} Unknown compiler arguments {bold.yellow [${output.unknown.join(
", ",
)}]}.`,
);
process.exit(1);
}
}
// Create the compiler flags
const flags: ICompilerFlags = Object.assign({}, configuration.flags, {
"--debug": [],
"--binaryFile": ["output.wasm"],
"--explicitStart": [],
});
if (
!flags["--use"] ||
flags["--use"].includes("ASC_RTRACE=1") ||
!compilerArgs.includes("ASC_RTRACE=1")
) {
if (!flags["--use"]) {
flags["--use"] = ["ASC_RTRACE=1"];
// inspect to see if the flag is used already
} else if (!flags["--use"].includes("ASC_RTRACE=1")) {
flags["--use"].push("--use", "ASC_RTRACE=1");
}
}
/** If the export table flag exists on the cli options, use the export table flag. */
if (exportTable) {
flags["--exportTable"] = [];
}
/** Always import the memory now so that we expose the WebAssembly.Memory object to imports. */
flags["--importMemory"] = [];
/** It's useful to notify the user that optimizations will make test compile times slower. */
if (
flags.hasOwnProperty("-O3") ||
flags.hasOwnProperty("-O2") ||
flags.hasOwnProperty("--optimize") ||
compilerArgs.includes("-O3") ||
compilerArgs.includes("-O2") ||
compilerArgs.includes("--optimize")
) {
console.log(
chalk`{yellow [Warning]} Using optimizations. This may result in slow test compilation times.`,
);
}
const disclude: RegExp[] = configuration.disclude || [];
// if a reporter is specified in cli arguments, override configuration
const reporter: IReporter =
configuration.reporter || collectReporter(cliOptions);
// include all the file globs
console.log(
chalk`{bgWhite.black [Log]} Including files: ${include.join(", ")}`,
);
// Create the test and group matchers
const testRegex = new RegExp(cliOptions.test, "i");
configuration.testRegex = testRegex;
console.log(
chalk`{bgWhite.black [Log]} Running tests that match: {yellow ${testRegex.source}}`,
);
const groupRegex = new RegExp(cliOptions.group, "i");
configuration.groupRegex = groupRegex;
console.log(
chalk`{bgWhite.black [Log]} Running groups that match: {yellow ${groupRegex.source}}`,
);
/**
* Check to see if the binary files should be written to the fileSystem.
*/
const outputBinary =
(cliOptions.changed.has("outputBinary")
? cliOptions.outputBinary
: configuration.outputBinary) ?? false;
if (outputBinary) {
console.log(chalk`{bgWhite.black [Log]} Outputing Binary *.wasm files.`);
}
/**
* Check to see if the tests should be run in the first place.
*/
const runTests = !cliOptions.norun;
if (!runTests) {
console.log(
chalk`{bgWhite.black [Log]} Not running tests, only outputting files.`,
);
}
/**
* Check for memory flags from the cli options.
*/
const memorySize =
(cliOptions.changed.has("memorySize")
? cliOptions.memorySize
: configuration.memorySize) ?? 10;
const memoryMax =
(cliOptions.changed.has("memoryMax")
? cliOptions.memoryMax
: configuration.memoryMax) ?? -1;
if (!Number.isInteger(memorySize) || memorySize <= 0) {
console.error(
chalk`{red [Error]} Invalid {yellow memorySize} value (${memorySize}) [valid range is a positive interger]`,
);
process.exit(1);
}
if (!Number.isInteger(memoryMax) || memoryMax < -1) {
console.error(
chalk`{red [Error]} Invalid {yellow memoryMax} value (${memoryMax}) [valid range is a positive interger greater than {yellow memorySize}]`,
);
process.exit(1);
}
if (memoryMax > 0 && memoryMax < memorySize) {
console.error(
chalk`{red [Error]} Invalid module memory configuration, memorySize (${memorySize}) is greater than memoryMax (${memoryMax}).`,
);
process.exit(1);
}
/** Potentailly enable code coverage, using the configurated globs */
let covers: import("@as-covers/glue").Covers | null = null;
const coverageFiles =
cliOptions.coverage.length === 0
? configuration.coverage || []
: cliOptions.coverage;
if (coverageFiles.length !== 0) {
chalk`{bgWhite.black [Log]} Using code coverage: ${coverageFiles.join(
", ",
)}`;
const Covers = require("@as-covers/glue").Covers;
covers = new Covers({ files: coverageFiles });
}
/**
* Add the proper trasform.
*/
flags["--transform"] = flags["--transform"] || [];
flags["--transform"].push(require.resolve("@as-pect/core/lib/transform"));
if (covers) {
flags["--lib"] = flags["--lib"] || [];
flags["--transform"].unshift(require.resolve("@as-covers/transform/lib"));
const coversEntryPath = require.resolve("@as-covers/assembly/index.ts");
const relativeCoversEntryPath = path.relative(
process.cwd(),
coversEntryPath,
);
flags["--lib"].push(relativeCoversEntryPath);
}
// if covers is enabled, add that entry point too to add the glue code
/**
* Concatenate compiler flags.
*/
if (compilerArgs.length > 0) {
console.log(
chalk`{bgWhite.black [Log]} Adding compiler arguments: ` +
compilerArgs.join(" "),
);
}
const addedTestEntryFiles = new Set<string>();
/** Get all the test entry files. */
const testEntryFiles = getTestEntryFiles(cliOptions, include, disclude);
if (testEntryFiles.size === 0) {
console.error(
chalk`{red [Error]} No files matching the pattern were found.`,
);
process.exit(1);
}
for (const pattern of add) {
// push all the added files to the added entry point list
for (const entry of glob.sync(pattern)) {
addedTestEntryFiles.add(entry);
}
}
// If another extension is used create copy of assembly/**/*.ts files
if (flags["--extension"]) {
console.log(
chalk`{bgWhite.black [Log]} Changing extension for injected assembly files`,
);
const newExt = flags["--extension"][0].replace(".", ""); // without dot should work
const assemblyFolder = path.dirname(
require.resolve("@as-pect/assembly/assembly/index.ts"),
);
const files = glob.sync(path.join(assemblyFolder, "**/*.ts"));
files.forEach((file) => {
const dirname = path.dirname(file);
const basename = path.basename(file, path.extname(file));
fs.copyFileSync(file, path.join(dirname, basename + "." + newExt));
});
}
// must include the assembly/index.ts file located in the assembly package
const entryExt = !flags["--extension"]
? "ts"
: flags["--extension"][0].replace(".", "");
const entryPath = require.resolve(
"@as-pect/assembly/assembly/index." + entryExt,
);
const relativeEntryPath = path.relative(process.cwd(), entryPath);
// add the relativeEntryPath of as-pect to the list of compiled files for each test
addedTestEntryFiles.add(relativeEntryPath);
// Create a test runner, and run each test
let count = testEntryFiles.size;
// create the array of compiler flags from the flags object
const flagList: string[] = Object.entries(flags)
.reduce(
(args: string[], [flag, options]) =>
args.concat(
flag,
options.length == 0 || typeof options == "string"
? options
: options.join(","),
),
[],
)
.concat(compilerArgs);
let testCount = 0;
let successCount = 0;
let groupSuccessCount = 0;
let groupCount = 0;
let errors: IWarning[] = [];
let filePromises: Promise<void>[] = [];
let failed = false;
const folderMap = new Map<string, string[]>();
const fileMap = new Map<string, string>();
console.log(chalk`{bgWhite.black [Log]} Effective command line args:`);
console.log(
chalk` {green [TestFile.ts]} {yellow ${Array.from(
addedTestEntryFiles,
).join(" ")}} ${flagList.join(" ")}`,
);
// add a line seperator between the next line and this line
console.log("");
const finalCompilerArguments = [
...Array.from(addedTestEntryFiles),
...flagList,
];
function runBinary(
error: Error | null,
file: string,
binary: Uint8Array,
): number {
// if there are any compilation errors, stop the test suite
if (error) {
console.error(
chalk`{red [Error]} There was a compilation error when trying to create the wasm binary for file: ${file}.`,
);
console.error(error);
return process.exit(1);
}
// if the binary wasn't emitted, stop the test suite
if (!binary) {
console.error(
chalk`{red [Error]} There was no output binary file: ${file}. Did you forget to emit the binary with {yellow --binaryFile}?`,
);
return process.exit(1);
}
if (runTests) {
// get the folder and test basename
const testFolderName = path.dirname(file);
const testBaseName = path.basename(file, path.extname(file));
const snapshotFolder = path.resolve(
path.join(testFolderName, "__snapshots__"),
);
// collect the expected snapshots
const snapshotsLocation = path.join(
snapshotFolder,
testBaseName + ".snap",
);
let wasi: import("wasi").WASI | null = null;
if (configuration.wasi) {
const { WASI } = require("wasi");
wasi = new WASI(configuration.wasi);
}
// create a test runner
const runner = new TestContext({
fileName: file,
groupRegex: configuration.groupRegex,
testRegex: configuration.testRegex,
reporter,
binary,
snapshots: fs.existsSync(snapshotsLocation)
? Snapshot.parse(fs.readFileSync(snapshotsLocation, "utf8"))
: new Snapshot(),
wasi,
});
// detect custom imports
const customImportFileLocation = path.resolve(
path.join(testFolderName, testBaseName + ".imports.js"),
);
const configurationImports = fs.existsSync(customImportFileLocation)
? require(customImportFileLocation)
: configuration!.imports ?? {};
const memoryDescriptor: WebAssembly.MemoryDescriptor = {
initial: memorySize,
};
if (memoryMax > 0) {
memoryDescriptor.maximum = memoryMax;
}
const memory = new WebAssembly.Memory(memoryDescriptor);
let result: any;
if (typeof configurationImports === "function") {
const createImports = (imports: any) => {
const results = runner.createImports({ env: { memory } }, imports);
return covers ? covers.installImports(results) : results;
};
result = configurationImports(
memory,
createImports,
instantiateSync,
binary,
);
if (!result) {
console.error(
chalk`{red [Error]} Imports configuration function did not return an AssemblyScript module. (Did you forget to return it?)`,
);
process.exit(1);
}
} else {
const imports = runner.createImports(configurationImports);
imports.env.memory = memory;
result = instantiateSync(
binary,
covers ? covers.installImports(imports) : imports,
);
}
if (runner.errors.length > 0) {
errors.push(...runner.errors);
} else {
// call run buffer because it's already compiled
if (covers) covers.registerLoader(result);
runner.run(result);
const runnerTestCount = runner.testCount;
const runnerTestPassCount = runner.testPassCount;
const runnerGroupCount = runner.groupCount;
const runnerGroupPassCount = runner.groupPassCount;
// a snapshot may have failed or a test may have failed
if (!runner.pass) {
// if we are updating snapshots
if (cliOptions.update) {
// check the pass count, because we are ignoring snapshot results
if (
runnerTestCount !== runnerTestPassCount ||
runnerGroupCount !== runnerGroupPassCount
) {
failed = true;
}
} else {
failed = true;
}
}
// statistics
testCount += runnerTestCount;
successCount += runnerTestPassCount;
groupCount += runnerGroupCount;
groupSuccessCount += runnerGroupPassCount;
errors.push(...runner.errors); // if there are any errors, add them
// if the update flag was passed, update the snapshots
if (cliOptions.update) {
const snapshots = runner.snapshots;
if (snapshots.values.size > 0) {
const output = snapshots.stringify();
if (!fs.existsSync(snapshotFolder)) fs.mkdirSync(snapshotFolder);
filePromises.push(writeFile(snapshotsLocation, output));
} else {
if (fs.existsSync(snapshotsLocation)) {
filePromises.push(removeFile(snapshotsLocation));
}
}
} else {
// check for any added snapshots
const result = runner.expectedSnapshots;
const diff = runner.snapshotDiff;
for (const [name, diffResult] of diff!.results.entries()) {
if (diffResult.type === SnapshotDiffResultType.Added) {
result.values.set(name, diffResult.left!);
}
}
// if there are any snapshots to report, report them
if (result.values.size > 0) {
const output = result.stringify();
if (!fs.existsSync(snapshotFolder)) fs.mkdirSync(snapshotFolder);
filePromises.push(writeFile(snapshotsLocation, output));
}
}
}
}
count -= 1;
// if any tests failed, and they all ran, exit(1)
if (count === 0) {
if (runTests) {
const end = performance.now();
failed = failed || errors.length > 0;
const result = failed ? chalk`{red ✖ FAIL}` : chalk`{green ✔ PASS}`;
for (const error of errors) {
console.log(chalk`
[Error]: {red ${error.type}}: ${error.message}
[Stack]: {yellow ${error.stackTrace.split("\n").join("\n ")}}
`);
}
console.log(chalk` [Result]: ${result}
[Files]: ${testEntryFiles.size.toString()} total
[Groups]: ${groupCount.toString()} count, ${groupSuccessCount.toString()} pass
[Tests]: ${successCount.toString()} pass, ${(
testCount - successCount
).toString()} fail, ${testCount.toString()} total
[Time]: ${timeDifference(end, start).toString()}ms`);
if (covers) console.log(covers.stringify());
if (worklets.length > 0) {
for (const worklet of worklets) {
worklet.terminate();
}
}
}
Promise.all(filePromises).then(() => {
if (failed) {
console.error(errors);
process.exit(1);
}
});
}
return 0;
}
if (worklets.length > 0) {
let i = 0;
let length = worklets.length;
for (const entry of Array.from(testEntryFiles)) {
const workload: ICommand = {
type: "compile",
props: {
file: entry,
args: [entry, ...finalCompilerArguments],
outputBinary,
},
};
worklets[i % length].postMessage(workload);
}
worklets.forEach((worklet) => {
worklet.on("message", (e: ICommand) => {
runBinary(e.props.error, e.props.file, e.props.binary);
});
});
} else {
// for each file, synchronously run each test
Array.from(testEntryFiles).forEach((file: string) => {
let binary: Uint8Array;
asc.main(
[file, ...finalCompilerArguments],
{
stdout: process.stdout as any, // use any type to quelch error
stderr: process.stderr as any,
listFiles(dirname: string, baseDir: string): string[] {
const folder = path.join(baseDir, dirname);
if (folderMap.has(folder)) {
return folderMap.get(folder)!;
}
try {
const results = fs
.readdirSync(folder)
.filter((file) => /^(?!.*\.d\.ts$).*\.ts$/.test(file));
folderMap.set(folder, results);
return results;
} catch (e) {
return [];
}
},
readFile(filename: string, baseDir: string) {
const fileName = path.join(baseDir, filename);
if (fileMap.has(fileName)) {
return fileMap.get(fileName)!;
}
try {
const contents = fs.readFileSync(fileName, { encoding: "utf8" });
fileMap.set(fileName, contents);
return contents;
} catch (e) {
return null;
}
},
writeFile(name: string, contents: Uint8Array, baseDir: string = ".") {
const ext = path.extname(name);
// get the wasm file
if (ext === ".wasm") {
binary = contents;
if (!outputBinary) return;
} else if (ext === ".ts") {
filePromises.push(writeFile(path.join(baseDir, name), contents));
return;
}
const outfileName = path.join(
path.dirname(file),
path.basename(file, path.extname(file)) + ext,
);
filePromises.push(writeFile(outfileName, contents));
},
},
(error: any) => runBinary(error, file, binary),
);
});
}
} | the_stack |
import { configure } from "mobx";
import { types, Instance } from "mobx-state-tree";
import { Field, Form, RepeatingForm, SubForm, converters } from "../src";
// "always" leads to trouble during initialization.
configure({ enforceActions: "observed" });
test("setRaw with required ignore", () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string, {
required: true,
}),
});
const o = M.create({ foo: "FOO" });
const state = form.state(o);
const field = state.field("foo");
field.setRaw("");
expect(field.error).toEqual("Required");
expect(field.value).toEqual("");
field.setRaw("", { ignoreRequired: true });
expect(field.error).toBeUndefined();
expect(field.value).toEqual("");
expect(o.foo).toEqual("");
});
test("setRaw with required ignore with automatically required", () => {
const M = types.model("M", {
foo: types.number,
});
const form = new Form(M, {
foo: new Field(converters.number),
});
const o = M.create({ foo: 1 });
const state = form.state(o);
const field = state.field("foo");
field.setRaw("");
expect(field.error).toEqual("Required");
expect(field.value).toEqual(1);
// we can set ignoreRequired, but it has no impact
// if the field *has* to be required by definition
field.setRaw("", { ignoreRequired: true });
expect(field.error).toEqual("Required");
expect(field.value).toEqual(1);
expect(o.foo).toEqual(1);
});
test("FormState can be saved ignoring required", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: "FOO" });
const form = new Form(M, {
foo: new Field(converters.string, { required: true }),
});
let saved = false;
async function save(data: any) {
saved = true;
return null;
}
const state = form.state(o, { backend: { save } });
const field = state.field("foo");
// we set the raw to the empty string even though it's required
field.setRaw("");
expect(field.error).toEqual("Required");
expect(o.foo).toEqual("");
// now we save, ignoring required
const saveResult = await state.save({ ignoreRequired: true });
// we expect the required message to be gone after save with ignoreRequired
expect(field.error).toEqual(undefined);
// saving actually succeeded
expect(o.foo).toEqual("");
expect(saveResult).toBeTruthy();
expect(saved).toBeTruthy();
// saving again without ignoreRequired will be an error
const saveResult1 = await state.save();
expect(saveResult1).toBeFalsy();
expect(field.error).toEqual("Required");
});
test("FormState can be saved ignoring external errors", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: "FOO" });
const form = new Form(M, {
foo: new Field(converters.string),
});
let saved = false;
async function save(data: any) {
saved = true;
return null;
}
// we need to define a process as ignoreGetError is enabled automatically
// otherwise
async function process(node: Instance<typeof M>, path: string) {
return {
updates: [],
accessUpdates: [],
errorValidations: [],
warningValidations: [],
};
}
const state = form.state(o, {
backend: { save, process },
getError: (accessor) => (accessor.path === "/foo" ? "Wrong!" : undefined),
});
const field = state.field("foo");
// we change a value to trigger the error
field.setRaw("BAR");
expect(field.error).toEqual("Wrong!");
// this is an external error, so change does happen
expect(o.foo).toEqual("BAR");
expect(field.isInternallyValid).toBeTruthy();
// we are without internal errors
expect(state.validate({ ignoreGetError: true })).toBeTruthy();
// now we save, ignoring external error
const saveResult = await state.save({ ignoreGetError: true });
expect(field.error).toEqual("Wrong!");
expect(o.foo).toEqual("BAR");
expect(saveResult).toBeTruthy();
expect(saved).toBeTruthy();
// but saving again without ignoreGetError will be an error
const saveResult1 = await state.save();
expect(saveResult1).toBeFalsy();
expect(field.error).toEqual("Wrong!");
});
test("FormState can be saved ignoring non-field external errors", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: "FOO" });
const form = new Form(M, {
foo: new Field(converters.string),
});
let saved = false;
async function save(data: any) {
saved = true;
return null;
}
// we need to define a process as ignoreGetError is enabled automatically
// otherwise
async function process(node: Instance<typeof M>, path: string) {
return {
updates: [],
accessUpdates: [],
errorValidations: [],
warningValidations: [],
};
}
const state = form.state(o, {
backend: { save, process },
getError: (accessor) => (accessor.path === "" ? "Wrong!" : undefined),
});
const field = state.field("foo");
// we have an internal error
expect(state.validate()).toBeFalsy();
// we can ignore it
expect(state.validate({ ignoreGetError: true })).toBeTruthy();
// now we save, ignoring external error
const saveResult = await state.save({ ignoreGetError: true });
expect(state.error).toEqual("Wrong!");
expect(saveResult).toBeTruthy();
expect(saved).toBeTruthy();
// but saving again without ignoreGetError will be an error
const saveResult1 = await state.save();
expect(saveResult1).toBeFalsy();
});
test("ignoreGetError repeating indexed accessor non-field external", async () => {
const N = types.model("N", {
foo: types.string,
});
const M = types.model("M", {
items: types.array(N),
});
const o = M.create({ items: [{ foo: "FOO" }] });
const form = new Form(M, {
items: new RepeatingForm({ foo: new Field(converters.string) }),
});
let saved = false;
async function save(data: any) {
saved = true;
return null;
}
// we need to define a process as ignoreGetError is enabled automatically
// otherwise
async function process(node: Instance<typeof M>, path: string) {
return {
updates: [],
accessUpdates: [],
errorValidations: [],
warningValidations: [],
};
}
const state = form.state(o, {
backend: { save, process },
getError: (accessor) =>
accessor.path === "/items/0" ? "Wrong!" : undefined,
});
// we have an internal error
expect(state.validate()).toBeFalsy();
// we can ignore it
expect(state.validate({ ignoreGetError: true })).toBeTruthy();
// now we save, ignoring external error
const saveResult = await state.save({ ignoreGetError: true });
expect(saveResult).toBeTruthy();
expect(saved).toBeTruthy();
// but saving again without ignoreGetError will be an error
const saveResult1 = await state.save();
expect(saveResult1).toBeFalsy();
});
test("ignoreGetError repeating accessor non-field external", async () => {
const N = types.model("N", {
foo: types.string,
});
const M = types.model("M", {
items: types.array(N),
});
const o = M.create({ items: [{ foo: "FOO" }] });
const form = new Form(M, {
items: new RepeatingForm({ foo: new Field(converters.string) }),
});
let saved = false;
async function save(data: any) {
saved = true;
return null;
}
// we need to define a process as ignoreGetError is enabled automatically
// otherwise
async function process(node: Instance<typeof M>, path: string) {
return {
updates: [],
accessUpdates: [],
errorValidations: [],
warningValidations: [],
};
}
const state = form.state(o, {
backend: { save, process },
getError: (accessor) => (accessor.path === "/items" ? "Wrong!" : undefined),
});
// we have an internal error
expect(state.validate()).toBeFalsy();
// we can ignore it
expect(state.validate({ ignoreGetError: true })).toBeTruthy();
// now we save, ignoring external error
const saveResult = await state.save({ ignoreGetError: true });
expect(saveResult).toBeTruthy();
expect(saved).toBeTruthy();
// but saving again without ignoreGetError will be an error
const saveResult1 = await state.save();
expect(saveResult1).toBeFalsy();
});
test("ignoreGetError sub form accessor non-field external", async () => {
const N = types.model("N", {
foo: types.string,
});
const M = types.model("M", {
item: N,
});
const o = M.create({ item: { foo: "FOO" } });
const form = new Form(M, {
item: new SubForm({ foo: new Field(converters.string) }),
});
let saved = false;
async function save(data: any) {
saved = true;
return null;
}
// we need to define a process as ignoreGetError is enabled automatically
// otherwise
async function process(node: Instance<typeof M>, path: string) {
return {
updates: [],
accessUpdates: [],
errorValidations: [],
warningValidations: [],
};
}
const state = form.state(o, {
backend: { save, process },
getError: (accessor) => (accessor.path === "/item" ? "Wrong!" : undefined),
});
// we have an internal error
expect(state.validate()).toBeFalsy();
// we can ignore it
expect(state.validate({ ignoreGetError: true })).toBeTruthy();
// now we save, ignoring external error
const saveResult = await state.save({ ignoreGetError: true });
expect(saveResult).toBeTruthy();
expect(saved).toBeTruthy();
// but saving again without ignoreGetError will be an error
const saveResult1 = await state.save();
expect(saveResult1).toBeFalsy();
});
test("FormState can be saved without affecting save status", async () => {
const M = types.model("M", {
foo: types.string,
});
const o = M.create({ foo: "FOO" });
const form = new Form(M, {
foo: new Field(converters.string),
});
async function save(data: any) {
return null;
}
const state = form.state(o, {
backend: { save },
getError: (accessor) => (accessor.path === "/foo" ? "Wrong!" : undefined),
});
// now we save, ignoring save status
await state.save({ ignoreSaveStatus: true });
expect(state.saveStatus).toEqual("before");
}); | the_stack |
import { URLSearchParams } from './url-search-params';
// https://github.com/Polymer/URL
var relative = Object.create(null);
relative.ftp = 21;
relative.file = 0;
relative.gopher = 70;
relative.http = 80;
relative.https = 443;
relative.ws = 80;
relative.wss = 443;
var relativePathDotMapping = Object.create(null);
relativePathDotMapping['%2e'] = '.';
relativePathDotMapping['.%2e'] = '..';
relativePathDotMapping['%2e.'] = '..';
relativePathDotMapping['%2e%2e'] = '..';
function isRelativeScheme(scheme: string) {
return relative[scheme] !== undefined;
}
function percentEscape(c: string) {
var unicode = c.charCodeAt(0);
if (unicode > 0x20 &&
unicode < 0x7F &&
// " # < > ? `
[0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1
) {
return c;
}
return encodeURIComponent(c);
}
function percentEscapeQuery(c: string) {
// XXX This actually needs to encode c using encoding and then
// convert the bytes one-by-one.
var unicode = c.charCodeAt(0);
if (unicode > 0x20 &&
unicode < 0x7F &&
// " # < > ` (do not escape '?')
[0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1
) {
return c;
}
return encodeURIComponent(c);
}
const EOF = undefined;
const ALPHA = /[a-zA-Z]/;
const ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
// Does not process domain names or IP addresses.
// Does not handle encoding for the query parameter.
export class URL {
_url: string;
_isInvalid: boolean;
_isRelative: boolean;
_username: string;
_password: null | string;
_scheme: string;
_query: string;
_fragment: string;
_host: string;
_port: string;
_path: any[];
_schemeData: string;
_searchParams: URLSearchParams;
_shouldUpdateSearchParams = true;
constructor(url: string, base?: string | URL) {
if (base !== undefined && !(base instanceof URL))
base = new URL(String(base));
this._url = url;
this._clear();
var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
// encoding = encoding || 'utf-8'
this._parse(input, null, base);
const searchParams = this._searchParams = new URLSearchParams(this.search);
['append', 'delete', 'set'].forEach((methodName) => {
var method = searchParams[methodName];
searchParams[methodName] = (...args: any) => {
method.apply(searchParams, args);
this._shouldUpdateSearchParams = false;
this.search = searchParams.toString();
this._shouldUpdateSearchParams = true;
};
});
}
private _clear() {
this._scheme = '';
this._schemeData = '';
this._username = '';
this._password = null;
this._host = '';
this._port = '';
this._path = [];
this._query = '';
this._fragment = '';
this._isInvalid = false;
this._isRelative = false;
}
private _invalid() {
this._clear();
this._isInvalid = true;
}
private _IDNAToASCII(h: string) {
if ('' == h) {
this._invalid();
}
// XXX
return h.toLowerCase();
}
private _parse(input: string, stateOverride: any, base?: any) {
var state = stateOverride || 'scheme start',
cursor = 0,
buffer = '',
rawQuery = '',
seenAt = false,
seenBracket = false,
errors = [];
function err(message: string) {
errors.push(message);
}
loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
var c = input[cursor];
switch (state) {
case 'scheme start':
if (c && ALPHA.test(c)) {
buffer += c.toLowerCase(); // ASCII-safe
state = 'scheme';
} else if (!stateOverride) {
buffer = '';
state = 'no scheme';
continue;
} else {
err('Invalid scheme.');
break loop;
}
break;
case 'scheme':
if (c && ALPHANUMERIC.test(c)) {
buffer += c.toLowerCase(); // ASCII-safe
} else if (':' == c) {
this._scheme = buffer;
buffer = '';
if (stateOverride) {
break loop;
}
if (isRelativeScheme(this._scheme)) {
this._isRelative = true;
}
if ('file' == this._scheme) {
state = 'relative';
} else if (this._isRelative && base && base._scheme == this._scheme) {
state = 'relative or authority';
} else if (this._isRelative) {
state = 'authority first slash';
} else {
state = 'scheme data';
}
} else if (!stateOverride) {
buffer = '';
cursor = 0;
state = 'no scheme';
continue;
} else if (EOF == c) {
break loop;
} else {
err('Code point not allowed in scheme: ' + c);
break loop;
}
break;
case 'scheme data':
if ('?' == c) {
state = 'query';
} else if ('#' == c) {
this._fragment = '#';
state = 'fragment';
} else {
// XXX error handling
if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
this._schemeData += percentEscape(c);
}
}
break;
case 'no scheme':
if (!base || !isRelativeScheme(base._scheme)) {
err('Missing scheme.');
this._invalid();
} else {
state = 'relative';
continue;
}
break;
case 'relative or authority':
if ('/' == c && '/' == input[cursor + 1]) {
state = 'authority ignore slashes';
} else {
err('Expected /, got: ' + c);
state = 'relative';
continue;
}
break;
case 'relative':
this._isRelative = true;
if ('file' != this._scheme)
this._scheme = base._scheme;
if (EOF == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
rawQuery = base._query;
this._username = base._username;
this._password = base._password;
break loop;
} else if ('/' == c || '\\' == c) {
if ('\\' == c)
err('\\ is an invalid code point.');
state = 'relative slash';
} else if ('?' == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
rawQuery = '?';
this._username = base._username;
this._password = base._password;
state = 'query';
} else if ('#' == c) {
this._host = base._host;
this._port = base._port;
this._path = base._path.slice();
rawQuery = base._query;
this._fragment = '#';
this._username = base._username;
this._password = base._password;
state = 'fragment';
} else {
var nextC = input[cursor + 1];
var nextNextC = input[cursor + 2];
if (
'file' != this._scheme || !ALPHA.test(c) ||
nextC != ':' && nextC != '|' ||
EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC) {
this._host = base._host;
this._port = base._port;
this._username = base._username;
this._password = base._password;
this._path = base._path.slice();
this._path.pop();
}
state = 'relative path';
continue;
}
break;
case 'relative slash':
if ('/' == c || '\\' == c) {
if ('\\' == c) {
err('\\ is an invalid code point.');
}
if ('file' == this._scheme) {
state = 'file host';
} else {
state = 'authority ignore slashes';
}
} else {
if ('file' != this._scheme) {
this._host = base._host;
this._port = base._port;
this._username = base._username;
this._password = base._password;
}
state = 'relative path';
continue;
}
break;
case 'authority first slash':
if ('/' == c) {
state = 'authority second slash';
} else {
err("Expected '/', got: " + c);
state = 'authority ignore slashes';
continue;
}
break;
case 'authority second slash':
state = 'authority ignore slashes';
if ('/' != c) {
err("Expected '/', got: " + c);
continue;
}
break;
case 'authority ignore slashes':
if ('/' != c && '\\' != c) {
state = 'authority';
continue;
} else {
err('Expected authority, got: ' + c);
}
break;
case 'authority':
if ('@' == c) {
if (seenAt) {
err('@ already seen.');
buffer += '%40';
}
seenAt = true;
for (let cp of buffer) {
if ('\t' == cp || '\n' == cp || '\r' == cp) {
err('Invalid whitespace in authority.');
continue;
}
// XXX check URL code points
if (':' == cp && null === this._password) {
this._password = '';
continue;
}
var tempC = percentEscape(cp);
null !== this._password ? this._password += tempC : this._username += tempC;
}
buffer = '';
} else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
cursor -= buffer.length;
buffer = '';
state = 'host';
continue;
} else {
buffer += c;
}
break;
case 'file host':
if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) {
state = 'relative path';
} else if (buffer.length == 0) {
state = 'relative path start';
} else {
this._host = this._IDNAToASCII(buffer);
buffer = '';
state = 'relative path start';
}
continue;
} else if ('\t' == c || '\n' == c || '\r' == c) {
err('Invalid whitespace in file host.');
} else {
buffer += c;
}
break;
case 'host':
case 'hostname':
if (':' == c && !seenBracket) {
// XXX host parsing
this._host = this._IDNAToASCII(buffer);
buffer = '';
state = 'port';
if ('hostname' == stateOverride) {
break loop;
}
} else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
this._host = this._IDNAToASCII(buffer);
buffer = '';
state = 'relative path start';
if (stateOverride) {
break loop;
}
continue;
} else if ('\t' != c && '\n' != c && '\r' != c) {
if ('[' == c) {
seenBracket = true;
} else if (']' == c) {
seenBracket = false;
}
buffer += c;
} else {
err('Invalid code point in host/hostname: ' + c);
}
break;
case 'port':
if (/[0-9]/.test(c)) {
buffer += c;
} else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) {
if ('' != buffer) {
var temp = parseInt(buffer, 10);
if (temp != relative[this._scheme]) {
this._port = temp + '';
}
buffer = '';
}
if (stateOverride) {
break loop;
}
state = 'relative path start';
continue;
} else if ('\t' == c || '\n' == c || '\r' == c) {
err('Invalid code point in port: ' + c);
} else {
this._invalid();
}
break;
case 'relative path start':
if ('\\' == c)
err("'\\' not allowed in path.");
state = 'relative path';
if ('/' != c && '\\' != c) {
continue;
}
break;
case 'relative path':
if (EOF == c || '/' == c || '\\' == c || !stateOverride && ('?' == c || '#' == c)) {
if ('\\' == c) {
err('\\ not allowed in relative path.');
}
var tmp;
if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
buffer = tmp;
}
if ('..' == buffer) {
this._path.pop();
if ('/' != c && '\\' != c) {
this._path.push('');
}
} else if ('.' == buffer && '/' != c && '\\' != c) {
this._path.push('');
} else if ('.' != buffer) {
if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') {
buffer = buffer[0] + ':';
}
this._path.push(buffer);
}
buffer = '';
if ('?' == c) {
rawQuery = '?';
state = 'query';
} else if ('#' == c) {
this._fragment = '#';
state = 'fragment';
}
} else if ('\t' != c && '\n' != c && '\r' != c) {
buffer += percentEscape(c);
}
break;
case 'query':
if (!stateOverride && '#' == c) {
this._fragment = '#';
state = 'fragment';
} else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
rawQuery += c;
}
break;
case 'fragment':
if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
this._fragment += c;
}
break;
}
cursor++;
}
// Handle unicode in query.
for (let char of rawQuery) {
this._query += percentEscapeQuery(char);
}
}
get href() {
if (this._isInvalid)
return this._url;
var authority = '';
if ('' != this._username || null != this._password) {
authority = this._username +
(null != this._password ? ':' + this._password : '') + '@';
}
return this.protocol +
(this._isRelative ? '//' + authority + this.host : '') +
this.pathname + this._query + this._fragment;
}
set href(href) {
this._clear();
this._parse(href, null);
}
get protocol() {
return this._scheme + ':';
}
set protocol(protocol) {
if (this._isInvalid)
return;
this._parse(protocol + ':', 'scheme start');
}
get host() {
return this._isInvalid ? '' : this._port ?
this._host + ':' + this._port : this._host;
}
set host(host) {
if (this._isInvalid || !this._isRelative)
return;
this._parse(host, 'host');
}
get hostname() {
return this._host;
}
set hostname(hostname) {
if (this._isInvalid || !this._isRelative)
return;
this._parse(hostname, 'hostname');
}
get port() {
return this._port;
}
set port(port) {
if (this._isInvalid || !this._isRelative)
return;
this._parse(port, 'port');
}
get pathname() {
return this._isInvalid ? '' : this._isRelative ?
'/' + this._path.join('/') : this._schemeData;
}
set pathname(pathname) {
if (this._isInvalid || !this._isRelative)
return;
this._path = [];
this._parse(pathname, 'relative path start');
}
get search() {
return this._isInvalid || !this._query || '?' == this._query ?
'' : this._query;
}
set search(search: string) {
if (this._isInvalid || !this._isRelative)
return;
search = '' + search;
if (search == '') {
this._query = search;
} else {
this._query = '?';
}
if ('?' == search[0])
search = search.slice(1);
this._parse(search, 'query');
if (this._shouldUpdateSearchParams) {
// @ts-ignore
this._searchParams._reset();
// @ts-ignore
this._searchParams._fromString(this.search);
}
}
get searchParams() {
return this._searchParams;
}
get hash() {
return this._isInvalid || !this._fragment || '#' == this._fragment ?
'' : this._fragment;
}
set hash(hash) {
if (this._isInvalid)
return;
this._fragment = '#';
if ('#' == hash[0])
hash = hash.slice(1);
this._parse(hash, 'fragment');
}
get origin() {
var host;
if (this._isInvalid || !this._scheme) {
return '';
}
// javascript: Gecko returns String(""), WebKit/Blink String("null")
// Gecko throws error for "data://"
// data: Gecko returns "", Blink returns "data://", WebKit returns "null"
// Gecko returns String("") for file: mailto:
// WebKit/Blink returns String("SCHEME://") for file: mailto:
switch (this._scheme) {
case 'data':
case 'file':
case 'javascript':
case 'mailto':
return 'null';
}
host = this.host;
if (!host) {
return '';
}
return this._scheme + '://' + host;
}
toString() {
return this.href;
}
} | the_stack |
import { ApiResourceScopeDTO } from '../entities/dtos/api-resource-allowed-scope.dto'
import { ApiResourceSecretDTO } from '../entities/dtos/api-resource-secret.dto'
import { ApiResourcesDTO } from '../entities/dtos/api-resources-dto'
import { ApiScopeDTO } from '../entities/dtos/api-scope-dto'
import { ApiScopeGroupDTO } from '../entities/dtos/api-scope-group.dto'
import { DomainDTO } from '../entities/dtos/domain.dto'
import IdentityResourceDTO from '../entities/dtos/identity-resource.dto'
import { UserClaimDTO } from '../entities/dtos/user-claim-dto'
import { ApiResourceScope } from '../entities/models/api-resource-scope.model'
import { ApiResourceSecret } from '../entities/models/api-resource-secret.model'
import { ApiResourceUserClaim } from '../entities/models/api-resource-user-claim.model'
import { ApiResource } from '../entities/models/api-resource.model'
import { ApiScopeGroup } from '../entities/models/api-scope-group.model'
import { ApiScopeUserClaim } from '../entities/models/api-scope-user-claim.model'
import { ApiScope } from '../entities/models/api-scope.model'
import { Domain } from '../entities/models/domain.model'
import { IdentityResourceUserClaim } from '../entities/models/identity-resource-user-claim.model'
import { IdentityResource } from '../entities/models/identity-resource.model'
import { PagedRowsDTO } from '../entities/models/paged-rows.dto'
import { BaseService } from './BaseService'
export class ResourcesService extends BaseService {
/** Gets API scope by name */
static async getApiResourceByName(name: string): Promise<ApiResource | null> {
return BaseService.GET(`api-resource/${encodeURIComponent(name)}`)
}
/** Gets all identity resource user claims */
static async findAllIdentityResourceUserClaims(): Promise<
IdentityResourceUserClaim[] | undefined
> {
return BaseService.GET('identity-resource-user-claim')
}
/** Gets all identity resource user claims */
static async findAllApiScopeUserClaims(): Promise<
ApiScopeUserClaim[] | undefined
> {
return BaseService.GET('api-scope-user-claim')
}
/** Gets all Api resource user claims */
static async findAllApiResourceUserClaims(): Promise<
ApiResourceUserClaim[] | undefined
> {
return BaseService.GET('api-resource-user-claim')
}
/** Creates a new claim for ApiResource */
static async createApiResourceUserClaim(
claim: UserClaimDTO,
): Promise<ApiResourceUserClaim | undefined> {
return BaseService.POST('api-resource-user-claim', claim)
}
/** Creates a new claim for ApiScope */
static async createApiScopeUserClaim(
claim: UserClaimDTO,
): Promise<ApiResourceUserClaim | undefined> {
return BaseService.POST('api-scope-user-claim', claim)
}
/** Creates a new claim for Identity Resource */
static async createIdentityResourceUserClaim(
claim: UserClaimDTO,
): Promise<ApiResourceUserClaim | undefined> {
return BaseService.POST('identity-resource-user-claim', claim)
}
/** Gets API scope by name */
static async getApiScopeByName(name: string): Promise<ApiScope | null> {
return BaseService.GET(`api-scope/${encodeURIComponent(name)}`)
}
/** Gets if scope name or identity resource name is availabe */
static async isScopeNameAvailable(name): Promise<boolean> {
return BaseService.GET(
`is-scope-name-available/${encodeURIComponent(name)}`,
)
}
/** Updates an existing Api Scope */
static async updateApiResource(
apiResource: ApiResourcesDTO,
name: string,
): Promise<ApiResource | null> {
return BaseService.PUT(
`api-resource/${encodeURIComponent(name)}`,
apiResource,
)
}
/** Update an Api Scope */
static async updateApiScope(apiScope: ApiScopeDTO): Promise<ApiScope> {
return BaseService.PUT(
`api-scope/${encodeURIComponent(apiScope.name)}`,
apiScope,
)
}
/** Finds all access controlled Api scopes */
static async findAllAccessControlledApiScopes(): Promise<ApiScope[] | null> {
return BaseService.GET('access-controlled-scopes')
}
/** Gets Identity resource by name */
static async getIdentityResourceByName(
name: string,
): Promise<IdentityResource | null> {
return BaseService.GET(`identity-resource/${encodeURIComponent(name)}`)
}
/** Creates a new identity resource */
static async createIdentityResource(
identityResource: IdentityResourceDTO,
): Promise<IdentityResource | null> {
return BaseService.POST(`identity-resource`, identityResource)
}
/** Updates an existing Identity resource */
static async updateIdentityResource(
identityResource: IdentityResourceDTO,
name: string,
): Promise<IdentityResource | null> {
return BaseService.PUT(
`identity-resource/${encodeURIComponent(name)}`,
identityResource,
)
}
/** Add User Claim to Identity Resource */
static async addIdentityResourceUserClaim(
identityResourceName: string,
claimName: string,
): Promise<IdentityResourceUserClaim | null> {
return BaseService.POST(
`identity-resource-user-claims/${encodeURIComponent(
identityResourceName,
)}/${encodeURIComponent(claimName)}`,
)
}
/** Removes User claim from Identity resource */
static async removeIdentityResourceUserClaim(
identityResourceName: string,
claimName: string,
): Promise<number> {
return BaseService.DELETE(
`identity-resource-user-claims/${encodeURIComponent(
identityResourceName,
)}/${encodeURIComponent(claimName)}`,
)
}
/** Adds user claim to Api Scope */
static async addApiScopeUserClaim(
apiScopeName: string,
claimName: string,
): Promise<IdentityResourceUserClaim | null> {
return BaseService.POST(
`api-scope-user-claims/${encodeURIComponent(
apiScopeName,
)}/${encodeURIComponent(claimName)}`,
)
}
/** Removes user claim from Api Scope */
static async removeApiScopeUserClaim(
apiScopeName: string,
claimName: string,
): Promise<number> {
return BaseService.DELETE(
`api-scope-user-claims/${encodeURIComponent(
apiScopeName,
)}/${encodeURIComponent(claimName)}`,
)
}
/** Creates a new Api Resource */
static async createApiResource(
apiResource: ApiResourcesDTO,
): Promise<ApiResource> {
return BaseService.POST('api-resource', apiResource)
}
/** Deletes an API resource */
static async deleteApiResource(name: string): Promise<number> {
return BaseService.DELETE(`api-resource/${encodeURIComponent(name)}`)
}
/** Get's all Api resources and total count of rows */
static async findAndCountAllApiResources(
searchString: string,
page: number,
count: number,
): Promise<{
rows: ApiResource[]
count: number
} | null> {
return BaseService.GET(
`api-resources?searchString=${searchString}&page=${page}&count=${count}`,
)
}
/** Get's all Api resources without count */
static async findAllApiResources(): Promise<ApiResource[] | null> {
return BaseService.GET(`all-api-resources`)
}
/** Creates a new Api Scope */
static async createApiScope(apiScope: ApiScopeDTO): Promise<ApiScope | null> {
return BaseService.POST('api-scope', apiScope)
}
/** Get's all Api scopes and total count of rows */
static async findAndCountAllApiScopes(
page: number,
count: number,
): Promise<{
rows: ApiScope[]
count: number
} | null> {
return BaseService.GET(`api-scopes?page=${page}&count=${count}`)
}
/** Deletes an API scope */
static async deleteApiScope(name: string): Promise<number> {
return BaseService.DELETE(`api-scope/${encodeURIComponent(name)}`)
}
/** Get's all identity resources and total count of rows */
static async findAndCountAllIdentityResources(
page: number,
count: number,
): Promise<{
rows: IdentityResource[]
count: number
} | null> {
return BaseService.GET(`identity-resources?page=${page}&count=${count}`)
}
/** Deletes an identity resource by name */
static async deleteIdentityResource(name: string): Promise<number> {
return BaseService.DELETE(`identity-resource/${encodeURIComponent(name)}`)
}
/** Adds claim to Api resource */
static async addApiResourceUserClaim(
apiResourceName: string,
claimName: string,
): Promise<ApiResourceUserClaim> {
return BaseService.POST(
`api-resource-claims/${encodeURIComponent(
apiResourceName,
)}/${encodeURIComponent(claimName)}`,
)
}
/** Get the api resource that is connected to a scope */
static async findApiResourceScopeByScopeName(
scopeName: string,
): Promise<ApiResourceScope | null> {
return BaseService.GET(
`api-scope-resource/${encodeURIComponent(scopeName)}`,
)
}
/** Delete Api Scope from Api Resource Scope */
static async deleteApiResourceScopeByScopeName(
scopeName: string,
): Promise<number | null> {
return BaseService.DELETE(
`api-scope-resource/${encodeURIComponent(scopeName)}`,
)
}
/** Removes user claim from Api Resource */
static async removeApiResourceUserClaim(
apiResourceName: string,
claimName: string,
): Promise<number | null> {
return BaseService.DELETE(
`api-resource-claims/${encodeURIComponent(
apiResourceName,
)}/${encodeURIComponent(claimName)}`,
)
}
/** Add secret to ApiResource */
static async addApiResourceSecret(
apiSecret: ApiResourceSecretDTO,
): Promise<ApiResourceSecret | null> {
return BaseService.POST('api-resource-secret', apiSecret)
}
/** Remove a secret from Api Resource */
static async removeApiResourceSecret(
apiSecret: ApiResourceSecretDTO,
): Promise<number | null> {
return BaseService.DELETE('api-resource-secret', apiSecret)
}
/** Adds an allowed scope to api resource */
static async addApiResourceAllowedScope(
resourceAllowedScope: ApiResourceScopeDTO,
): Promise<ApiResourceScope | null> {
return BaseService.POST('api-resources-allowed-scope', resourceAllowedScope)
}
/** Removes an allowed scope from api Resource */
static async removeApiResourceAllowedScope(
apiResourceName: string,
scopeName: string,
): Promise<number | null> {
return BaseService.DELETE(
`api-resources-allowed-scope/${encodeURIComponent(
apiResourceName,
)}/${encodeURIComponent(scopeName)}`,
)
}
static async getApiResourcesCsv(): Promise<any[] | null> {
const result = await BaseService.GET(
`api-resources?page=${1}&count=${Number.MAX_SAFE_INTEGER}`,
)
return result.rows.map((r) => ResourcesService.toApiResourceCsv(r))
}
static toApiResourceCsv = (apiResource: ApiResource): any[] => {
return [
apiResource.name,
apiResource.displayName,
apiResource.nationalId,
apiResource.contactEmail,
apiResource.created,
apiResource.modified,
apiResource.enabled,
apiResource.archived,
]
}
static getApiResourcesCsvHeaders(): string[] {
return [
'Name',
'DisplayName',
'NationalId',
'Contact',
'Created',
'Modified',
'Enabled',
'Archived',
]
}
// #region ApiScopeGroup
/** Creates a new Api Scope Group */
static async createApiScopeGroup(
group: ApiScopeGroupDTO,
): Promise<ApiScopeGroup | null> {
return BaseService.POST(`api-scope-group`, group)
}
/** Updates an existing ApiScopeGroup */
static async updateApiScopeGroup(
group: ApiScopeGroupDTO,
id: string,
): Promise<[number, ApiScopeGroup[]] | null> {
return BaseService.PUT(`api-scope-group/${id}`, group)
}
/** Delete ApiScopeGroup */
static async deleteApiScopeGroup(id: string): Promise<number | null> {
return BaseService.DELETE(`api-scope-group/${id}`)
}
/** Returns a ApiScopeGroup by Id */
static async findApiScopeGroup(id: string): Promise<ApiScopeGroup> {
return BaseService.GET(`api-scope-group/${encodeURIComponent(id)}`)
}
/** Returns all ApiScopeGroups with Paging */
static async findAllApiScopeGroups(
searchString: string = null,
page: number = null,
count: number = null,
): Promise<
| {
rows: ApiScopeGroup[]
count: number
}
| ApiScopeGroup[]
| null
> {
if (page && count) {
return BaseService.GET(
`api-scope-group?searchString=${searchString}&page=${page}&count=${count}`,
)
}
return BaseService.GET(`api-scope-group`)
}
// #endregion ApiScopeGroup
// #region Domain
/** Find all domains with or without paging */
static async findAllDomains(
searchString: string | null = null,
page: number | null = null,
count: number | null = null,
): Promise<Domain[] | PagedRowsDTO<Domain>> {
return BaseService.GET(
`domain?searchString=${searchString}&page=${page}&count=${count}`,
)
}
/** Gets domain by it's name */
static async getDomain(name: string): Promise<Domain> {
return BaseService.GET(`domain/${name}`)
}
/** Creates a new Domain */
static async createDomain(domain: DomainDTO): Promise<Domain> {
return BaseService.POST(`domain`, domain)
}
/** Updates an existing Domain */
static async updateDomain(
domain: DomainDTO,
name: string,
): Promise<[number, Domain[]]> {
return BaseService.PUT(`domain/${name}`, domain)
}
/** Delete Domain */
static async deleteDomain(name: string): Promise<number> {
return BaseService.DELETE(`domain/${name}`)
}
// #endregion Domain
} | the_stack |
import {Oas20Document} from "../src/models/2.0/document.model";
import {OasLibraryUtils} from "../src/library.utils";
import {Oas30Document} from "../src/models/3.0/document.model";
import {OasAllNodeVisitor} from "../src/visitors/visitor.base";
import {OasNode} from "../src/models/node.model";
import {OasVisitorUtil} from "../src/visitors/visitor.utils";
export interface TestSpec {
name: string;
test: string;
extraProperties: number;
debug?: boolean;
}
/**
* This function recursively sorts all objects by property name. This is so that it is
* easier to compare two objects.
* @param original
* @return {any}
*/
function sortObj(original: any): any {
let sorted: any = {};
Object.keys(original).sort().forEach(function(key) {
let val: any = original[key];
if (typeof val === 'object') {
val = sortObj(val);
}
sorted[key] = val;
});
return sorted;
}
class ExtraPropertyDetectionVisitor extends OasAllNodeVisitor {
public numDetected: number = 0;
protected doVisitNode(node: OasNode): void {
if (node.hasExtraProperties()) {
this.numDetected += node.getExtraPropertyNames().length;
}
}
}
/**
* Full I/O Tests for Version 2.0 of the OpenAPI Specification.
*/
describe("Full I/O (2.0)", () => {
let TESTS: TestSpec[] = [
{ name: "Simple (Easy 2.0 spec)", test: "tests/fixtures/full-io/2.0/simple/simplest.json", extraProperties: 0 },
{ name: "Simple (Info)", test: "tests/fixtures/full-io/2.0/simple/simple-info.json", extraProperties: 0 },
{ name: "Simple (Info + extensions)", test: "tests/fixtures/full-io/2.0/simple/simple-info-extensions.json", extraProperties: 0 },
{ name: "Simple (Tags)", test: "tests/fixtures/full-io/2.0/simple/simple-tags.json", extraProperties: 0 },
{ name: "Simple (External Docs)", test: "tests/fixtures/full-io/2.0/simple/simple-externalDocs.json", extraProperties: 0 },
{ name: "Simple (Security Definitions)", test: "tests/fixtures/full-io/2.0/simple/simple-securityDefinitions.json", extraProperties: 0 },
{ name: "Simple (Security Requirements)", test: "tests/fixtures/full-io/2.0/simple/simple-security.json", extraProperties: 0 },
{ name: "Paths (Empty)", test: "tests/fixtures/full-io/2.0/paths/paths-empty.json", extraProperties: 0 },
{ name: "Paths (GET)", test: "tests/fixtures/full-io/2.0/paths/paths-get.json", extraProperties: 0 },
{ name: "Paths (GET + Params)", test: "tests/fixtures/full-io/2.0/paths/paths-get-with-params.json", extraProperties: 0 },
{ name: "Paths (GET + Tags)", test: "tests/fixtures/full-io/2.0/paths/paths-get-with-tags.json", extraProperties: 0 },
{ name: "Paths (Path + Params)", test: "tests/fixtures/full-io/2.0/paths/paths-path-with-params.json", extraProperties: 0 },
{ name: "Paths (All Ops)", test: "tests/fixtures/full-io/2.0/paths/paths-all-operations.json", extraProperties: 0 },
{ name: "Paths (Ref)", test: "tests/fixtures/full-io/2.0/paths/paths-ref.json", extraProperties: 0 },
{ name: "Paths (External Docs)", test: "tests/fixtures/full-io/2.0/paths/paths-externalDocs.json", extraProperties: 0 },
{ name: "Paths (Security)", test: "tests/fixtures/full-io/2.0/paths/paths-security.json", extraProperties: 0 },
{ name: "Paths (Default Response)", test: "tests/fixtures/full-io/2.0/paths/paths-default-response.json", extraProperties: 0 },
{ name: "Paths (Responses)", test: "tests/fixtures/full-io/2.0/paths/paths-responses.json", extraProperties: 0 },
{ name: "Paths (Response w/ Headers)", test: "tests/fixtures/full-io/2.0/paths/paths-response-with-headers.json", extraProperties: 0 },
{ name: "Paths (Response w/ Examples)", test: "tests/fixtures/full-io/2.0/paths/paths-response-with-examples.json", extraProperties: 0 },
{ name: "Paths (Response w/ Schema)", test: "tests/fixtures/full-io/2.0/paths/paths-response-with-schema.json", extraProperties: 0 },
{ name: "Paths (With Extensions)", test: "tests/fixtures/full-io/2.0/paths/paths-with-extensions.json", extraProperties: 0 },
{ name: "Paths (Responses w/ Extensions)", test: "tests/fixtures/full-io/2.0/paths/paths-responses-with-extensions.json", extraProperties: 0 },
{ name: "Paths (Response w/ $ref)", test: "tests/fixtures/full-io/2.0/paths/paths-response-with-ref.json", extraProperties: 0 },
{ name: "Definitions (Primitives Sample)", test: "tests/fixtures/full-io/2.0/definitions/primitive.json", extraProperties: 0 },
{ name: "Definitions (Spec Example)", test: "tests/fixtures/full-io/2.0/definitions/spec-example-1.json", extraProperties: 0 },
{ name: "Definitions (Schema+XML)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-xml.json", extraProperties: 0 },
{ name: "Definitions (Schema+Meta Data)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-metaData.json", extraProperties: 0 },
{ name: "Definitions (Schema+'allOf')", test: "tests/fixtures/full-io/2.0/definitions/schema-with-allOf.json", extraProperties: 0 },
{ name: "Definitions (Schema+External Docs)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-externalDocs.json", extraProperties: 0 },
{ name: "Definitions (Schema+Props)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-additionalProperties.json", extraProperties: 0 },
{ name: "Definitions (Schema+Example)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-example.json", extraProperties: 0 },
{ name: "Definitions (Schema+Extension)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-extension.json", extraProperties: 0 },
{ name: "Definitions (Schema+Composition)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-composition.json", extraProperties: 0 },
{ name: "Definitions (Schema+Polymorphism)", test: "tests/fixtures/full-io/2.0/definitions/schema-with-polymorphism.json", extraProperties: 0 },
{ name: "Definitions (JSON Schema Basic)", test: "tests/fixtures/full-io/2.0/definitions/json-schema-basic.json", extraProperties: 0 },
{ name: "Definitions (JSON Schema Products)", test: "tests/fixtures/full-io/2.0/definitions/json-schema-products.json", extraProperties: 0 },
{ name: "Definitions (JSON Schema fstab)", test: "tests/fixtures/full-io/2.0/definitions/json-schema-fstab.json", extraProperties: 0 },
{ name: "Parameters (Spec Example)", test: "tests/fixtures/full-io/2.0/parameters/spec-example-1.json", extraProperties: 0 },
{ name: "Parameters (Array Params (items))", test: "tests/fixtures/full-io/2.0/parameters/array-param.json", extraProperties: 0 },
{ name: "Responses (Spec Example)", test: "tests/fixtures/full-io/2.0/responses/spec-example-1.json", extraProperties: 0 },
{ name: "Responses (Multiple Spec Examples)", test: "tests/fixtures/full-io/2.0/responses/response-spec-examples.json", extraProperties: 0 },
{ name: "Complete (Security Definitions)", test: "tests/fixtures/full-io/2.0/complete/complete-securityDefinitions.json", extraProperties: 0 },
{ name: "Complete (Tags)", test: "tests/fixtures/full-io/2.0/complete/complete-tags.json", extraProperties: 0 },
{ name: "Complete (Pet Store)", test: "tests/fixtures/full-io/2.0/complete/pet-store.json", extraProperties: 0 },
{ name: "Complete (api.meerkat)", test: "tests/fixtures/full-io/2.0/complete/api.meerkat.com.br.json", extraProperties: 0 },
{ name: "Complete (austin2015.apistrat)", test: "tests/fixtures/full-io/2.0/complete/austin2015.apistrat.com.json", extraProperties: 0 },
{ name: "Complete (developer.trade.gov)", test: "tests/fixtures/full-io/2.0/complete/developer.trade.gov.json", extraProperties: 0 },
{ name: "Complete (api.hairmare)", test: "tests/fixtures/full-io/2.0/complete/subnet.api.hairmare.ch.json", extraProperties: 0 },
{ name: "Complete (weatherbit.io)", test: "tests/fixtures/full-io/2.0/complete/www.weatherbit.io.json", extraProperties: 0 },
{ name: "Extra Properties", test: "tests/fixtures/full-io/2.0/extra-properties/extra-properties.json", extraProperties: 3 }
];
let library: OasLibraryUtils;
beforeEach(() => {
library = new OasLibraryUtils();
});
it("Invalid spec version", () => {
let json: any = readJSON('tests/fixtures/full-io/2.0/invalid-version.json');
expect(() => { library.createDocument(json); }).toThrowError("Unsupported OAS version: 1.1");
});
// it("Numeric spec version", () => {
// let json: any = readJSON('tests/fixtures/full-io/2.0/numeric-version.json');
// expect(() => { library.createDocument(json); }).toThrowError("Unsupported OAS version: 1.1");
// });
// All tests in the list above.
TESTS.forEach( spec => {
it(spec.name, () => {
if (spec.debug) {
console.info("******* Running test: " + spec.name);
}
let json: any = readJSON(spec.test);
let document: Oas20Document = library.createDocument(json) as Oas20Document;
// Assert the # of extra properties is right.
let viz: ExtraPropertyDetectionVisitor = new ExtraPropertyDetectionVisitor();
OasVisitorUtil.visitTree(document, viz);
expect(viz.numDetected).toEqual(spec.extraProperties);
let jsObj: any = library.writeNode(document);
if (spec.debug) {
console.info("------- INPUT --------\n " + JSON.stringify(json, null, 2) + "\n-------------------");
console.info("------- ACTUAL --------\n " + JSON.stringify(jsObj, null, 2) + "\n-------------------");
}
expect(jsObj).toEqual(json);
});
});
});
/**
* Full I/O Tests for Version 3.0 of the OpenAPI Specification.
*/
describe("Full I/O (3.0)", () => {
let TESTS: TestSpec[] = [
{ name: "Simple (Easy 3.0 spec)", test: "tests/fixtures/full-io/3.0/simple/simplest.json", extraProperties: 0 },
{ name: "Simple (Info)", test: "tests/fixtures/full-io/3.0/simple/simple-info.json", extraProperties: 0 },
{ name: "Simple (Info + extensions)", test: "tests/fixtures/full-io/3.0/simple/simple-info-extensions.json", extraProperties: 0 },
{ name: "Simple (Servers)", test: "tests/fixtures/full-io/3.0/simple/simple-servers.json", extraProperties: 0 },
{ name: "Simple (Security Requirements)", test: "tests/fixtures/full-io/3.0/simple/simple-security.json", extraProperties: 0 },
{ name: "Simple (Tags)", test: "tests/fixtures/full-io/3.0/simple/simple-tags.json", extraProperties: 0 },
{ name: "Simple (External Docs)", test: "tests/fixtures/full-io/3.0/simple/simple-externalDocs.json", extraProperties: 0 },
{ name: "Complete (Tags)", test: "tests/fixtures/full-io/3.0/complete/complete-tags.json", extraProperties: 0 },
{ name: "Paths (Empty)", test: "tests/fixtures/full-io/3.0/paths/paths-empty.json", extraProperties: 0 },
{ name: "Paths (GET)", test: "tests/fixtures/full-io/3.0/paths/paths-get.json", extraProperties: 0 },
{ name: "Paths ($ref)", test: "tests/fixtures/full-io/3.0/paths/paths-ref.json", extraProperties: 0 },
{ name: "Paths (Extensions)", test: "tests/fixtures/full-io/3.0/paths/paths-with-extensions.json", extraProperties: 0 },
{ name: "Paths (All Operations)", test: "tests/fixtures/full-io/3.0/paths/paths-all-operations.json", extraProperties: 0 },
{ name: "Paths (Servers)", test: "tests/fixtures/full-io/3.0/paths/paths-servers.json", extraProperties: 0 },
{ name: "Paths (Parameters)", test: "tests/fixtures/full-io/3.0/paths/paths-parameters.json", extraProperties: 0 },
{ name: "Paths (GET+Servers)", test: "tests/fixtures/full-io/3.0/paths/paths-get-servers.json", extraProperties: 0 },
{ name: "Paths (GET+Security)", test: "tests/fixtures/full-io/3.0/paths/paths-get-security.json", extraProperties: 0 },
{ name: "Paths (GET+AnonSecurity)", test: "tests/fixtures/full-io/3.0/paths/paths-get-security-anon.json", extraProperties: 0 },
{ name: "Paths (GET+Parameters)", test: "tests/fixtures/full-io/3.0/paths/paths-get-parameters.json", extraProperties: 0 },
{ name: "Paths (GET+RequestBody)", test: "tests/fixtures/full-io/3.0/paths/paths-get-requestBody.json", extraProperties: 0 },
{ name: "Paths (GET+RequestBody+Content)", test: "tests/fixtures/full-io/3.0/paths/paths-get-requestBody-content.json", extraProperties: 0 },
{ name: "Paths (GET+RequestBody+Examples)", test: "tests/fixtures/full-io/3.0/paths/paths-get-requestBody.json", extraProperties: 0 },
{ name: "Paths (GET+Responses)", test: "tests/fixtures/full-io/3.0/paths/paths-get-responses.json", extraProperties: 0 },
{ name: "Paths (GET+Response+Header)", test: "tests/fixtures/full-io/3.0/paths/paths-get-response-headers.json", extraProperties: 0 },
{ name: "Paths (GET+Response+Content)", test: "tests/fixtures/full-io/3.0/paths/paths-get-response-content.json", extraProperties: 0 },
{ name: "Paths (GET+Response+Links)", test: "tests/fixtures/full-io/3.0/paths/paths-get-response-links.json", extraProperties: 0 },
{ name: "Paths (GET+Callbacks)", test: "tests/fixtures/full-io/3.0/paths/paths-get-callbacks.json", extraProperties: 0 },
{ name: "Components (Empty)", test: "tests/fixtures/full-io/3.0/components/components-empty.json", extraProperties: 0 },
{ name: "Components (Schemas)", test: "tests/fixtures/full-io/3.0/components/components-schemas.json", extraProperties: 0 },
{ name: "Components (Schemas + extensions)", test: "tests/fixtures/full-io/3.0/components/components-schemas-extensions.json", extraProperties: 0 },
{ name: "Components (Responses)", test: "tests/fixtures/full-io/3.0/components/components-responses.json", extraProperties: 0 },
{ name: "Components (Parameters)", test: "tests/fixtures/full-io/3.0/components/components-parameters.json", extraProperties: 0 },
{ name: "Components (Examples)", test: "tests/fixtures/full-io/3.0/components/components-examples.json", extraProperties: 0 },
{ name: "Components (Request Bodies)", test: "tests/fixtures/full-io/3.0/components/components-requestBodies.json", extraProperties: 0 },
{ name: "Components (Headers)", test: "tests/fixtures/full-io/3.0/components/components-headers.json", extraProperties: 0 },
{ name: "Components (Security Schemes)", test: "tests/fixtures/full-io/3.0/components/components-securitySchemes.json", extraProperties: 0 },
{ name: "Components (Links)", test: "tests/fixtures/full-io/3.0/components/components-links.json", extraProperties: 0 },
{ name: "Components (Callbacks)", test: "tests/fixtures/full-io/3.0/components/components-callbacks.json", extraProperties: 0 },
{ name: "Components ($ref loops)", test: "tests/fixtures/full-io/3.0/components/components-ref-loops.json", extraProperties: 0 },
{ name: "Schemas (Discriminator)", test: "tests/fixtures/full-io/3.0/schemas/discriminator.json", extraProperties: 0 },
{ name: "Extra Properties", test: "tests/fixtures/full-io/3.0/extra-properties/extra-properties.json", extraProperties: 3 },
];
let library: OasLibraryUtils;
beforeEach(() => {
library = new OasLibraryUtils();
});
// All tests in the list above.
TESTS.forEach( spec => {
it(spec.name, () => {
if (spec.debug) {
console.info("******* Running test: " + spec.name);
}
let json: any = readJSON(spec.test);
let document: Oas30Document = library.createDocument(json) as Oas30Document;
// Assert the # of extra properties is right.
let viz: ExtraPropertyDetectionVisitor = new ExtraPropertyDetectionVisitor();
OasVisitorUtil.visitTree(document, viz);
expect(viz.numDetected).toEqual(spec.extraProperties);
let jsObj: any = library.writeNode(document);
if (spec.debug) {
console.info("------- INPUT --------\n " + JSON.stringify(json, null, 2) + "\n-------------------");
console.info("------- ACTUAL --------\n " + JSON.stringify(jsObj, null, 2) + "\n-------------------");
}
expect(jsObj).toEqual(json);
});
});
}); | the_stack |
import { FixNamingScheme } from './FixNamingScheme';
import { GeoMath } from './GeoMath';
import { HoldDetails, HoldTurnDirection } from './HoldDetails';
import { RawDataMapper } from './RawDataMapper';
/**
* Creates a collection of waypoints from a legs procedure.
*/
export class LegsProcedure {
/** The current index in the procedure. */
private _currentIndex = 0;
/** Whether or not there is a discontinuity pending to be mapped. */
private _isDiscontinuityPending = false;
/** A collection of the loaded facilities needed for this procedure. */
private _facilities = new Map<string, any>();
/** Whether or not the facilities have completed loading. */
private _facilitiesLoaded = false;
/**The collection of facility promises to await on first load. */
private _facilitiesToLoad = new Map();
/** Whether or not a non initial-fix procedure start has been added to the procedure. */
private _addedProcedureStart = false;
/** A normalization factor for calculating distances from triangular ratios. */
public static distanceNormalFactorNM = (21639 / 2) * Math.PI;
/** A collection of filtering rules for filtering ICAO data to pre-load for the procedure. */
private legFilteringRules: ((icao: string) => boolean)[] = [
icao => icao.trim() !== '', //Icao is not empty
icao => icao[0] !== 'R', //Icao is not runway icao, which is not searchable
icao => icao[0] !== 'A', //Icao is not airport icao, which can be skipped
icao => icao.substr(1, 2) !== ' ', //Icao is not missing a region code
icao => !this._facilitiesToLoad.has(icao) //Icao is not already being loaded
];
/**
* Creates an instance of a LegsProcedure.
* @param _legs The legs that are part of the procedure.
* @param _previousFix The previous fix before the procedure starts.
* @param _fixMinusTwo The fix before the previous fix.
* @param _instrument The instrument that is attached to the flight plan.
*/
constructor(private _legs: ProcedureLeg[], private _previousFix: WayPoint, private _fixMinusTwo: WayPoint, private _instrument: BaseInstrument) {
for (const leg of this._legs) {
if (this.isIcaoValid(leg.fixIcao)) {
this._facilitiesToLoad.set(leg.fixIcao, this._instrument.facilityLoader.getFacilityRaw(leg.fixIcao, 2000));
}
if (this.isIcaoValid(leg.originIcao)) {
this._facilitiesToLoad.set(leg.originIcao, this._instrument.facilityLoader.getFacilityRaw(leg.originIcao, 2000));
}
}
}
/**
* Checks whether or not there are any legs remaining in the procedure.
* @returns True if there is a next leg, false otherwise.
*/
public hasNext(): boolean {
return this._currentIndex < this._legs.length || this._isDiscontinuityPending;
}
/**
* Gets the next mapped leg from the procedure.
* @returns The mapped waypoint from the leg of the procedure.
*/
public async getNext(): Promise<WayPoint> {
let isLegMappable = false;
let mappedLeg: WayPoint;
if (!this._facilitiesLoaded) {
const facilityResults = await Promise.all(this._facilitiesToLoad.values());
for (const facility of facilityResults.filter(f => f !== undefined)) {
this._facilities.set(facility.icao, facility);
}
this._facilitiesLoaded = true;
}
while (!isLegMappable && this._currentIndex < this._legs.length) {
const currentLeg = this._legs[this._currentIndex];
isLegMappable = true;
//Some procedures don't start with 15 (initial fix) but instead start with a heading and distance from
//a fix: the procedure then starts with the fix exactly
if (this._currentIndex === 0 && currentLeg.type === 10 && !this._addedProcedureStart) {
mappedLeg = this.mapExactFix(currentLeg, this._previousFix);
this._addedProcedureStart = true;
}
else {
try {
switch (currentLeg.type) {
case 3:
mappedLeg = this.mapHeadingUntilDistanceFromOrigin(currentLeg, this._previousFix);
break;
case 4:
//Only map if the fix is itself not a runway fix to avoid double
//adding runway fixes
if (currentLeg.fixIcao === '' || currentLeg.fixIcao[0] !== 'R') {
mappedLeg = this.mapOriginRadialForDistance(currentLeg, this._previousFix);
}
else {
isLegMappable = false;
}
break;
case 5:
case 21:
mappedLeg = this.mapHeadingToInterceptNextLeg(currentLeg, this._previousFix, this._legs[this._currentIndex + 1]);
break;
case 6:
case 23:
mappedLeg = this.mapHeadingUntilRadialCrossing(currentLeg, this._previousFix);
break;
case 9:
case 10:
mappedLeg = this.mapBearingAndDistanceFromOrigin(currentLeg);
break;
case 11:
case 22:
mappedLeg = this.mapVectors(currentLeg, this._previousFix);
break;
case 14:
mappedLeg = this.mapHold(currentLeg, this._fixMinusTwo);
break;
case 15: {
if (currentLeg.fixIcao[0] !== 'A') {
const leg = this.mapExactFix(currentLeg, this._previousFix);
const prevLeg = this._previousFix;
//If a type 15 (initial fix) comes up in the middle of a plan
if (leg.icao === prevLeg.icao && leg.infos.coordinates.lat === prevLeg.infos.coordinates.lat
&& leg.infos.coordinates.long === prevLeg.infos.coordinates.long) {
isLegMappable = false;
}
else {
mappedLeg = leg;
}
}
//If type 15 is an airport itself, we don't need to map it (and the data is generally wrong)
else {
isLegMappable = false;
}
}
break;
case 7:
case 17:
case 18:
mappedLeg = this.mapExactFix(currentLeg, this._previousFix);
break;
case 2:
case 19:
mappedLeg = this.mapHeadingUntilAltitude(currentLeg, this._previousFix);
break;
default:
isLegMappable = false;
break;
}
}
catch (err) {
console.log(`LegsProcedure: Unexpected unmappable leg: ${err}`);
}
if (mappedLeg !== undefined) {
if (this.altitudeIsVerticalAngleInfo(currentLeg)) {
mappedLeg.legAltitudeDescription = 1;
mappedLeg.legAltitude1 = 100 * Math.round((currentLeg.altitude2 * 3.28084) / 100);
mappedLeg.legAltitude2 = 100 * Math.round((currentLeg.altitude1 * 3.28084) / 100);
} else {
mappedLeg.legAltitudeDescription = currentLeg.altDesc;
mappedLeg.legAltitude1 = 100 * Math.round((currentLeg.altitude1 * 3.28084) / 100);
mappedLeg.legAltitude2 = 100 * Math.round((currentLeg.altitude2 * 3.28084) / 100);
}
}
this._currentIndex++;
}
}
if (mappedLeg !== undefined) {
this._fixMinusTwo = this._previousFix;
this._previousFix = mappedLeg;
return mappedLeg;
}
else {
return undefined;
}
}
private altitudeIsVerticalAngleInfo(leg: ProcedureLeg): boolean {
return (leg.type === 4 || leg.type === 18)
&& (leg.altDesc === 1 || leg.altDesc === 2)
&& (leg.altitude1 > 0 && leg.altitude2 > 0);
}
/**
* Maps a heading until distance from origin leg.
* @param leg The procedure leg to map.
* @param prevLeg The previously mapped waypoint in the procedure.
* @returns The mapped leg.
*/
public mapHeadingUntilDistanceFromOrigin(leg: ProcedureLeg, prevLeg: WayPoint): WayPoint {
const origin = this._facilities.get(leg.originIcao);
const originIdent = origin.icao.substring(7, 12).trim();
const bearingToOrigin = Avionics.Utils.computeGreatCircleHeading(prevLeg.infos.coordinates, new LatLongAlt(origin.lat, origin.lon));
const distanceToOrigin = Avionics.Utils.computeGreatCircleDistance(prevLeg.infos.coordinates, new LatLongAlt(origin.lat, origin.lon)) / LegsProcedure.distanceNormalFactorNM;
const deltaAngle = this.deltaAngleRadians(bearingToOrigin, leg.course);
const targetDistance = (leg.distance / 1852) / LegsProcedure.distanceNormalFactorNM;
const distanceAngle = Math.asin((Math.sin(distanceToOrigin) * Math.sin(deltaAngle)) / Math.sin(targetDistance));
const inverseDistanceAngle = Math.PI - distanceAngle;
const legDistance1 = 2 * Math.atan(Math.tan(0.5 * (targetDistance - distanceToOrigin)) * (Math.sin(0.5 * (deltaAngle + distanceAngle))
/ Math.sin(0.5 * (deltaAngle - distanceAngle))));
const legDistance2 = 2 * Math.atan(Math.tan(0.5 * (targetDistance - distanceToOrigin)) * (Math.sin(0.5 * (deltaAngle + inverseDistanceAngle))
/ Math.sin(0.5 * (deltaAngle - inverseDistanceAngle))));
const legDistance = targetDistance > distanceToOrigin ? legDistance1 : Math.min(legDistance1, legDistance2);
const course = leg.course + GeoMath.getMagvar(prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
const coordinates = Avionics.Utils.bearingDistanceToCoordinates(course, legDistance * LegsProcedure.distanceNormalFactorNM, prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
return this.buildWaypoint(`${originIdent}${Math.trunc(legDistance * LegsProcedure.distanceNormalFactorNM)}`, coordinates);
}
/**
* Maps a bearing/distance fix in the procedure.
* @param leg The procedure leg to map.
* @returns The mapped leg.
*/
public mapBearingAndDistanceFromOrigin(leg: ProcedureLeg): WayPoint {
const origin = this._facilities.get(leg.originIcao);
const originIdent = origin.icao.substring(7, 12).trim();
const course = leg.course + GeoMath.getMagvar(origin.lat, origin.lon);
const coordinates = Avionics.Utils.bearingDistanceToCoordinates(leg.course, leg.distance / 1852, origin.lat, origin.lon);
return this.buildWaypoint(`${originIdent}${Math.trunc(leg.distance / 1852)}`, coordinates);
}
/**
* Maps a radial on the origin for a specified distance leg in the procedure.
* @param leg The procedure leg to map.
* @param prevLeg The previously mapped leg.
* @returns The mapped leg.
*/
public mapOriginRadialForDistance(leg: ProcedureLeg, prevLeg: WayPoint): WayPoint {
if (leg.fixIcao.trim() !== '') {
return this.mapExactFix(leg, prevLeg);
}
else {
const origin = this._facilities.get(leg.originIcao);
const originIdent = origin.icao.substring(7, 12).trim();
const course = leg.course + GeoMath.getMagvar(prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
const coordinates = Avionics.Utils.bearingDistanceToCoordinates(course, leg.distance / 1852, prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
const distanceFromOrigin = Avionics.Utils.computeGreatCircleDistance(new LatLongAlt(origin.lat, origin.lon), coordinates);
return this.buildWaypoint(`${originIdent}${Math.trunc(distanceFromOrigin / 1852)}`, coordinates);
}
}
/**
* Maps a heading turn to intercept the next leg in the procedure.
* @param leg The procedure leg to map.
* @param prevLeg The previously mapped leg.
* @param nextLeg The next leg in the procedure to intercept.
* @returns The mapped leg.
*/
public mapHeadingToInterceptNextLeg(leg: ProcedureLeg, prevLeg: WayPoint, nextLeg: ProcedureLeg): WayPoint {
let referenceCoordinates;
let courseToIntercept;
let referenceFix;
switch (nextLeg.type) {
case 4:
case 7:
case 15:
case 17:
case 18:
referenceFix = this._facilities.get(nextLeg.fixIcao);
referenceCoordinates = new LatLongAlt(referenceFix.lat, referenceFix.lon);
courseToIntercept = nextLeg.course - 180;
if (courseToIntercept < 0) {
courseToIntercept += 360;
}
break;
case 9:
referenceFix = this._facilities.get(nextLeg.originIcao);
referenceCoordinates = new LatLongAlt(referenceFix.lat, referenceFix.lon);
courseToIntercept = nextLeg.course;
break;
}
if (referenceCoordinates !== undefined && courseToIntercept !== undefined) {
const distanceFromOrigin = Avionics.Utils.computeGreatCircleDistance(prevLeg.infos.coordinates, referenceCoordinates);
const bearingToOrigin = Avionics.Utils.computeGreatCircleHeading(prevLeg.infos.coordinates, referenceCoordinates);
const bearingFromOrigin = Avionics.Utils.computeGreatCircleHeading(referenceCoordinates, prevLeg.infos.coordinates);
const ang1 = this.deltaAngleRadians(bearingToOrigin, leg.course);
const ang2 = this.deltaAngleRadians(bearingFromOrigin, courseToIntercept);
const ang3 = Math.acos(Math.sin(ang1) * Math.sin(ang2) * Math.cos(distanceFromOrigin / LegsProcedure.distanceNormalFactorNM) - Math.cos(ang1) * Math.cos(ang2));
const legDistance = Math.acos((Math.cos(ang1) + Math.cos(ang2) * Math.cos(ang3)) / (Math.sin(ang2) * Math.sin(ang3))) * LegsProcedure.distanceNormalFactorNM;
const course = leg.course + GeoMath.getMagvar(prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
const coordinates = Avionics.Utils.bearingDistanceToCoordinates(course, legDistance, prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
return this.buildWaypoint(FixNamingScheme.courseToIntercept(course), coordinates);
}
}
/**
* Maps flying a heading until crossing a radial of a reference fix.
* @param leg The procedure leg to map.
* @param prevLeg The previously mapped leg.
* @returns The mapped leg.
*/
public mapHeadingUntilRadialCrossing(leg: ProcedureLeg, prevLeg: WayPoint): WayPoint {
const origin = this._facilities.get(leg.originIcao);
const originCoordinates = new LatLongAlt(origin.lat, origin.lon);
const originToCoordinates = Avionics.Utils.computeGreatCircleHeading(originCoordinates, prevLeg.infos.coordinates);
const coordinatesToOrigin = Avionics.Utils.computeGreatCircleHeading(prevLeg.infos.coordinates, new LatLongAlt(origin.lat, origin.lon));
const distanceToOrigin = Avionics.Utils.computeGreatCircleDistance(prevLeg.infos.coordinates, originCoordinates) / LegsProcedure.distanceNormalFactorNM;
const alpha = this.deltaAngleRadians(coordinatesToOrigin, leg.course);
const beta = this.deltaAngleRadians(originToCoordinates, leg.theta);
const gamma = Math.acos(Math.sin(alpha) * Math.sin(beta) * Math.cos(distanceToOrigin) - Math.cos(alpha) * Math.cos(beta));
const legDistance = Math.acos((Math.cos(beta) + Math.cos(alpha) * Math.cos(gamma)) / (Math.sin(alpha) * Math.sin(gamma)));
const course = leg.course + GeoMath.getMagvar(prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
const coordinates = Avionics.Utils.bearingDistanceToCoordinates(course, legDistance * LegsProcedure.distanceNormalFactorNM, prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
return this.buildWaypoint(`${this.getIdent(origin.icao)}${leg.theta}`, coordinates);
}
/**
* Maps flying a heading until a proscribed altitude.
* @param leg The procedure leg to map.
* @param prevLeg The previous leg in the procedure.
* @returns The mapped leg.
*/
public mapHeadingUntilAltitude(leg: ProcedureLeg, prevLeg: WayPoint): WayPoint {
const altitudeFeet = (leg.altitude1 * 3.2808399);
const distanceInNM = altitudeFeet / 750.0;
const course = leg.course + GeoMath.getMagvar(prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
const coordinates = GeoMath.relativeBearingDistanceToCoords(course, distanceInNM, prevLeg.infos.coordinates);
return this.buildWaypoint(`(${Math.trunc(altitudeFeet)})`, coordinates, prevLeg.infos.magneticVariation);
}
/**
* Maps a vectors instruction.
* @param leg The procedure leg to map.
* @param prevLeg The previous leg in the procedure.
* @returns The mapped leg.
*/
public mapVectors(leg: ProcedureLeg, prevLeg: WayPoint): WayPoint {
const course = leg.course + GeoMath.getMagvar(prevLeg.infos.coordinates.lat, prevLeg.infos.coordinates.long);
const coordinates = GeoMath.relativeBearingDistanceToCoords(course, 5, prevLeg.infos.coordinates);
const waypoint = this.buildWaypoint('(VECT)', coordinates);
waypoint.isVectors = true;
waypoint.endsInDiscontinuity = true;
return waypoint;
}
/**
* Maps an exact fix leg in the procedure.
* @param leg The procedure leg to map.
* @param prevLeg The previous mapped leg in the procedure.
* @returns The mapped leg.
*/
public mapExactFix(leg: ProcedureLeg, prevLeg: WayPoint): WayPoint {
const facility = this._facilities.get(leg.fixIcao);
if (facility) {
return RawDataMapper.toWaypoint(facility, this._instrument);
}
else {
const origin = this._facilities.get(leg.originIcao);
const originIdent = origin.icao.substring(7, 12).trim();
const coordinates = Avionics.Utils.bearingDistanceToCoordinates(leg.theta, leg.rho / 1852, origin.lat, origin.lon);
return this.buildWaypoint(`${originIdent}${Math.trunc(leg.rho / 1852)}`, coordinates);
}
}
/**
* Maps a hold leg in the procedure.
* @param leg The procedure leg to map.
* @param fixMinusTwo The fix that is two previous to this leg.
* @returns The mapped leg.
*/
public mapHold(leg: ProcedureLeg, fixMinusTwo: WayPoint): WayPoint {
const facility = this._facilities.get(leg.fixIcao);
const waypoint = RawDataMapper.toWaypoint(facility, this._instrument);
waypoint.hasHold = true;
const course = Avionics.Utils.computeGreatCircleHeading(fixMinusTwo.infos.coordinates, waypoint.infos.coordinates);
const holdDetails = HoldDetails.createDefault(leg.course, course);
holdDetails.turnDirection = leg.turnDirection === 1 ? HoldTurnDirection.Left : HoldTurnDirection.Right;
holdDetails.entryType = HoldDetails.calculateEntryType(leg.course, course, holdDetails.turnDirection);
waypoint.holdDetails = holdDetails;
return waypoint;
}
/**
* Gets the difference between two headings in zero north normalized radians.
* @param a The degrees of heading a.
* @param b The degrees of heading b.
* @returns The difference between the two headings in zero north normalized radians.
*/
private deltaAngleRadians(a: number, b: number): number {
return Math.abs((Avionics.Utils.fmod((a - b) + 180, 360) - 180) * Avionics.Utils.DEG2RAD);
}
/**
* Gets an ident from an ICAO.
* @param icao The icao to pull the ident from.
* @returns The parsed ident.
*/
private getIdent(icao: string): string {
return icao.substring(7, 12).trim();
}
/**
* Checks if an ICAO is valid to load.
* @param icao The icao to check.
* @returns Whether or not the ICAO is valid.
*/
private isIcaoValid(icao): boolean {
for (const rule of this.legFilteringRules) {
if (!rule(icao)) {
return false;
}
}
return true;
}
/**
* Builds a WayPoint from basic data.
* @param ident The ident of the waypoint.
* @param coordinates The coordinates of the waypoint.
* @param magneticVariation The magnetic variation of the waypoint, if any.
* @returns The built waypoint.
*/
public buildWaypoint(ident: string, coordinates: LatLongAlt, magneticVariation?: number): WayPoint {
const waypoint = new WayPoint(this._instrument);
waypoint.type = 'W';
waypoint.infos = new IntersectionInfo(this._instrument);
waypoint.infos.coordinates = coordinates;
waypoint.infos.magneticVariation = magneticVariation;
waypoint.ident = ident;
waypoint.infos.ident = ident;
return waypoint;
}
} | the_stack |
import {
expect
} from 'chai';
import {
each, every
} from '@phosphor/algorithm';
import {
Message, MessageLoop
} from '@phosphor/messaging';
import {
BoxLayout, Widget
} from '@phosphor/widgets';
class LogBoxLayout extends BoxLayout {
methods: string[] = [];
protected init(): void {
super.init();
this.methods.push('init');
}
protected attachWidget(index: number, widget: Widget): void {
super.attachWidget(index, widget);
this.methods.push('attachWidget');
}
protected moveWidget(fromIndex: number, toIndex: number, widget: Widget): void {
super.moveWidget(fromIndex, toIndex, widget);
this.methods.push('moveWidget');
}
protected detachWidget(index: number, widget: Widget): void {
super.detachWidget(index, widget);
this.methods.push('detachWidget');
}
protected onAfterShow(msg: Message): void {
super.onAfterShow(msg);
this.methods.push('onAfterShow');
}
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.methods.push('onAfterAttach');
}
protected onChildShown(msg: Widget.ChildMessage): void {
super.onChildShown(msg);
this.methods.push('onChildShown');
}
protected onChildHidden(msg: Widget.ChildMessage): void {
super.onChildHidden(msg);
this.methods.push('onChildHidden');
}
protected onResize(msg: Widget.ResizeMessage): void {
super.onResize(msg);
this.methods.push('onResize');
}
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.methods.push('onUpdateRequest');
}
protected onFitRequest(msg: Message): void {
super.onFitRequest(msg);
this.methods.push('onFitRequest');
}
}
class LogWidget extends Widget {
methods: string[] = [];
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.methods.push('onAfterAttach');
}
protected onBeforeDetach(msg: Message): void {
super.onBeforeDetach(msg);
this.methods.push('onBeforeDetach');
}
protected onAfterShow(msg: Message): void {
super.onAfterShow(msg);
this.methods.push('onAfterShow');
}
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.methods.push('onUpdateRequest');
}
}
describe('@phosphor/widgets', () => {
describe('BoxLayout', () => {
describe('constructor()', () => {
it('should take no arguments', () => {
let layout = new BoxLayout();
expect(layout).to.be.an.instanceof(BoxLayout);
});
it('should accept options', () => {
let layout = new BoxLayout({ direction: 'bottom-to-top', spacing: 10 });
expect(layout.direction).to.equal('bottom-to-top');
expect(layout.spacing).to.equal(10);
});
});
describe('#direction', () => {
it('should default to `"top-to-bottom"`', () => {
let layout = new BoxLayout();
expect(layout.direction).to.equal('top-to-bottom');
});
it('should set the layout direction for the box layout', () => {
let layout = new BoxLayout();
layout.direction = 'left-to-right';
expect(layout.direction).to.equal('left-to-right');
});
it('should set the direction attribute of the parent widget', () => {
let parent = new Widget();
let layout = new BoxLayout();
parent.layout = layout;
layout.direction = 'top-to-bottom';
expect(parent.node.getAttribute('data-direction')).to.equal('top-to-bottom');
layout.direction = 'bottom-to-top';
expect(parent.node.getAttribute('data-direction')).to.equal('bottom-to-top');
layout.direction = 'left-to-right';
expect(parent.node.getAttribute('data-direction')).to.equal('left-to-right');
layout.direction = 'right-to-left';
expect(parent.node.getAttribute('data-direction')).to.equal('right-to-left');
});
it('should post a fit request to the parent widget', (done) => {
let parent = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
layout.direction = 'right-to-left';
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
done();
});
});
it('should be a no-op if the value does not change', (done) => {
let parent = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
layout.direction = 'top-to-bottom';
requestAnimationFrame(() => {
expect(layout.methods).to.not.contain('onFitRequest');
done();
});
});
});
describe('#spacing', () => {
it('should default to `4`', () => {
let layout = new BoxLayout();
expect(layout.spacing).to.equal(4);
});
it('should set the inter-element spacing for the box panel', () => {
let layout = new BoxLayout();
layout.spacing = 8;
expect(layout.spacing).to.equal(8);
});
it('should post a fit request to the parent widget', (done) => {
let parent = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
layout.spacing = 8;
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
done();
});
});
it('should be a no-op if the value does not change', (done) => {
let parent = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
layout.spacing = 4;
requestAnimationFrame(() => {
expect(layout.methods).to.not.contain('onFitRequest');
done();
});
});
});
describe('#init()', () => {
it('should set the direction attribute on the parent widget', () => {
let parent = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
expect(parent.node.getAttribute('data-direction')).to.equal('top-to-bottom');
expect(layout.methods).to.contain('init');
parent.dispose();
});
it('should attach the child widgets', () => {
let parent = new Widget();
let layout = new LogBoxLayout();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { layout.addWidget(w); });
parent.layout = layout;
expect(every(widgets, w => w.parent === parent));
expect(layout.methods).to.contain('attachWidget');
parent.dispose();
});
});
describe('#attachWidget()', () => {
it("should attach a widget to the parent's DOM node", () => {
let panel = new Widget();
let layout = new LogBoxLayout();
let widget = new Widget();
panel.layout = layout;
layout.addWidget(widget);
layout.addWidget(widget);
expect(layout.methods).to.contain('attachWidget');
expect(panel.node.contains(widget.node)).to.equal(true);
panel.dispose();
});
it("should send an `'after-attach'` message if the parent is attached", () => {
let panel = new Widget();
let layout = new LogBoxLayout();
let widget = new LogWidget();
panel.layout = layout;
Widget.attach(panel, document.body);
layout.addWidget(widget);
expect(layout.methods).to.contain('attachWidget');
expect(widget.methods).to.contain('onAfterAttach');
panel.dispose();
});
it('should post a layout request for the parent widget', (done) => {
let panel = new Widget();
let layout = new LogBoxLayout();
panel.layout = layout;
layout.addWidget(new Widget());
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
panel.dispose();
done();
});
});
});
describe('#moveWidget()', () => {
it('should post an update request for the parent widget', (done) => {
let panel = new Widget();
let layout = new LogBoxLayout();
panel.layout = layout;
layout.addWidget(new Widget());
let widget = new Widget();
layout.addWidget(widget);
layout.insertWidget(0, widget);
expect(layout.methods).to.contain('moveWidget');
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onUpdateRequest');
panel.dispose();
done();
});
});
});
describe('#detachWidget()', () => {
it("should detach a widget from the parent's DOM node", () => {
let panel = new Widget();
let layout = new LogBoxLayout();
let widget = new Widget();
panel.layout = layout;
layout.addWidget(widget);
layout.removeWidget(widget);
expect(layout.methods).to.contain('detachWidget');
expect(panel.node.contains(widget.node)).to.equal(false);
panel.dispose();
});
it("should send a `'before-detach'` message if the parent is attached", () => {
let panel = new Widget();
let layout = new LogBoxLayout();
panel.layout = layout;
let widget = new LogWidget();
Widget.attach(panel, document.body);
layout.addWidget(widget);
layout.removeWidget(widget);
expect(widget.methods).to.contain('onBeforeDetach');
panel.dispose();
});
it('should post a layout request for the parent widget', (done) => {
let panel = new Widget();
let layout = new LogBoxLayout();
let widget = new Widget();
panel.layout = layout;
layout.addWidget(widget);
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
layout.removeWidget(widget);
layout.methods = [];
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
panel.dispose();
done();
});
});
});
});
describe('#onAfterShow()', () => {
it('should post an update request to the parent', (done) => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
Widget.attach(parent, document.body);
parent.hide();
parent.show();
expect(parent.methods).to.contain('onAfterShow');
expect(layout.methods).to.contain('onAfterShow');
requestAnimationFrame(() => {
expect(parent.methods).to.contain('onUpdateRequest');
parent.dispose();
done();
});
});
it('should send an `after-show` message to non-hidden child widgets', () => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
let widgets = [new LogWidget(), new LogWidget(), new LogWidget()];
let hiddenWidgets = [new LogWidget(), new LogWidget()];
each(widgets, w => { layout.addWidget(w); });
each(hiddenWidgets, w => { layout.addWidget(w); });
each(hiddenWidgets, w => { w.hide(); });
Widget.attach(parent, document.body);
parent.layout = layout;
parent.hide();
parent.show();
expect(every(widgets, w => w.methods.indexOf('after-show') !== -1));
expect(every(hiddenWidgets, w => w.methods.indexOf('after-show') === -1));
expect(parent.methods).to.contain('onAfterShow');
expect(layout.methods).to.contain('onAfterShow');
parent.dispose();
});
});
describe('#onAfterAttach()', () => {
it('should post a fit request to the parent', (done) => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
Widget.attach(parent, document.body);
expect(parent.methods).to.contain('onAfterAttach');
expect(layout.methods).to.contain('onAfterAttach');
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
parent.dispose();
done();
});
});
it('should send `after-attach` to all child widgets', () => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
let widgets = [new LogWidget(), new LogWidget(), new LogWidget()];
each(widgets, w => { layout.addWidget(w); });
Widget.attach(parent, document.body);
expect(parent.methods).to.contain('onAfterAttach');
expect(layout.methods).to.contain('onAfterAttach');
expect(every(widgets, w => w.methods.indexOf('onAfterAttach') !== -1));
parent.dispose();
});
});
describe('#onChildShown()', () => {
it('should post or send a fit request to the parent', (done) => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
let widgets = [new LogWidget(), new LogWidget(), new LogWidget()];
widgets[0].hide();
each(widgets, w => { layout.addWidget(w); });
Widget.attach(parent, document.body);
widgets[0].show();
expect(layout.methods).to.contain('onChildShown');
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
parent.dispose();
done();
});
});
});
describe('#onChildHidden()', () => {
it('should post a fit request to the parent', (done) => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
let widgets = [new LogWidget(), new LogWidget(), new LogWidget()];
each(widgets, w => { layout.addWidget(w); });
Widget.attach(parent, document.body);
widgets[0].hide();
expect(layout.methods).to.contain('onChildHidden');
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
parent.dispose();
done();
});
});
});
describe('#onResize()', () => {
it('should be called when a resize event is sent to the parent', () => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
let widgets = [new LogWidget(), new LogWidget(), new LogWidget()];
each(widgets, w => { layout.addWidget(w); });
Widget.attach(parent, document.body);
MessageLoop.sendMessage(parent, Widget.ResizeMessage.UnknownSize);
expect(layout.methods).to.contain('onResize');
parent.dispose();
});
it('should be a no-op if the parent is hidden', () => {
let parent = new LogWidget();
let layout = new LogBoxLayout();
parent.layout = layout;
Widget.attach(parent, document.body);
parent.hide();
MessageLoop.sendMessage(parent, Widget.ResizeMessage.UnknownSize);
expect(layout.methods).to.contain('onResize');
parent.dispose();
});
});
describe('#onUpdateRequest()', () => {
it('should be called when the parent is updated', () => {
let parent = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.UpdateRequest);
expect(layout.methods).to.contain('onUpdateRequest');
});
});
describe('#onFitRequest()', () => {
it('should be called when the parent fit is requested', () => {
let parent = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.FitRequest);
expect(layout.methods).to.contain('onFitRequest');
});
});
describe('.getStretch()', () => {
it('should get the box panel stretch factor for the given widget', () => {
let widget = new Widget();
expect(BoxLayout.getStretch(widget)).to.equal(0);
});
});
describe('.setStretch()', () => {
it('should set the box panel stretch factor for the given widget', () => {
let widget = new Widget();
BoxLayout.setStretch(widget, 8);
expect(BoxLayout.getStretch(widget)).to.equal(8);
});
it("should post a fit request to the widget's parent", (done) => {
let parent = new Widget();
let widget = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
layout.addWidget(widget);
BoxLayout.setStretch(widget, 8);
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
done();
});
});
});
describe('.getSizeBasis()', () => {
it('should get the box panel size basis for the given widget', () => {
let widget = new Widget();
expect(BoxLayout.getSizeBasis(widget)).to.equal(0);
});
});
describe('.setSizeBasis()', () => {
it('should set the box panel size basis for the given widget', () => {
let widget = new Widget();
BoxLayout.setSizeBasis(widget, 8);
expect(BoxLayout.getSizeBasis(widget)).to.equal(8);
});
it("should post a fit request to the widget's parent", (done) => {
let parent = new Widget();
let widget = new Widget();
let layout = new LogBoxLayout();
parent.layout = layout;
layout.addWidget(widget);
BoxLayout.setSizeBasis(widget, 8);
requestAnimationFrame(() => {
expect(layout.methods).to.contain('onFitRequest');
done();
});
});
});
});
}); | the_stack |
import { ScaleBand, ScaleLinear, ScaleTime } from 'd3-scale'
import { CurveFactory, stackOffsetNone } from 'd3-shape'
import React, { CSSProperties, RefObject } from 'react'
import * as TSTB from 'ts-toolbelt'
import { TooltipRendererProps } from './components/TooltipRenderer'
export type ChartOptions<TDatum> = {
data: UserSerie<TDatum>[]
primaryAxis: AxisOptions<TDatum>
secondaryAxes: AxisOptions<TDatum>[]
padding?:
| number
| {
left?: number
right?: number
top?: number
bottom?: number
}
getSeriesStyle?: (
series: Series<TDatum>,
status: SeriesFocusStatus
) => SeriesStyles
getDatumStyle?: (
datum: Datum<TDatum>,
status: DatumFocusStatus
) => DatumStyles
getSeriesOrder?: (series: Series<TDatum>[]) => Series<TDatum>[]
interactionMode?: InteractionMode
showVoronoi?: boolean
showDebugAxes?: boolean
memoizeSeries?: boolean
defaultColors?: string[]
initialWidth?: number
initialHeight?: number
brush?: {
style?: CSSProperties
onSelect?: (selection: {
pointer: Pointer
start: unknown
end: unknown
}) => void
}
onFocusDatum?: (datum: Datum<TDatum> | null) => void
onClickDatum?: (
datum: Datum<TDatum> | null,
event: React.MouseEvent<SVGSVGElement, MouseEvent>
) => void
dark?: boolean
renderSVG?: () => React.ReactNode
primaryCursor?: boolean | CursorOptions
secondaryCursor?: boolean | CursorOptions
tooltip?: boolean | TooltipOptions<TDatum>
useIntersectionObserver?: boolean
intersectionObserverRootMargin?:
| `${number}px`
| `${number}px ${number}px`
| `${number}px ${number}px ${number}px ${number}px`
}
export type RequiredChartOptions<TDatum> = TSTB.Object.Required<
ChartOptions<TDatum>,
| 'getSeriesOrder'
| 'interactionMode'
| 'tooltipMode'
| 'showVoronoi'
| 'defaultColors'
| 'initialWidth'
| 'initialHeight'
| 'useIntersectionObserver'
| 'intersectionObserverThreshold'
| 'primaryCursor'
| 'secondaryCursor'
| 'padding'
>
export type ResolvedChartOptions<TDatum> = Omit<
RequiredChartOptions<TDatum>,
'tooltip'
> & {
tooltip: ResolvedTooltipOptions<TDatum>
}
export type ChartContextValue<TDatum> = {
getOptions: () => ResolvedChartOptions<TDatum>
gridDimensions: GridDimensions
primaryAxis: Axis<TDatum>
secondaryAxes: Axis<TDatum>[]
series: Series<TDatum>[]
orderedSeries: Series<TDatum>[]
datumsByInteractionGroup: Map<any, Datum<TDatum>[]>
datumsByTooltipGroup: Map<any, Datum<TDatum>[]>
width: number
height: number
svgRef: RefObject<SVGSVGElement>
getSeriesStatusStyle: (
series: Series<TDatum>,
focusedDatum: Datum<TDatum> | null
) => SeriesStyles
getDatumStatusStyle: (
datum: Datum<TDatum>,
focusedDatum: Datum<TDatum> | null
) => DatumStyles
axisDimensionsState: [
AxisDimensions,
React.Dispatch<React.SetStateAction<AxisDimensions>>
]
focusedDatumState: [
Datum<TDatum> | null,
React.Dispatch<React.SetStateAction<Datum<TDatum> | null>>
]
isInteractingState: [boolean, React.Dispatch<React.SetStateAction<boolean>>]
}
export type TooltipOptions<TDatum> = {
align?: AlignMode
alignPriority?: AlignPosition[]
padding?: number
arrowPadding?: number
groupingMode?: TooltipGroupingMode
show?: boolean
// anchor?: AnchorMode
// arrowPosition?: AlignPosition
render?: (props: TooltipRendererProps<TDatum>) => React.ReactNode
// formatSecondary?: (d: unknown) => string | number
// formatTertiary?: (d: unknown) => string | number
invert?: boolean
}
export type ResolvedTooltipOptions<TDatum> = TSTB.Object.Required<
TooltipOptions<TDatum>,
'align' | 'alignPriority' | 'padding' | 'arrowPadding' | 'anchor' | 'render'
>
export type SeriesStyles = CSSProperties & {
area?: CSSProperties
line?: CSSProperties
circle?: CSSProperties
rectangle?: CSSProperties
}
export type DatumStyles = CSSProperties & {
area?: CSSProperties
line?: CSSProperties
circle?: CSSProperties
rectangle?: CSSProperties
}
export type Position = 'top' | 'right' | 'bottom' | 'left'
export type InteractionMode = 'closest' | 'primary'
export type TooltipGroupingMode = 'single' | 'primary' | 'secondary' | 'series'
export type AlignMode =
| 'auto'
| 'right'
| 'topRight'
| 'bottomRight'
| 'left'
| 'topLeft'
| 'bottomLeft'
| 'top'
| 'bottom'
| 'center'
export type AlignPosition =
| 'right'
| 'topRight'
| 'bottomRight'
| 'left'
| 'topLeft'
| 'bottomLeft'
| 'top'
| 'bottom'
export type AxisType = 'ordinal' | 'time' | 'localTime' | 'linear' | 'log'
export type AnchorMode =
| 'pointer'
| 'closest'
| 'center'
| 'top'
| 'bottom'
| 'left'
| 'right'
| 'gridTop'
| 'gridBottom'
| 'gridLeft'
| 'gridRight'
| 'gridCenter'
export type Side = 'left' | 'right' | 'top' | 'bottom'
type PointerBase = {
x: number
y: number
svgHovered: boolean
}
export type PointerUnpressed = PointerBase & {
dragging: false
}
export type PointerPressed = PointerBase & {
dragging: true
startX: number
startY: number
}
export type Pointer = PointerUnpressed | PointerPressed
export type ChartOffset = {
left: number
top: number
width: number
height: number
}
export type AxisDimension = {
paddingLeft: number
paddingRight: number
paddingTop: number
paddingBottom: number
width: number
height: number
}
export type AxisDimensions = {
left: Record<string, AxisDimension>
right: Record<string, AxisDimension>
top: Record<string, AxisDimension>
bottom: Record<string, AxisDimension>
}
export type AxisOptionsBase = {
primaryAxisId?: string
elementType?: 'line' | 'area' | 'bar' | 'bubble'
showDatumElements?: boolean | 'onFocus'
curve?: CurveFactory
invert?: boolean
position?: Position
minTickPaddingForRotation?: number
tickLabelRotationDeg?: number
tickCount?: number
shouldNice?: boolean
innerBandPadding?: number
outerBandPadding?: number
innerSeriesBandPadding?: number
outerSeriesBandPadding?: number
minBandSize?: number
maxBandSize?: number
minDomainLength?: number
showGrid?: boolean
show?: boolean
stacked?: boolean
stackOffset?: typeof stackOffsetNone
id?: string | number
styles?: CSSProperties & {
line?: CSSProperties
tick?: CSSProperties
}
}
export type AxisTimeOptions<TDatum> = AxisOptionsBase & {
scaleType?: 'time' | 'localTime'
getValue: (datum: TDatum) => ChartValue<Date>
min?: Date
max?: Date
hardMin?: Date
hardMax?: Date
padBandRange?: boolean
formatters?: {
scale?: (
value: Date,
formatters: AxisTimeOptions<TDatum>['formatters']
) => string
tooltip?: (
value: Date,
formatters: AxisTimeOptions<TDatum>['formatters']
) => React.ReactNode
cursor?: (
value: Date,
formatters: AxisTimeOptions<TDatum>['formatters']
) => React.ReactNode
}
}
export type AxisLinearOptions<TDatum> = AxisOptionsBase & {
scaleType?: 'linear' | 'log'
getValue: (datum: TDatum) => ChartValue<number>
min?: number
max?: number
hardMin?: number
hardMax?: number
// base?: number
formatters?: {
scale?: (
value: number,
formatters: AxisLinearOptions<TDatum>['formatters']
) => string
tooltip?: (
value: number,
formatters: AxisLinearOptions<TDatum>['formatters']
) => React.ReactNode
cursor?: (
value: number,
formatters: AxisLinearOptions<TDatum>['formatters']
) => React.ReactNode
}
}
export type AxisBandOptions<TDatum> = AxisOptionsBase & {
scaleType?: 'band'
getValue: (datum: TDatum) => ChartValue<any>
originalSinBandSize?: number
formatters?: {
scale?: (
value: any,
formatters: AxisBandOptions<TDatum>['formatters']
) => string
tooltip?: (
value: React.ReactNode,
formatters: AxisBandOptions<TDatum>['formatters']
) => string
cursor?: (
value: React.ReactNode,
formatters: AxisBandOptions<TDatum>['formatters']
) => string
}
}
export type AxisOptions<TDatum> =
| AxisTimeOptions<TDatum>
| AxisLinearOptions<TDatum>
| AxisBandOptions<TDatum>
export type AxisOptionsWithScaleType<TDatum> = TSTB.Object.Required<
AxisOptions<TDatum>,
'scaleType'
>
export type BuildAxisOptions<TDatum> = TSTB.Object.Required<
AxisOptions<TDatum>,
'position' | 'scaleType'
>
export type ResolvedAxisOptions<TAxisOptions> = TSTB.Object.Required<
TAxisOptions & {},
| 'scaleType'
| 'position'
| 'minTickPaddingForRotation'
| 'tickLabelRotationDeg'
| 'innerBandPadding'
| 'outerBandPadding'
| 'innerSeriesBandPadding'
| 'outerSeriesBandPadding'
| 'show'
| 'stacked'
>
export type ChartValue<T> = T | null | undefined
export type AxisBase = {
position: Position
isVertical: boolean
range: [number, number]
}
export type AxisTime<TDatum> = Omit<
AxisBase & ResolvedAxisOptions<AxisTimeOptions<TDatum>>,
'format'
> & {
isPrimary?: boolean
isInvalid: boolean
axisFamily: 'time'
scale: ScaleTime<number, number, never>
outerScale: ScaleTime<number, number, never>
primaryBandScale?: ScaleBand<number>
seriesBandScale?: ScaleBand<number>
formatters: {
default: (value: Date) => string
scale: (value: Date) => string
tooltip: (value: Date) => React.ReactNode
cursor: (value: Date) => React.ReactNode
}
}
export type AxisLinear<TDatum> = Omit<
AxisBase & ResolvedAxisOptions<AxisLinearOptions<TDatum>>,
'format'
> & {
isPrimary?: boolean
isInvalid: boolean
axisFamily: 'linear'
scale: ScaleLinear<number, number, never>
outerScale: ScaleLinear<number, number, never>
primaryBandScale?: ScaleBand<number>
seriesBandScale?: ScaleBand<number>
formatters: {
default: (value: ChartValue<any>) => string
scale: (value: number) => string
tooltip: (value: number) => React.ReactNode
cursor: (value: number) => React.ReactNode
}
}
export type AxisBand<TDatum> = Omit<
AxisBase & ResolvedAxisOptions<AxisBandOptions<TDatum>>,
'format'
> & {
isPrimary?: boolean
isInvalid: boolean
axisFamily: 'band'
scale: ScaleBand<any>
outerScale: ScaleBand<any>
primaryBandScale: ScaleBand<number>
seriesBandScale: ScaleBand<number>
formatters: {
default: (value: any) => string
scale: (value: any) => string
tooltip: (value: React.ReactNode) => string
cursor: (value: React.ReactNode) => string
}
}
export type Axis<TDatum> =
| AxisTime<TDatum>
| AxisLinear<TDatum>
| AxisBand<TDatum>
export type UserSerie<TDatum> = {
data: TDatum[]
id?: string
label?: string
color?: string
primaryAxisId?: string
secondaryAxisId?: string
}
//
export type Series<TDatum> = {
originalSeries: UserSerie<TDatum>
index: number
indexPerAxis: number
id: string
label: string
secondaryAxisId?: string
datums: Datum<TDatum>[]
style?: CSSProperties
}
export type Datum<TDatum> = {
originalSeries: UserSerie<TDatum>
seriesIndex: number
seriesId: string
seriesLabel: string
index: number
originalDatum: TDatum
secondaryAxisId?: string
seriesIndexPerAxis: number
primaryValue?: any
secondaryValue?: any
stackData?: StackDatum<TDatum>
interactiveGroup?: Datum<TDatum>[]
tooltipGroup?: Datum<TDatum>[]
style?: CSSProperties
element?: Element | null
}
export type StackDatum<TDatum> = {
0: number
1: number
data: Datum<TDatum>
length: number
}
//
export type Measurement = Side | 'width' | 'height'
export type GridDimensions = {
left: number
top: number
right: number
bottom: number
width: number
height: number
}
export type CursorOptions = {
value?: unknown
show?: boolean
showLine?: boolean
showLabel?: boolean
onChange?: (value: any) => void
}
export type SeriesFocusStatus = 'none' | 'focused'
export type DatumFocusStatus = 'none' | 'focused' | 'groupFocused' | the_stack |
import { Keyboard, Platform } from 'react-native';
import { runOnJS, useWorkletCallback } from 'react-native-reanimated';
import { clamp, snapPoint } from 'react-native-redash';
import { useBottomSheetInternal } from './useBottomSheetInternal';
import {
ANIMATION_SOURCE,
GESTURE_SOURCE,
KEYBOARD_STATE,
SCROLLABLE_TYPE,
WINDOW_HEIGHT,
} from '../constants';
import type {
GestureEventsHandlersHookType,
GestureEventHandlerCallbackType,
} from '../types';
type GestureEventContextType = {
initialPosition: number;
initialKeyboardState: KEYBOARD_STATE;
isScrollablePositionLocked: boolean;
};
export const useGestureEventsHandlersDefault: GestureEventsHandlersHookType =
() => {
//#region variables
const {
animatedPosition,
animatedSnapPoints,
animatedKeyboardState,
animatedKeyboardHeight,
animatedContainerHeight,
animatedScrollableType,
animatedHighestSnapPoint,
animatedClosedPosition,
animatedScrollableContentOffsetY,
enableOverDrag,
enablePanDownToClose,
overDragResistanceFactor,
isInTemporaryPosition,
isScrollableRefreshable,
animateToPosition,
stopAnimation,
} = useBottomSheetInternal();
//#endregion
//#region gesture methods
const handleOnStart: GestureEventHandlerCallbackType<GestureEventContextType> =
useWorkletCallback(
function handleOnStart(__, _, context) {
// cancel current animation
stopAnimation();
// store current animated position
context.initialPosition = animatedPosition.value;
context.initialKeyboardState = animatedKeyboardState.value;
/**
* if the scrollable content is scrolled, then
* we lock the position.
*/
if (animatedScrollableContentOffsetY.value > 0) {
context.isScrollablePositionLocked = true;
}
},
[
stopAnimation,
animatedPosition,
animatedKeyboardState,
animatedScrollableContentOffsetY,
]
);
const handleOnActive: GestureEventHandlerCallbackType<GestureEventContextType> =
useWorkletCallback(
function handleOnActive(source, { translationY }, context) {
let highestSnapPoint = animatedHighestSnapPoint.value;
/**
* if keyboard is shown, then we set the highest point to the current
* position which includes the keyboard height.
*/
if (
isInTemporaryPosition.value &&
context.initialKeyboardState === KEYBOARD_STATE.SHOWN
) {
highestSnapPoint = context.initialPosition;
}
/**
* if current position is out of provided `snapPoints` and smaller then
* highest snap pont, then we set the highest point to the current position.
*/
if (
isInTemporaryPosition.value &&
context.initialPosition < highestSnapPoint
) {
highestSnapPoint = context.initialPosition;
}
const lowestSnapPoint = enablePanDownToClose
? animatedContainerHeight.value
: animatedSnapPoints.value[0];
/**
* if scrollable is refreshable and sheet position at the highest
* point, then do not interact with current gesture.
*/
if (
source === GESTURE_SOURCE.SCROLLABLE &&
isScrollableRefreshable.value &&
animatedPosition.value === highestSnapPoint
) {
return;
}
/**
* a negative scrollable content offset to be subtracted from accumulated
* current position and gesture translation Y to allow user to drag the sheet,
* when scrollable position at the top.
* a negative scrollable content offset when the scrollable is not locked.
*/
const negativeScrollableContentOffset =
(context.initialPosition === highestSnapPoint &&
source === GESTURE_SOURCE.SCROLLABLE) ||
!context.isScrollablePositionLocked
? animatedScrollableContentOffsetY.value * -1
: 0;
/**
* an accumulated value of starting position with gesture translation y.
*/
const draggedPosition = context.initialPosition + translationY;
/**
* an accumulated value of dragged position and negative scrollable content offset,
* this will insure locking sheet position when user is scrolling the scrollable until,
* they reach to the top of the scrollable.
*/
const accumulatedDraggedPosition =
draggedPosition + negativeScrollableContentOffset;
/**
* a clamped value of the accumulated dragged position, to insure keeping the dragged
* position between the highest and lowest snap points.
*/
const clampedPosition = clamp(
accumulatedDraggedPosition,
highestSnapPoint,
lowestSnapPoint
);
/**
* if scrollable position is locked and the animated position
* reaches the highest point, then we unlock the scrollable position.
*/
if (
context.isScrollablePositionLocked &&
source === GESTURE_SOURCE.SCROLLABLE &&
animatedPosition.value === highestSnapPoint
) {
context.isScrollablePositionLocked = false;
}
/**
* over-drag implementation.
*/
if (enableOverDrag) {
if (
(source === GESTURE_SOURCE.HANDLE ||
animatedScrollableType.value === SCROLLABLE_TYPE.VIEW) &&
draggedPosition < highestSnapPoint
) {
const resistedPosition =
highestSnapPoint -
Math.sqrt(1 + (highestSnapPoint - draggedPosition)) *
overDragResistanceFactor;
animatedPosition.value = resistedPosition;
return;
}
if (
source === GESTURE_SOURCE.HANDLE &&
draggedPosition > lowestSnapPoint
) {
const resistedPosition =
lowestSnapPoint +
Math.sqrt(1 + (draggedPosition - lowestSnapPoint)) *
overDragResistanceFactor;
animatedPosition.value = resistedPosition;
return;
}
if (
source === GESTURE_SOURCE.SCROLLABLE &&
draggedPosition + negativeScrollableContentOffset >
lowestSnapPoint
) {
const resistedPosition =
lowestSnapPoint +
Math.sqrt(
1 +
(draggedPosition +
negativeScrollableContentOffset -
lowestSnapPoint)
) *
overDragResistanceFactor;
animatedPosition.value = resistedPosition;
return;
}
}
animatedPosition.value = clampedPosition;
},
[
enableOverDrag,
enablePanDownToClose,
overDragResistanceFactor,
isInTemporaryPosition,
isScrollableRefreshable,
animatedHighestSnapPoint,
animatedContainerHeight,
animatedSnapPoints,
animatedPosition,
animatedScrollableType,
animatedScrollableContentOffsetY,
]
);
const handleOnEnd: GestureEventHandlerCallbackType<GestureEventContextType> =
useWorkletCallback(
function handleOnEnd(
source,
{ translationY, absoluteY, velocityY },
context
) {
const highestSnapPoint = animatedHighestSnapPoint.value;
const isSheetAtHighestSnapPoint =
animatedPosition.value === highestSnapPoint;
/**
* if scrollable is refreshable and sheet position at the highest
* point, then do not interact with current gesture.
*/
if (
source === GESTURE_SOURCE.SCROLLABLE &&
isScrollableRefreshable.value &&
isSheetAtHighestSnapPoint
) {
return;
}
/**
* if the sheet is in a temporary position and the gesture ended above
* the current position, then we snap back to the temporary position.
*/
if (
isInTemporaryPosition.value &&
context.initialPosition >= animatedPosition.value
) {
if (context.initialPosition > animatedPosition.value) {
animateToPosition(
context.initialPosition,
ANIMATION_SOURCE.GESTURE,
velocityY / 2
);
}
return;
}
/**
* close keyboard if current position is below the recorded
* start position and keyboard still shown.
*/
const isScrollable =
animatedScrollableType.value !== SCROLLABLE_TYPE.UNDETERMINED &&
animatedScrollableType.value !== SCROLLABLE_TYPE.VIEW;
/**
* if keyboard is shown and the sheet is dragged down,
* then we dismiss the keyboard.
*/
if (
context.initialKeyboardState === KEYBOARD_STATE.SHOWN &&
animatedPosition.value > context.initialPosition
) {
/**
* if the platform is ios, current content is scrollable and
* the end touch point is below the keyboard position then
* we exit the method.
*
* because the the keyboard dismiss is interactive in iOS.
*/
if (
!(
Platform.OS === 'ios' &&
isScrollable &&
absoluteY > WINDOW_HEIGHT - animatedKeyboardHeight.value
)
) {
runOnJS(Keyboard.dismiss)();
}
}
/**
* reset isInTemporaryPosition value
*/
if (isInTemporaryPosition.value) {
isInTemporaryPosition.value = false;
}
/**
* clone snap points array, and insert the container height
* if pan down to close is enabled.
*/
const snapPoints = animatedSnapPoints.value.slice();
if (enablePanDownToClose) {
snapPoints.unshift(animatedClosedPosition.value);
}
/**
* calculate the destination point, using redash.
*/
const destinationPoint = snapPoint(
translationY + context.initialPosition,
velocityY,
snapPoints
);
/**
* if destination point is the same as the current position,
* then no need to perform animation.
*/
if (destinationPoint === animatedPosition.value) {
return;
}
const wasGestureHandledByScrollView =
source === GESTURE_SOURCE.SCROLLABLE &&
animatedScrollableContentOffsetY.value > 0;
/**
* prevents snapping from top to middle / bottom with repeated interrupted scrolls
*/
if (wasGestureHandledByScrollView && isSheetAtHighestSnapPoint) {
return;
}
animateToPosition(
destinationPoint,
ANIMATION_SOURCE.GESTURE,
velocityY / 2
);
},
[
enablePanDownToClose,
isInTemporaryPosition,
isScrollableRefreshable,
animatedClosedPosition,
animatedHighestSnapPoint,
animatedKeyboardHeight,
animatedPosition,
animatedScrollableType,
animatedSnapPoints,
animatedScrollableContentOffsetY,
animateToPosition,
]
);
//#endregion
return {
handleOnStart,
handleOnActive,
handleOnEnd,
};
}; | the_stack |
import * as chai from 'chai';
import castToType from 'fontoxpath/expressions/dataTypes/castToType';
import createAtomicValue from 'fontoxpath/expressions/dataTypes/createAtomicValue';
import { ValueType } from 'fontoxpath/expressions/dataTypes/Value';
import DateTime from 'fontoxpath/expressions/dataTypes/valueTypes/DateTime';
import DayTimeDuration from 'fontoxpath/expressions/dataTypes/valueTypes/DayTimeDuration';
import Duration from 'fontoxpath/expressions/dataTypes/valueTypes/Duration';
import YearMonthDuration from 'fontoxpath/expressions/dataTypes/valueTypes/YearMonthDuration';
// Y = can be cast to target
// N = can not be cast to target
// ? = depends on given value if cast will succeed
// S\T | uA str flt dbl dec int dur yMD dTD dT tim dat gYM gY gMD gD gM bln b64 hxB URI QN NOT
// uA | Y Y ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
// str | Y Y ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
// flt | Y Y Y Y ? ? N N N N N N N N N N N Y N N N N N
// dbl | Y Y Y Y ? ? N N N N N N N N N N N Y N N N N N
// dec | Y Y Y Y Y Y N N N N N N N N N N N Y N N N N N
// int | Y Y Y Y Y Y N N N N N N N N N N N Y N N N N N
// dur | Y Y N N N N Y Y Y N N N N N N N N N N N N N N
// yMD | Y Y N N N N Y Y Y N N N N N N N N N N N N N N
// dTD | Y Y N N N N Y Y Y N N N N N N N N N N N N N N
// dT | Y Y N N N N N N N Y Y Y Y Y Y Y Y N N N N N N
// tim | Y Y N N N N N N N N Y N N N N N N N N N N N N
// dat | Y Y N N N N N N N Y N Y Y Y Y Y Y N N N N N N
// gYM | Y Y N N N N N N N N N N Y N N N N N N N N N N
// gY | Y Y N N N N N N N N N N N Y N N N N N N N N N
// gMD | Y Y N N N N N N N N N N N N Y N N N N N N N N
// gD | Y Y N N N N N N N N N N N N N Y N N N N N N N
// gM | Y Y N N N N N N N N N N N N N N Y N N N N N N
// bln | Y Y Y Y Y Y N N N N N N N N N N N Y N N N N N
// b64 | Y Y N N N N N N N N N N N N N N N N Y Y N N N
// hxB | Y Y N N N N N N N N N N N N N N N N Y Y N N N
// URI | Y Y N N N N N N N N N N N N N N N N N N Y N N
// QN | Y Y N N N N N N N N N N N N N N N N N N N Y ?
// NOT | Y Y N N N N N N N N N N N N N N N N N N N Y ?
describe('castToType()', () => {
before(() => {
if (typeof (global as any).atob === 'undefined') {
(global as any).atob = (b64Encoded) => new Buffer(b64Encoded, 'base64').toString();
(global as any).btoa = (str) => new Buffer(str).toString('base64');
}
});
describe('casting to or from xs:anySimpleType', () => {
it('throws when casting to xs:anySimpleType', () => {
chai.assert.throw(() =>
castToType(
createAtomicValue('string', ValueType.XSSTRING),
ValueType.XSANYSIMPLETYPE
)
);
});
it('throws when casting from xs:anySimpleType', () => {
chai.assert.throw(() =>
castToType(
createAtomicValue('string', ValueType.XSANYSIMPLETYPE),
ValueType.XSSTRING
)
);
});
});
describe('casting to or from xs:anyAtomicType', () => {
it('throws when casting to xs:anyAtomicType', () => {
chai.assert.throw(() =>
castToType(
createAtomicValue('string', ValueType.XSSTRING),
ValueType.XSANYATOMICTYPE
)
);
});
it('throws when casting to xs:anyAtomicTpe', () => {
chai.assert.throw(() =>
castToType(
createAtomicValue('string', ValueType.XSANYATOMICTYPE),
ValueType.XSSTRING
)
);
});
});
describe('to xs:untypedAtomic', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('string', ValueType.XSSTRING),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSUNTYPEDATOMIC),
createAtomicValue('10.123', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(10.123, ValueType.XSDOUBLE),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('10.123', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSUNTYPEDATOMIC),
createAtomicValue('1010', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSUNTYPEDATOMIC),
createAtomicValue('1010', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:duration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('P10Y10M10DT10H10M10S', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:yearMonthDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('P10Y10M', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:dayTimeDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10DT10H10M10S'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('P10DT10H10M10S', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('2000-10-10T10:10:10+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:time', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('10:10:10+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('2000-10-10+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:gYearMonth', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('2000-10+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:gYear', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('2000+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:gMonthDay', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('--10-10+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:gDay', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('---10+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:gMonth', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('--10+10:30', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSUNTYPEDATOMIC),
createAtomicValue('true', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:base64Binary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:hexBinary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:anyURI', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC)
));
it('from xs:NOTATION', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSUNTYPEDATOMIC
),
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC)
));
});
describe('to xs:string', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC),
ValueType.XSSTRING
),
createAtomicValue('string', ValueType.XSSTRING)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('string', ValueType.XSSTRING), ValueType.XSSTRING),
createAtomicValue('string', ValueType.XSSTRING)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSSTRING),
createAtomicValue('10.123', ValueType.XSSTRING)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSSTRING),
createAtomicValue('10.123', ValueType.XSSTRING)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSSTRING),
createAtomicValue('1010', ValueType.XSSTRING)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSSTRING),
createAtomicValue('1010', ValueType.XSSTRING)
));
it('from xs:duration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSSTRING
),
createAtomicValue('P10Y10M10DT10H10M10S', ValueType.XSSTRING)
));
it('from xs:yearMonthDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSSTRING
),
createAtomicValue('P10Y10M', ValueType.XSSTRING)
));
it('from xs:dayTimeDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10DT10H10M10S'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSSTRING
),
createAtomicValue('P10DT10H10M10S', ValueType.XSSTRING)
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSSTRING
),
createAtomicValue('2000-10-10T10:10:10+10:30', ValueType.XSSTRING)
));
it('from xs:time', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSSTRING
),
createAtomicValue('10:10:10+10:30', ValueType.XSSTRING)
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSSTRING
),
createAtomicValue('2000-10-10+10:30', ValueType.XSSTRING)
));
it('from xs:gYearMonth', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH),
ValueType.XSSTRING
),
createAtomicValue('2000-10+10:30', ValueType.XSSTRING)
));
it('from xs:gYear', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSSTRING
),
createAtomicValue('2000+10:30', ValueType.XSSTRING)
));
it('from xs:gMonthDay', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY),
ValueType.XSSTRING
),
createAtomicValue('--10-10+10:30', ValueType.XSSTRING)
));
it('from xs:gDay', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSSTRING
),
createAtomicValue('---10+10:30', ValueType.XSSTRING)
));
it('from xs:gMonth', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSSTRING
),
createAtomicValue('--10+10:30', ValueType.XSSTRING)
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSSTRING),
createAtomicValue('true', ValueType.XSSTRING)
));
it('from xs:base64Binary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSSTRING
),
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSSTRING)
));
it('from xs:hexBinary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSSTRING
),
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSSTRING)
));
it('from xs:anyURI', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSSTRING),
createAtomicValue('string', ValueType.XSSTRING)
));
it('from xs:NOTATION', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('string', ValueType.XSNOTATION), ValueType.XSSTRING),
createAtomicValue('string', ValueType.XSSTRING)
));
});
describe('to xs:float', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('10.10', ValueType.XSUNTYPEDATOMIC),
ValueType.XSFLOAT
),
createAtomicValue(10.1, ValueType.XSFLOAT)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('10.10', ValueType.XSSTRING), ValueType.XSFLOAT),
createAtomicValue(10.1, ValueType.XSFLOAT)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSFLOAT),
createAtomicValue(10.123, ValueType.XSFLOAT)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSFLOAT),
createAtomicValue(10.123, ValueType.XSFLOAT)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSFLOAT),
createAtomicValue(1010, ValueType.XSFLOAT)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSFLOAT),
createAtomicValue(1010, ValueType.XSFLOAT)
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(Duration.fromString('P10Y10M'), ValueType.XSDURATION),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSFLOAT),
createAtomicValue(1, ValueType.XSFLOAT)
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSFLOAT
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSFLOAT),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSFLOAT
),
'XPTY0004'
));
});
describe('to xs:double', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('10.10', ValueType.XSUNTYPEDATOMIC),
ValueType.XSDOUBLE
),
createAtomicValue(10.1, ValueType.XSDOUBLE)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('10.10', ValueType.XSSTRING), ValueType.XSDOUBLE),
createAtomicValue(10.1, ValueType.XSDOUBLE)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSDOUBLE),
createAtomicValue(10.123, ValueType.XSDOUBLE)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSDOUBLE),
createAtomicValue(10.123, ValueType.XSDOUBLE)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSDOUBLE),
createAtomicValue(1010, ValueType.XSDOUBLE)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSDOUBLE),
createAtomicValue(1010, ValueType.XSDOUBLE)
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(Duration.fromString('P10Y10M'), ValueType.XSDURATION),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSDOUBLE),
createAtomicValue(1, ValueType.XSDOUBLE)
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSDOUBLE),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSDOUBLE
),
'XPTY0004'
));
});
describe('to xs:double', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('10.10', ValueType.XSUNTYPEDATOMIC),
ValueType.XSDOUBLE
),
createAtomicValue(10.1, ValueType.XSDOUBLE)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('10.10', ValueType.XSSTRING), ValueType.XSDOUBLE),
createAtomicValue(10.1, ValueType.XSDOUBLE)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSDOUBLE),
createAtomicValue(10.123, ValueType.XSDOUBLE)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSDOUBLE),
createAtomicValue(10.123, ValueType.XSDOUBLE)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSDOUBLE),
createAtomicValue(1010, ValueType.XSDOUBLE)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSDOUBLE),
createAtomicValue(1010, ValueType.XSDOUBLE)
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(Duration.fromString('P10Y10M'), ValueType.XSDURATION),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSDOUBLE),
createAtomicValue(1, ValueType.XSDOUBLE)
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSDOUBLE
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSDOUBLE),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSDOUBLE
),
'XPTY0004'
));
});
describe('to xs:decimal', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('10.10', ValueType.XSUNTYPEDATOMIC),
ValueType.XSDECIMAL
),
createAtomicValue(10.1, ValueType.XSDECIMAL)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('10.10', ValueType.XSSTRING), ValueType.XSDECIMAL),
createAtomicValue(10.1, ValueType.XSDECIMAL)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSDECIMAL),
createAtomicValue(10.123, ValueType.XSDECIMAL)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSDECIMAL),
createAtomicValue(10.123, ValueType.XSDECIMAL)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSDECIMAL),
createAtomicValue(1010, ValueType.XSDECIMAL)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSDECIMAL),
createAtomicValue(1010, ValueType.XSDECIMAL)
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(Duration.fromString('P10Y10M'), ValueType.XSDURATION),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSDECIMAL),
createAtomicValue(1, ValueType.XSDECIMAL)
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSDECIMAL
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSDECIMAL
),
'XPTY0004'
));
});
describe('to xs:integer', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('10', ValueType.XSUNTYPEDATOMIC), ValueType.XSINTEGER),
createAtomicValue(10, ValueType.XSINTEGER)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('10', ValueType.XSSTRING), ValueType.XSINTEGER),
createAtomicValue(10, ValueType.XSINTEGER)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSINTEGER),
createAtomicValue(10, ValueType.XSINTEGER)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSINTEGER),
createAtomicValue(10, ValueType.XSINTEGER)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSINTEGER),
createAtomicValue(1010, ValueType.XSINTEGER)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSINTEGER),
createAtomicValue(1010, ValueType.XSINTEGER)
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(Duration.fromString('P10Y10M'), ValueType.XSDURATION),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSINTEGER),
createAtomicValue(1, ValueType.XSINTEGER)
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSINTEGER
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSINTEGER
),
'XPTY0004'
));
});
describe('to xs:duration', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('P10Y10M10DT10H10M10S', ValueType.XSUNTYPEDATOMIC),
ValueType.XSDURATION
),
createAtomicValue(Duration.fromString('P10Y10M10DT10H10M10S'), ValueType.XSDURATION)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('P10Y10M10DT10H10M10S', ValueType.XSSTRING),
ValueType.XSDURATION
),
createAtomicValue(Duration.fromString('P10Y10M10DT10H10M10S'), ValueType.XSDURATION)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSDURATION),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSDURATION),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSDURATION),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSDURATION),
'XPTY0004'
));
it('from xs:duration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSDURATION
),
createAtomicValue(Duration.fromString('P10Y10M10DT10H10M10S'), ValueType.XSDURATION)
));
it('from xs:yearMonthDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
YearMonthDuration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSDURATION
),
createAtomicValue(Duration.fromString('P10Y10M'), ValueType.XSDURATION)
));
it('from xs:dayTimeDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DayTimeDuration.fromString('P10D'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSDURATION
),
createAtomicValue(Duration.fromString('P10D'), ValueType.XSDURATION)
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSDURATION),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSDURATION
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSDURATION
),
'XPTY0004'
));
});
describe('to xs:yearMonthDuration', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('P10Y10M', ValueType.XSUNTYPEDATOMIC),
ValueType.XSYEARMONTHDURATION
),
createAtomicValue(
YearMonthDuration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('P10Y10M', ValueType.XSSTRING),
ValueType.XSYEARMONTHDURATION
),
createAtomicValue(
YearMonthDuration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(10.123, ValueType.XSFLOAT),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(10.123, ValueType.XSDOUBLE),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(1010, ValueType.XSDECIMAL),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(1010, ValueType.XSINTEGER),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:duration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSYEARMONTHDURATION
),
createAtomicValue(
YearMonthDuration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
)
));
it('from xs:yearMonthDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
YearMonthDuration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSYEARMONTHDURATION
),
createAtomicValue(
YearMonthDuration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
)
));
it('from xs:dayTimeDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DayTimeDuration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSYEARMONTHDURATION
),
createAtomicValue(
YearMonthDuration.fromString('P0M'),
ValueType.XSYEARMONTHDURATION
)
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(true, ValueType.XSBOOLEAN),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSYEARMONTHDURATION
),
'XPTY0004'
));
});
describe('to xs:dayTimeDuration', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('P10DT10H10M10S', ValueType.XSUNTYPEDATOMIC),
ValueType.XSDAYTIMEDURATION
),
createAtomicValue(
DayTimeDuration.fromString('P10DT10H10M10S'),
ValueType.XSDAYTIMEDURATION
)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('P10DT10H10M10S', ValueType.XSSTRING),
ValueType.XSDAYTIMEDURATION
),
createAtomicValue(
DayTimeDuration.fromString('P10DT10H10M10S'),
ValueType.XSDAYTIMEDURATION
)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(10.123, ValueType.XSFLOAT),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(10.123, ValueType.XSDOUBLE),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(1010, ValueType.XSDECIMAL),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(1010, ValueType.XSINTEGER),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:duration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSDAYTIMEDURATION
),
createAtomicValue(
DayTimeDuration.fromString('P10DT10H10M10S'),
ValueType.XSDAYTIMEDURATION
)
));
it('from xs:yearMonthDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
YearMonthDuration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSDAYTIMEDURATION
),
createAtomicValue(DayTimeDuration.fromString('PT0S'), ValueType.XSDAYTIMEDURATION)
));
it('from xs:dayTimeDuration', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DayTimeDuration.fromString('P10DT10H10M10S'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSDAYTIMEDURATION
),
createAtomicValue(
DayTimeDuration.fromString('P10DT10H10M10S'),
ValueType.XSDAYTIMEDURATION
)
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(true, ValueType.XSBOOLEAN),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSDAYTIMEDURATION
),
'XPTY0004'
));
});
describe('to xs:dateTime', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('2000-10-10T10:10:10+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSDATETIME
),
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('2000-10-10T10:10:10+10:30', ValueType.XSSTRING),
ValueType.XSDATETIME
),
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSDATETIME),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSDATETIME),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSDATETIME),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSDATETIME),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSDATETIME
),
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
)
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSDATETIME
),
createAtomicValue(
DateTime.fromString('2000-10-10T00:00:00+10:30'),
ValueType.XSDATETIME
)
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSDATETIME),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSDATETIME
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSDATETIME
),
'XPTY0004'
));
});
describe('to xs:time', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('10:10:10+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSTIME
),
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('10:10:10+10:30', ValueType.XSSTRING),
ValueType.XSTIME
),
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSTIME),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSTIME),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSTIME),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSTIME),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSTIME
),
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME)
));
it('from xs:time', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSTIME
),
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME)
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSTIME),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSTIME
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSTIME),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSNOTATION), ValueType.XSTIME),
'XPTY0004'
));
});
describe('to xs:date', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('2000-10-10+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSDATE
),
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('2000-10-10+10:30', ValueType.XSSTRING),
ValueType.XSDATE
),
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSDATE),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSDATE),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSDATE),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSDATE),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSDATE
),
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE)
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSDATE
),
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE)
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSDATE),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSDATE
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSDATE),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSNOTATION), ValueType.XSDATE),
'XPTY0004'
));
});
describe('to xs:gYearMonth', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('2000-10+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSGYEARMONTH
),
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('2000-10+10:30', ValueType.XSSTRING),
ValueType.XSGYEARMONTH
),
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(10.123, ValueType.XSFLOAT),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(10.123, ValueType.XSDOUBLE),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(1010, ValueType.XSDECIMAL),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(1010, ValueType.XSINTEGER),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSGYEARMONTH
),
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH)
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSGYEARMONTH
),
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH)
));
it('from xs:gYearMonth', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH),
ValueType.XSGYEARMONTH
),
createAtomicValue(DateTime.fromString('2000-10+10:30'), ValueType.XSGYEARMONTH)
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(true, ValueType.XSBOOLEAN),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSGYEARMONTH
),
'XPTY0004'
));
});
describe('to xs:gYear', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('2000+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSGYEAR
),
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('2000+10:30', ValueType.XSSTRING), ValueType.XSGYEAR),
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSGYEAR),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSGYEAR),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSGYEAR),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSGYEAR),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSGYEAR
),
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR)
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSGYEAR
),
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR)
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:gYear', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSGYEAR
),
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR)
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSGYEAR),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSGYEAR
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSGYEAR),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSGYEAR
),
'XPTY0004'
));
});
describe('to xs:gMonthDay', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('--10-10+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSGMONTHDAY
),
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('--10-10+10:30', ValueType.XSSTRING),
ValueType.XSGMONTHDAY
),
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSGMONTHDAY),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(10.123, ValueType.XSDOUBLE),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSGMONTHDAY),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSGMONTHDAY),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSGMONTHDAY
),
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY)
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSGMONTHDAY
),
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY)
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:gMonthDay', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY),
ValueType.XSGMONTHDAY
),
createAtomicValue(DateTime.fromString('--10-10+10:30'), ValueType.XSGMONTHDAY)
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSGMONTHDAY),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSGMONTHDAY
),
'XPTY0004'
));
});
describe('to xs:gDay', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('---10+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSGDAY
),
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('---10+10:30', ValueType.XSSTRING), ValueType.XSGDAY),
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSGDAY),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSGDAY),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSGDAY),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSGDAY),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSGDAY
),
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY)
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSGDAY
),
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY)
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:gDay', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSGDAY
),
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY)
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSGDAY),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSGDAY
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSGDAY),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSNOTATION), ValueType.XSGDAY),
'XPTY0004'
));
});
describe('to xs:gMonth', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('--10+10:30', ValueType.XSUNTYPEDATOMIC),
ValueType.XSGMONTH
),
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('--10+10:30', ValueType.XSSTRING), ValueType.XSGMONTH),
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSFLOAT), ValueType.XSGMONTH),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(10.123, ValueType.XSDOUBLE), ValueType.XSGMONTH),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSDECIMAL), ValueType.XSGMONTH),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1010, ValueType.XSINTEGER), ValueType.XSGMONTH),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:dateTime', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSGMONTH
),
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH)
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:date', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('2000-10-10+10:30'), ValueType.XSDATE),
ValueType.XSGMONTH
),
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH)
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:gMonth', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSGMONTH
),
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH)
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSGMONTH),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSGMONTH
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSGMONTH),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSGMONTH
),
'XPTY0004'
));
});
describe('to xs:boolean', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('true', ValueType.XSUNTYPEDATOMIC),
ValueType.XSBOOLEAN
),
createAtomicValue(true, ValueType.XSBOOLEAN)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('true', ValueType.XSSTRING), ValueType.XSBOOLEAN),
createAtomicValue(true, ValueType.XSBOOLEAN)
));
it('from xs:float', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1, ValueType.XSFLOAT), ValueType.XSBOOLEAN),
createAtomicValue(true, ValueType.XSBOOLEAN)
));
it('from xs:double', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1, ValueType.XSDOUBLE), ValueType.XSBOOLEAN),
createAtomicValue(true, ValueType.XSBOOLEAN)
));
it('from xs:decimal', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1, ValueType.XSDECIMAL), ValueType.XSBOOLEAN),
createAtomicValue(true, ValueType.XSBOOLEAN)
));
it('from xs:integer', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(1, ValueType.XSINTEGER), ValueType.XSBOOLEAN),
createAtomicValue(true, ValueType.XSBOOLEAN)
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:boolean', () =>
chai.assert.deepEqual(
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSBOOLEAN),
createAtomicValue(true, ValueType.XSBOOLEAN)
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('21FE3A44123C21FE3A44123C', ValueType.XSHEXBINARY),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSBOOLEAN
),
'XPTY0004'
));
});
describe('to xs:base64Binary', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSUNTYPEDATOMIC),
ValueType.XSBASE64BINARY
),
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSSTRING),
ValueType.XSBASE64BINARY
),
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSFLOAT), ValueType.XSBASE64BINARY),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1, ValueType.XSDOUBLE), ValueType.XSBASE64BINARY),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1, ValueType.XSDECIMAL), ValueType.XSBASE64BINARY),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(1, ValueType.XSINTEGER), ValueType.XSBASE64BINARY),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(true, ValueType.XSBOOLEAN),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:base64Binary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSBASE64BINARY
),
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY)
));
it('from xs:hexBinary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSHEXBINARY),
ValueType.XSBASE64BINARY
),
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY)
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSBASE64BINARY
),
'XPTY0004'
));
});
describe('to xs:hexBinary', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue(
'736F6D65206261736536342074657874',
ValueType.XSUNTYPEDATOMIC
),
ValueType.XSHEXBINARY
),
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSHEXBINARY)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSSTRING),
ValueType.XSHEXBINARY
),
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSHEXBINARY)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSFLOAT), ValueType.XSHEXBINARY),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSDOUBLE), ValueType.XSHEXBINARY),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSDECIMAL), ValueType.XSHEXBINARY),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSINTEGER), ValueType.XSHEXBINARY),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSHEXBINARY),
'XPTY0004'
));
it('from xs:base64Binary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSHEXBINARY
),
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSHEXBINARY)
));
it('from xs:hexBinary', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSHEXBINARY),
ValueType.XSHEXBINARY
),
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSHEXBINARY)
));
it('from xs:anyURI (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSHEXBINARY
),
'XPTY0004'
));
});
describe('to xs:anyURI', () => {
it('from xs:untypedAtomic', () =>
chai.assert.deepEqual(
castToType(
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC),
ValueType.XSANYURI
),
createAtomicValue('string', ValueType.XSANYURI)
));
it('from xs:string', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('string', ValueType.XSSTRING), ValueType.XSANYURI),
createAtomicValue('string', ValueType.XSANYURI)
));
it('from xs:float (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSFLOAT), ValueType.XSANYURI),
'XPTY0004'
));
it('from xs:double (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSDOUBLE), ValueType.XSANYURI),
'XPTY0004'
));
it('from xs:decimal (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSDECIMAL), ValueType.XSANYURI),
'XPTY0004'
));
it('from xs:integer (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSINTEGER), ValueType.XSANYURI),
'XPTY0004'
));
it('from xs:duration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:yearMonthDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:dayTimeDuration (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:dateTime (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:time (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:date (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:gYearMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:gYear (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:gMonthDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:gDay (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:gMonth (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:boolean (throws XPTY0004)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSANYURI),
'XPTY0004'
));
it('from xs:base64Binary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:hexBinary (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
'736F6D65206261736536342074657874',
ValueType.XSHEXBINARY
),
ValueType.XSANYURI
),
'XPTY0004'
));
it('from xs:anyURI', () =>
chai.assert.deepEqual(
castToType(createAtomicValue('string', ValueType.XSANYURI), ValueType.XSANYURI),
createAtomicValue('string', ValueType.XSANYURI)
));
it('from xs:NOTATION (throws XPTY0004)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSANYURI
),
'XPTY0004'
));
});
describe('to xs:NOTATION', () => {
it('from xs:untypedAtomic (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSUNTYPEDATOMIC),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:string (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSSTRING),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:float (throws XPST0080)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSFLOAT), ValueType.XSNOTATION),
'XPST0080'
));
it('from xs:double (throws XPST0080)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSDOUBLE), ValueType.XSNOTATION),
'XPST0080'
));
it('from xs:decimal (throws XPST0080)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSDECIMAL), ValueType.XSNOTATION),
'XPST0080'
));
it('from xs:integer (throws XPST0080)', () =>
chai.assert.throws(
() => castToType(createAtomicValue(1, ValueType.XSINTEGER), ValueType.XSNOTATION),
'XPST0080'
));
it('from xs:duration (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M10DT10H10M10S'),
ValueType.XSDURATION
),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:yearMonthDuration (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSYEARMONTHDURATION
),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:dayTimeDuration (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
Duration.fromString('P10Y10M'),
ValueType.XSDAYTIMEDURATION
),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:dateTime (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10T10:10:10+10:30'),
ValueType.XSDATETIME
),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:time (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('10:10:10+10:30'), ValueType.XSTIME),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:date (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10-10+10:30'),
ValueType.XSDATE
),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:gYearMonth (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('2000-10+10:30'),
ValueType.XSGYEARMONTH
),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:gYear (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('2000+10:30'), ValueType.XSGYEAR),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:gMonthDay (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(
DateTime.fromString('--10-10+10:30'),
ValueType.XSGMONTHDAY
),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:gDay (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('---10+10:30'), ValueType.XSGDAY),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:gMonth (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue(DateTime.fromString('--10+10:30'), ValueType.XSGMONTH),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:boolean (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(createAtomicValue(true, ValueType.XSBOOLEAN), ValueType.XSNOTATION),
'XPST0080'
));
it('from xs:base64Binary (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('c29tZSBiYXNlNjQgdGV4dA==', ValueType.XSBASE64BINARY),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:NOTATION (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('736F6D65206261736536342074657874', ValueType.XSNOTATION),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:anyURI (throws XPST0080)', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSANYURI),
ValueType.XSNOTATION
),
'XPST0080'
));
it('from xs:NOTATION', () =>
chai.assert.throws(
() =>
castToType(
createAtomicValue('string', ValueType.XSNOTATION),
ValueType.XSNOTATION
),
'XPST0080'
));
});
}); | the_stack |
import { EOL } from 'os'
import _ from 'lodash'
import wu from 'wu'
import { getChangeElement, isInstanceElement, AdapterOperationName, Progress } from '@salto-io/adapter-api'
import { fetch as apiFetch, FetchFunc, FetchChange, FetchProgressEvents, StepEmitter,
PlanItem, FetchFromWorkspaceFunc, loadLocalWorkspace, fetchFromWorkspace } from '@salto-io/core'
import { Workspace, nacl, StateRecency } from '@salto-io/workspace'
import { promises, values } from '@salto-io/lowerdash'
import { EventEmitter } from 'pietile-eventemitter'
import { logger } from '@salto-io/logging'
import { progressOutputer, outputLine, errorOutputLine } from '../outputer'
import { WorkspaceCommandAction, createWorkspaceCommand } from '../command_builder'
import { CliOutput, CliExitCode, CliTelemetry } from '../types'
import { formatMergeErrors, formatFetchHeader, formatFetchFinish, formatStateChanges, formatStateRecencies, formatAppliedChanges, formatFetchWarnings, formatAdapterProgress } from '../formatter'
import { getApprovedChanges as cliGetApprovedChanges, shouldUpdateConfig as cliShouldUpdateConfig, getChangeToAlignAction } from '../callbacks'
import { getWorkspaceTelemetryTags, updateStateOnly, applyChangesToWorkspace, isValidWorkspaceForCommand } from '../workspace/workspace'
import Prompts from '../prompts'
import { ENVIRONMENT_OPTION, EnvArg, validateAndSetEnv } from './common/env'
import { SERVICES_OPTION, ServicesArg, getAndValidateActiveServices } from './common/services'
const log = logger(module)
const { series } = promises.array
type ApproveChangesFunc = (
changes: ReadonlyArray<FetchChange>,
) => Promise<ReadonlyArray<FetchChange>>
type ShouldUpdateConfigFunc = (
{ stdout }: CliOutput,
introMessage: string,
change: PlanItem
) => Promise<boolean>
export type FetchCommandArgs = {
workspace: Workspace
force: boolean
mode: nacl.RoutingMode
cliTelemetry: CliTelemetry
output: CliOutput
fetch: FetchFunc
getApprovedChanges: ApproveChangesFunc
shouldUpdateConfig: ShouldUpdateConfigFunc
shouldCalcTotalSize: boolean
stateOnly: boolean
services: string[]
regenerateSaltoIds: boolean
}
const createFetchFromWorkspaceCommand = (
fetchFromWorkspaceFunc: FetchFromWorkspaceFunc,
otherWorkspacePath: string,
env : string
): FetchFunc => async (workspace, progressEmitter, services) => {
let otherWorkspace: Workspace
try {
otherWorkspace = await loadLocalWorkspace(otherWorkspacePath, [], false)
} catch (err) {
throw new Error(`Failed to load source workspace: ${err.message ?? err}`)
}
return fetchFromWorkspaceFunc({ workspace, otherWorkspace, progressEmitter, services, env })
}
export const fetchCommand = async (
{
workspace, force, mode,
getApprovedChanges, shouldUpdateConfig, services,
cliTelemetry, output, fetch, shouldCalcTotalSize,
stateOnly, regenerateSaltoIds,
}: FetchCommandArgs): Promise<CliExitCode> => {
const bindedOutputline = (text: string): void => outputLine(text, output)
const workspaceTags = await getWorkspaceTelemetryTags(workspace)
const fetchProgress = new EventEmitter<FetchProgressEvents>()
fetchProgress.on('adaptersDidInitialize', () => {
bindedOutputline(formatFetchHeader())
})
fetchProgress.on('adapterProgress', (adapterName: string, _operationName: AdapterOperationName, progress: Progress) =>
bindedOutputline(formatAdapterProgress(adapterName, progress.message)))
fetchProgress.on('stateWillBeUpdated', (
progress: StepEmitter,
numOfChanges: number
) => progressOutputer(
formatStateChanges(numOfChanges),
() => Prompts.STATE_ONLY_UPDATE_END,
Prompts.STATE_ONLY_UPDATE_FAILED(numOfChanges),
output
)(progress))
fetchProgress.on('changesWillBeFetched', (progress: StepEmitter, adapters: string[]) => progressOutputer(
Prompts.FETCH_GET_CHANGES_START(adapters),
() => Prompts.FETCH_GET_CHANGES_FINISH(adapters),
Prompts.FETCH_GET_CHANGES_FAIL,
output
)(progress))
fetchProgress.on('diffWillBeCalculated', progressOutputer(
Prompts.FETCH_CALC_DIFF_START,
() => Prompts.FETCH_CALC_DIFF_FINISH,
Prompts.FETCH_CALC_DIFF_FAIL,
output
))
fetchProgress.on('workspaceWillBeUpdated', (progress: StepEmitter, _changes: number, approved: number) => {
log.debug(`Applying ${approved} semantic changes to the local workspace`)
progressOutputer(
Prompts.APPLYING_CHANGES,
formatAppliedChanges,
Prompts.FETCH_UPDATE_WORKSPACE_FAIL,
output
)(progress)
})
const applyChangesToState = async (allChanges: readonly FetchChange[]): Promise<boolean> => {
const updatingStateEmitter = new StepEmitter()
fetchProgress.emit('stateWillBeUpdated', updatingStateEmitter, allChanges.length)
const success = await updateStateOnly(workspace, allChanges)
if (success) {
updatingStateEmitter.emit('completed')
return true
}
updatingStateEmitter.emit('failed')
return false
}
if (stateOnly && mode !== 'default') {
throw new Error('The state only flag can only be used in default mode')
}
const fetchResult = await fetch(
workspace,
fetchProgress,
services,
regenerateSaltoIds,
)
// A few merge errors might have occurred,
// but since it's fetch flow, we omitted the elements
// and only print the merge errors
if (!_.isEmpty(fetchResult.mergeErrors)) {
log.debug(`fetch had ${fetchResult.mergeErrors.length} merge errors`)
cliTelemetry.mergeErrors(fetchResult.mergeErrors.length, workspaceTags)
errorOutputLine(formatMergeErrors(fetchResult.mergeErrors), output)
}
if (!_.isUndefined(fetchResult.configChanges)) {
const abortRequests = await series(
wu(fetchResult.configChanges.itemsByEvalOrder()).map(planItem => async () => {
const [change] = planItem.changes()
const newConfig = getChangeElement(change)
const adapterName = newConfig.elemID.adapter
if (!isInstanceElement(newConfig)) {
log.error('Got non instance config from adapter %s - %o', adapterName, newConfig)
return false
}
const shouldWriteToConfig = force || await shouldUpdateConfig(
output,
fetchResult.adapterNameToConfigMessage?.[adapterName] || '',
planItem,
)
if (shouldWriteToConfig) {
await workspace.updateServiceConfig(adapterName, fetchResult.updatedConfig[adapterName])
}
return !shouldWriteToConfig
})
)
if (_.some(abortRequests)) {
return CliExitCode.UserInputError
}
}
// Unpack changes to array so we can iterate on them more than once
const changes = [...fetchResult.changes]
cliTelemetry.changes(changes.length, workspaceTags)
const updatingWsSucceeded = stateOnly
? await applyChangesToState(changes)
: await applyChangesToWorkspace({
workspace,
cliTelemetry,
workspaceTags,
force,
shouldCalcTotalSize,
output,
changes,
mode,
approveChangesCallback: getApprovedChanges,
applyProgress: fetchProgress,
})
if (!_.isEmpty(fetchResult.fetchErrors)) {
// We currently assume all fetchErrors are warnings
log.debug(`fetch had ${fetchResult.fetchErrors.length} warnings`)
bindedOutputline(
formatFetchWarnings(fetchResult.fetchErrors.map(fetchError => fetchError.message))
)
}
if (updatingWsSucceeded) {
bindedOutputline(formatFetchFinish())
return CliExitCode.Success
}
return CliExitCode.AppError
}
const shouldRecommendAlignMode = async (
workspace: Workspace,
stateRecencies: StateRecency[],
inputServices?: ReadonlyArray<string>,
): Promise<boolean> => {
const newlyAddedServices = stateRecencies
.filter(recency => (
inputServices === undefined
|| inputServices.includes(recency.serviceName)
))
return (
newlyAddedServices.every(recency => recency.status === 'Nonexistent')
&& workspace.hasElementsInServices(newlyAddedServices.map(recency => recency.serviceName))
)
}
type FetchArgs = {
force: boolean
stateOnly: boolean
mode: nacl.RoutingMode
regenerateSaltoIds: boolean
fromWorkspace?: string
fromEnv?: string
} & ServicesArg & EnvArg
export const action: WorkspaceCommandAction<FetchArgs> = async ({
input,
cliTelemetry,
config,
output,
spinnerCreator,
workspace,
}): Promise<CliExitCode> => {
const { force, stateOnly, services, mode, regenerateSaltoIds, fromWorkspace, fromEnv } = input
if (
[fromEnv, fromWorkspace].some(values.isDefined)
&& ![fromEnv, fromWorkspace].every(values.isDefined)
) {
errorOutputLine('The fromEnv and fromWorkspace arguments must both be provided.', output)
outputLine(EOL, output)
return CliExitCode.UserInputError
}
const { shouldCalcTotalSize } = config
await validateAndSetEnv(workspace, input, output)
const activeServices = getAndValidateActiveServices(workspace, services)
const stateRecencies = await Promise.all(
activeServices.map(service => workspace.getStateRecency(service))
)
// Print state recencies
outputLine(formatStateRecencies(stateRecencies), output)
const validWorkspace = await isValidWorkspaceForCommand(
{ workspace, cliOutput: output, spinnerCreator, force }
)
if (!validWorkspace) {
return CliExitCode.AppError
}
let useAlignMode = false
if (!force && mode !== 'align' && await shouldRecommendAlignMode(workspace, stateRecencies, activeServices)) {
const userChoice = await getChangeToAlignAction(mode, output)
if (userChoice === 'cancel operation') {
log.info('Canceling operation based on user input')
return CliExitCode.UserInputError
}
if (userChoice === 'yes') {
log.info(`Changing fetch mode from '${mode}' to 'align' based on user input`)
useAlignMode = true
}
log.info('Not changing fetch mode based on user input')
}
return fetchCommand({
workspace,
force,
cliTelemetry,
output,
fetch: fromWorkspace && fromEnv ? createFetchFromWorkspaceCommand(
fetchFromWorkspace,
fromWorkspace,
fromEnv
) : apiFetch,
getApprovedChanges: cliGetApprovedChanges,
shouldUpdateConfig: cliShouldUpdateConfig,
services: activeServices,
mode: useAlignMode ? 'align' : mode,
shouldCalcTotalSize,
stateOnly,
regenerateSaltoIds,
})
}
const fetchDef = createWorkspaceCommand({
properties: {
name: 'fetch',
description: 'Update the workspace configuration elements from the upstream services',
keyedOptions: [
{
name: 'force',
alias: 'f',
required: false,
description: 'Do not warn on conflicts with local changes',
type: 'boolean',
},
{
name: 'stateOnly',
alias: 'st',
required: false,
description: 'Update just the state file and not the NaCLs',
type: 'boolean',
},
SERVICES_OPTION,
ENVIRONMENT_OPTION,
{
name: 'mode',
alias: 'm',
required: false,
description: 'Choose a fetch mode. Options - [default, align]',
type: 'string',
// 'override' and 'isolated' are undocumented
choices: ['default', 'align', 'override', 'isolated'],
default: 'default',
},
{
name: 'regenerateSaltoIds',
alias: 'r',
required: false,
description: 'Regenerate configuration elements Salto IDs based on the current settings and fetch results',
type: 'boolean',
},
{
name: 'fromWorkspace',
alias: 'w',
required: false,
description: 'Fetch the data from another workspace at this path',
type: 'string',
},
{
name: 'fromEnv',
alias: 'we',
required: false,
description: 'Fetch the data from another workspace at this path from this env',
type: 'string',
},
],
},
action,
})
export default fetchDef | the_stack |
import UPlot, {
Options as UPlotOptions,
AlignedData as UPlotData,
Plugin,
Series,
DrawOrderKey,
SyncPubSub,
} from 'uplot';
import LegendPlugin from './plugins/legend/legend';
import tooltipPlugin, {TooltipPlugin} from './plugins/tooltip/tooltip';
import markersPlugin from './plugins/markers';
import cursorPlugin from './plugins/cursor/cursor';
import plotLinesPlugin, {PlotLinesPlugin} from './plugins/plotLines/plotLines';
import {
YagrConfig,
RawSerieData,
PlotLineConfig,
YagrHooks,
DataSeries,
MinimalValidConfig,
YagrTheme,
HookParams,
} from './types';
import {assignKeys, debounce, genId, getSumByIdx, preprocess} from './utils/common';
import {configureAxes, getRedrawOptionsForAxesUpdate, updateAxis} from './utils/axes';
import {getPaddingByAxes} from './utils/chart';
import ColorParser from './utils/colors';
import {configureSeries, UPDATE_KEYS} from './utils/series';
import ThemedDefaults, {
DEFAULT_X_SCALE,
DEFAULT_X_SERIE_NAME,
MIN_SELECTION_WIDTH,
DEFAULT_FOCUS_ALPHA,
DEFAULT_CANVAS_PIXEL_RATIO,
DEFAULT_Y_SCALE,
DEFAULT_SYNC_KEY,
DEFAULT_TITLE_FONT_SIZE,
} from './defaults';
import i18n from './locale';
import {configureScales} from './utils/scales';
export interface YagrEvent {
chart: Yagr;
meta: YagrMeta;
}
export type YagrMeta = {
renderTime: number;
processTime: number;
initTime: number;
};
type CachedProps = {
width: number;
height: number;
};
export interface YagrState {
isMouseOver: boolean;
stage: 'config' | 'processing' | 'uplot' | 'render' | 'listen';
inBatch?: boolean;
}
export interface UpdateOptions {
incremental?: boolean;
splice?: boolean;
}
/*
* Main core-module of Yagr.
* Implements data processing and autoconfigurable wrapper
* for uPlot chart.
* Entrypoint of every Yagr chart.
*/
class Yagr<TConfig extends MinimalValidConfig = MinimalValidConfig> {
id!: string;
options!: UPlotOptions;
uplot!: UPlot;
root!: HTMLElement;
series!: UPlotData;
config!: YagrConfig;
resizeOb?: ResizeObserver;
canvas!: HTMLCanvasElement;
plugins!: {
tooltip?: ReturnType<TooltipPlugin>;
plotLines?: ReturnType<PlotLinesPlugin>;
cursor?: ReturnType<typeof cursorPlugin>;
legend?: LegendPlugin;
} & (TConfig['plugins'] extends YagrConfig['plugins']
? {[key in keyof TConfig['plugins']]: ReturnType<TConfig['plugins'][key]>}
: {});
state!: YagrState;
utils!: {
colors: ColorParser;
sync?: SyncPubSub;
theme: ThemedDefaults;
i18n: ReturnType<typeof i18n>;
};
get isEmpty() {
return this._isEmptyDataSet;
}
private _startTime!: number;
private _meta: Partial<YagrMeta> = {};
private _cache!: CachedProps;
private _isEmptyDataSet = false;
private _y2uIdx: Record<string, number> = {};
private _batch: {fns: Function[]; recalc?: boolean} = {fns: []};
constructor(root: HTMLElement, pConfig: TConfig) {
this._startTime = performance.now();
this.state = {
isMouseOver: false,
stage: 'config',
};
const config: YagrConfig = Object.assign(
{
title: {},
data: [],
axes: {},
series: [],
scales: {},
hooks: {},
settings: {},
chart: {},
cursor: {},
plugins: {},
legend: {
show: false,
},
tooltip: {
show: true,
},
grid: null,
markers: {},
},
pConfig,
);
this.config = config;
this.inStage('config', () => {
this.id = root.id || genId();
this.root = root;
this.root.classList.add('yagr');
const colorParser = new ColorParser();
const sync = this.config.cursor.sync;
const chart = this.config.chart;
chart.series ||= {type: 'line'};
chart.size ||= {adaptive: true};
chart.appereance ||= {locale: 'en'};
chart.select ||= {};
this.utils = {
colors: colorParser,
i18n: i18n(config.chart.appereance?.locale || 'en'),
theme: new ThemedDefaults(colorParser),
};
colorParser.setContext(root);
if (sync) {
this.utils.sync = UPlot.sync(typeof sync === 'string' ? sync : DEFAULT_SYNC_KEY);
}
if (!chart.size.adaptive && chart.size.width && chart.size.height) {
root.style.width = chart.size.width + 'px';
root.style.height = chart.size.height + 'px';
}
this.setTheme(chart.appereance.theme || 'light');
const options = this.createUplotOptions();
this._cache = {height: options.height, width: options.width};
this.options = config.editUplotOptions ? config.editUplotOptions(options) : options;
this.plugins.legend = new LegendPlugin(this, config.legend);
})
.inStage('processing', () => {
const series = this.transformSeries();
this.series = series;
})
.inStage('uplot', () => {
this.uplot = new UPlot(this.options, this.series, this.initRender);
this.canvas = root.querySelector('canvas') as HTMLCanvasElement;
this.init();
const processTime = performance.now() - this._startTime;
this._meta.processTime = processTime;
this.execHooks(config.hooks.processed, {
chart: this,
meta: {
processTime,
},
});
})
.inStage('render');
}
/*
* Set's locale of chart and redraws all locale-dependent elements.
*/
setLocale(locale: string | Record<string, string>) {
this.wrapBatch(() => () => {
this.utils.i18n = i18n(locale);
this.plugins.legend?.redraw();
});
}
/**
* Set's theme of chart and redraws all theme-dependent elements.
*/
setTheme(themeValue: YagrTheme) {
this.utils.theme.setTheme(themeValue);
this.root.classList.remove('yagr_theme_dark');
this.root.classList.remove('yagr_theme_light');
this.root.classList.add('yagr_theme_' + themeValue);
if (!this.uplot) {
return;
}
this.wrapBatch(() => () => this.redraw(false, true));
}
/**
* Redraws Yagr instance by given options.
*/
redraw(series = true, axes = true) {
this.uplot.redraw(series, axes);
}
/**
* Get uPlot's Series from series id
*/
getSeriesById(id: string): Series {
return this.uplot.series[this._y2uIdx[id]];
}
setVisible(lineId: string | null, show: boolean) {
const seriesIdx = lineId === null ? null : this._y2uIdx[lineId];
const fns: Function[] = [];
if (seriesIdx === null) {
fns.push(() => {
/**
* @TODO Fix after bug in uPlot will be fixed
* @see https://github.com/leeoniya/uPlot/issues/680
*/
this.uplot.series.forEach((_, i) => {
i && this.uplot.setSeries(i, {show});
});
});
} else {
fns.push(() => {
this.uplot.setSeries(seriesIdx, {
show,
});
});
}
this.options.series = this.uplot.series;
let shouldRebuildStacks = false;
if (seriesIdx) {
const series = this.uplot.series[seriesIdx];
const scaleName = series.scale || DEFAULT_Y_SCALE;
const scale = this.config.scales[scaleName];
shouldRebuildStacks = Boolean(scale && scale.stacking);
} else {
shouldRebuildStacks = this.options.series.reduce((acc, {scale}) => {
return Boolean((scale && this.config.scales[scale]?.stacking) || acc);
}, false as boolean);
}
return this.wrapBatch(() => [fns, shouldRebuildStacks]);
}
setFocus(lineId: string | null, focus: boolean) {
this.wrapBatch(() => () => {
const seriesIdx = lineId === null ? null : this._y2uIdx[lineId];
this.plugins.cursor?.focus(seriesIdx, focus);
this.uplot.setSeries(seriesIdx, {focus});
});
}
dispose() {
this.resizeOb && this.resizeOb.unobserve(this.root);
this.unsubscribe();
this.uplot.destroy();
this.execHooks(this.config.hooks.dispose, {chart: this});
}
toDataUrl() {
return this.canvas.toDataURL('img/png');
}
subscribe() {
this.utils.sync?.sub(this.uplot);
}
unsubscribe() {
this.utils.sync?.unsub(this.uplot);
}
batch(fn: () => void) {
this.state.inBatch = true;
fn();
this.uplot.batch(() => {
this._batch.fns.forEach((f) => f());
if (this._batch.recalc) {
this.series = this.transformSeries();
this.uplot.setData(this.series, true);
}
});
this._batch = {fns: [], recalc: false};
this.state.inBatch = false;
}
setAxes(axes: YagrConfig['axes']) {
const {x, ...rest} = axes;
if (x) {
const xAxis = this.uplot.axes.find(({scale}) => scale === DEFAULT_X_SCALE);
if (xAxis) {
updateAxis(this, xAxis, {scale: DEFAULT_X_SCALE, ...x});
}
}
Object.entries(rest).forEach(([scaleName, scaleConfig]) => {
const axis = this.uplot.axes.find(({scale}) => scale === scaleName);
if (axis) {
updateAxis(this, axis, {scale: scaleName, ...scaleConfig});
}
});
this.redraw(...getRedrawOptionsForAxesUpdate(axes));
}
/** Incremental false */
setSeries(seriesId: string, series: Partial<RawSerieData>): void;
setSeries(seriesIdx: number, series: Partial<RawSerieData>): void;
setSeries(series: Partial<RawSerieData>[]): void;
/** Incremental depends on setting */
setSeries(timeline: number[], series: Partial<RawSerieData>[], options: UpdateOptions): void;
setSeries(
timelineOrSeriesOrId: Partial<RawSerieData>[] | number[] | number | string,
maybeSeries?: Partial<RawSerieData>[] | Partial<RawSerieData>,
options: UpdateOptions = {
incremental: true,
splice: false,
},
) {
this.wrapBatch(() => {
return this._setSeries(timelineOrSeriesOrId, maybeSeries, options);
});
}
/*
* Main config processing options
* Configures options, axess, grids, scales etc
*/
private createUplotOptions() {
const {config} = this;
const plugins: Plugin[] = [];
// @ts-ignore
this.plugins = {};
Object.entries(config.plugins).forEach(([name, plugin]) => {
const pluginInstance = plugin(this);
plugins.push(pluginInstance.uplot);
Object.assign(this.plugins, {[name]: pluginInstance});
});
const chart = config.chart;
/** Setting up TooltipPugin */
if (config.tooltip && config.tooltip.show !== false) {
const tooltipPluginInstance = tooltipPlugin(this, config.tooltip);
plugins.push(tooltipPluginInstance.uplot);
this.plugins.tooltip = tooltipPluginInstance;
}
const options: UPlotOptions = {
width: this.root.clientWidth,
height: this.clientHeight,
title: config.title?.text,
plugins: plugins,
focus: {alpha: DEFAULT_FOCUS_ALPHA},
series: [
{
id: DEFAULT_X_SERIE_NAME,
$c: config.timeline,
scale: DEFAULT_X_SCALE,
count: config.timeline.length,
} as Series,
],
ms: chart.timeMultiplier || 1,
hooks: config.hooks || {},
};
this._isEmptyDataSet =
config.timeline.length === 0 ||
config.series.length === 0 ||
config.series.every(({data}) => data.length === 0);
/**
* Setting up cursor - points on cursor, drag behavior, crosshairs
*/
options.cursor = options.cursor || {};
options.cursor.points = options.cursor.points || {};
options.cursor.drag = options.cursor.drag || {
dist: chart.select?.minWidth || MIN_SELECTION_WIDTH,
x: true,
y: false,
setScale: chart.select?.zoom ?? true,
};
if (this.utils.sync) {
options.cursor.sync = options.cursor.sync || {
key: this.utils.sync.key,
};
}
if (config.cursor) {
const cPlugin = cursorPlugin(this, config.cursor);
this.plugins.cursor = cPlugin;
plugins.push(cPlugin.uplot);
}
const seriesOptions = config.series || [];
const resultingSeriesOptions: Series[] = options.series;
/**
* Prepare series options
*/
for (let i = seriesOptions.length - 1; i >= 0; i--) {
const serie = configureSeries(this, seriesOptions[i] || {}, i);
const uIdx = resultingSeriesOptions.push(serie);
this._y2uIdx[serie.id || i] = uIdx - 1;
}
/** Setting up markers plugin after default points renderers to be settled */
const markersPluginInstance = markersPlugin(this, config);
plugins.push(markersPluginInstance);
options.series = resultingSeriesOptions;
if (!config.scales || Object.keys(config.scales).length === 0) {
config.scales = {
x: {},
y: {},
};
}
/** Setting up scales */
options.scales = options.scales || {};
options.scales = configureScales(this, options.scales, config);
/** Setting up minimal axes */
options.axes = options.axes || [];
const axes = options.axes;
axes.push(...configureAxes(this, config));
const plotLinesPluginInstance = this.initPlotLinesPlugin(config);
this.plugins.plotLines = plotLinesPluginInstance;
plugins.push(plotLinesPluginInstance.uplot);
/** Setting up hooks */
options.hooks = config.hooks || {};
options.hooks.draw = options.hooks.draw || [];
options.hooks.draw.push(() => {
if (this.state.stage === 'listen') {
return;
}
this.state.stage = 'listen';
this.execHooks(this.config.hooks.stage, {chart: this, stage: this.state.stage});
const renderTime = performance.now() - this._startTime;
this._meta.renderTime = renderTime;
this.execHooks(config.hooks.load, {
chart: this,
meta: this._meta as YagrMeta,
});
});
options.hooks.ready = options.hooks.ready || [];
options.hooks.ready.push(() => {
const initTime = performance.now() - this._startTime;
this._meta.initTime = initTime;
this.execHooks(config.hooks.inited, {
chart: this,
meta: {
initTime,
},
});
});
options.hooks.drawClear = options.hooks.drawClear || [];
options.hooks.drawClear.push((u: UPlot) => {
const {ctx} = u;
ctx.save();
ctx.fillStyle = this.utils.theme.BACKGROUND;
ctx.fillRect(
DEFAULT_CANVAS_PIXEL_RATIO,
DEFAULT_CANVAS_PIXEL_RATIO,
u.width * DEFAULT_CANVAS_PIXEL_RATIO - 2 * DEFAULT_CANVAS_PIXEL_RATIO,
u.height * DEFAULT_CANVAS_PIXEL_RATIO - 2 * DEFAULT_CANVAS_PIXEL_RATIO,
);
ctx.restore();
});
options.hooks.setSelect = options.hooks.setSelect || [];
options.hooks.setSelect.push((u: UPlot) => {
const {left, width} = u.select;
const [_from, _to] = [u.posToVal(left, DEFAULT_X_SCALE), u.posToVal(left + width, DEFAULT_X_SCALE)];
const {timeMultiplier = 1} = chart;
this.execHooks(config.hooks.onSelect, {
from: Math.ceil(_from / timeMultiplier),
to: Math.ceil(_to / timeMultiplier),
chart: this,
});
u.setSelect({width: 0, height: 0, top: 0, left: 0}, false);
});
options.drawOrder = chart.appereance?.drawOrder
? (chart.appereance?.drawOrder.filter(
(key) => key === DrawOrderKey.Series || key === DrawOrderKey.Axes,
) as DrawOrderKey[])
: [DrawOrderKey.Series, DrawOrderKey.Axes];
/** Disabling uPlot legend. */
options.legend = {show: false};
options.padding = config.chart.size?.padding || getPaddingByAxes(options);
this.options = options;
return options;
}
/*
* Main data processing function
* Transforms series values
*/
// eslint-disable-next-line complexity
private transformSeries() {
const result = [];
const config = this.config;
const timeline = config.timeline;
let processing = config.processing || false;
let series: DataSeries[] = this.config.series.map(({data}) => data) as DataSeries[];
if (processing && processing.interpolation) {
series = preprocess(series, timeline, processing);
processing = false;
}
const shouldMapNullValues = Boolean(processing && processing.nullValues);
const nullValues = (processing && processing.nullValues) || {};
/**
* Stacks are represented as:
* {
* [scale]: {
* [], // stacking group idx 0 (default for all on scale),
* [], // stacking group idx 1
* ]
* }
*
* All stacked points are accumulating inside of series' scale group
*/
const stacks: Record<string, number[][]> = {};
for (let sIdx = 0; sIdx < series.length; sIdx++) {
const dataLine: (number | null)[] = [];
const realSerieIdx = sIdx + 1;
const serie = series[sIdx];
const serieConfigIndex = this.options.series.length - realSerieIdx;
const serieOptions = this.options.series[serieConfigIndex];
const scale = serieOptions.scale || DEFAULT_Y_SCALE;
const scaleConfig = this.config.scales[scale] || {};
const isStacking = scaleConfig.stacking;
const sGroup = serieOptions.stackGroup || 0;
let empty = true;
if (isStacking && !stacks[scale]) {
this.options.focus = this.options.focus || {alpha: 1.1};
this.options.focus.alpha = 1.1;
stacks[scale] = [];
}
if (isStacking && !stacks[scale][sGroup]) {
stacks[scale][sGroup] = new Array(timeline.length).fill(0);
}
serieOptions.count = 0;
for (let idx = 0; idx < serie.length; idx++) {
let value = serie[idx];
if (shouldMapNullValues && nullValues[String(value)]) {
value = null;
}
if (serieOptions.transform) {
serieOptions._transformed = true;
value = serieOptions.transform(value, series, idx);
}
if (scaleConfig.transform) {
serieOptions._transformed = true;
value = scaleConfig.transform(value, series, idx);
}
if (value === null) {
if (serieOptions.type === 'line' || serieOptions.type === 'dots') {
dataLine.push(null);
continue;
} else {
value = 0;
}
}
empty = false;
if (scaleConfig.normalize) {
const sum = getSumByIdx(series, this.options.series, idx, scale);
value = sum && (value / sum) * (scaleConfig.normalizeBase || 100);
serieOptions.normalizedData = serieOptions.normalizedData || [];
serieOptions.normalizedData[idx] = value;
}
if (scaleConfig.stacking) {
if (serieOptions.show === false) {
value = 0;
}
value = stacks[scale][sGroup][idx] += value;
}
if (scaleConfig.type === 'logarithmic' && value === 0) {
value = 1;
}
serieOptions.sum = (serieOptions.sum || 0) + (value || 0);
serieOptions.count += 1;
dataLine.push(value);
}
serieOptions.avg = (serieOptions.sum || 0) / serieOptions.count;
serieOptions.empty = empty;
result.unshift(dataLine);
}
result.unshift(this.config.timeline);
return result as UPlotData;
}
private onError(error: Error) {
this.execHooks(this.config.hooks.error, {
stage: this.state.stage,
error,
chart: this,
});
return error;
}
private initPlotLinesPlugin(config: YagrConfig) {
const plotLines: PlotLineConfig[] = [];
/** Collecting plot lines from config axes for plotLines plugin */
Object.entries(config.axes).forEach(([scale, axisConfig]) => {
if (axisConfig.plotLines) {
axisConfig.plotLines.forEach((plotLine) => {
plotLines.push({...plotLine, scale});
});
}
});
return plotLinesPlugin(this, plotLines);
}
/*
* Resize handler. Should cache height and width to avoid unneccesary resize handling,
* when actial width and height of contentRect doesn't changed
*/
private onResize = (args: ResizeObserverEntry[]) => {
const [resize] = args;
if (this._cache.height === resize.contentRect.height && this._cache.width === resize.contentRect.width) {
return;
}
if (this.plugins.tooltip) {
const t = this.plugins.tooltip;
if (t.state.pinned && t.state.visible) {
t.hide();
t.pin(false);
}
}
this._cache.width = this.options.width = this.root.clientWidth;
this._cache.height = this.options.height = this.clientHeight;
this.plugins?.legend?.redraw();
this.uplot.setSize({
width: this.options.width,
height: this.options.height,
});
this.uplot.redraw();
this.execHooks(this.config.hooks.resize, {entries: args, chart: this});
};
private init = () => {
if (this.config.chart.size?.adaptive) {
this.resizeOb = new ResizeObserver(debounce(this.onResize, this.config.chart.size.resizeDebounceMs || 100));
this.resizeOb.observe(this.root);
}
if (!this.config.hooks.dispose) {
this.config.hooks.dispose = [];
}
/** Unsubscribe in init required to avoid chars been synced without action from developer */
this.unsubscribe();
this.config.hooks.dispose.push(this.trackMouse());
};
private execHooks = <T extends YagrHooks[keyof YagrHooks]>(hooks: T, ...args: HookParams<T>) => {
if (Array.isArray(hooks)) {
hooks.forEach((hook) => {
if (!hook) {
return;
}
// @ts-ignore
typeof hook === 'function' && hook(...args);
});
}
};
private inStage(stage: YagrState['stage'], fn?: () => void) {
this.state.stage === stage;
this.execHooks(this.config.hooks.stage, {chart: this, stage});
try {
fn && fn();
} catch (error) {
this.onError(error as Error);
}
return this;
}
private trackMouse() {
const mouseOver = () => {
this.state.isMouseOver = true;
};
const mouseLeave = () => {
this.state.isMouseOver = false;
};
this.root.addEventListener('mouseover', mouseOver);
this.root.addEventListener('mouseleave', mouseLeave);
return () => {
this.root.removeEventListener('mouseover', mouseOver);
this.root.removeEventListener('mouseleave', mouseLeave);
};
}
private initRender = (u: uPlot, done: Function) => {
/** Init legend if required */
this.plugins.legend?.init(u);
/** Setup font size for title if required */
if (this.config.title && this.config.title.fontSize) {
const size = this.config.title.fontSize;
const t = this.root.querySelector('.u-title') as HTMLElement;
t.setAttribute('style', `font-size:${size}px;line-height:${size}px;`);
}
done();
};
private wrapBatch(batchFn: (() => [Function | Function[], boolean]) | (() => Function)) {
const res = batchFn();
const [fnsOrFn, shouldRecalc] = Array.isArray(res) ? res : [res, false];
const fns = Array.isArray(fnsOrFn) ? fnsOrFn : [fnsOrFn];
if (this.state.inBatch) {
this._batch.fns.push(...fns);
this._batch.recalc = shouldRecalc;
} else {
this.uplot.batch(() => {
fns.forEach((fn) => fn());
if (shouldRecalc) {
this.series = this.transformSeries();
this.uplot.setData(this.series, true);
}
});
}
}
private _setSeries(
timelineOrSeriesOrId: Partial<RawSerieData>[] | number[] | number | string,
maybeSeries?: Partial<RawSerieData>[] | Partial<RawSerieData>,
options: UpdateOptions = {
incremental: true,
splice: false,
},
): [Function[], boolean] {
let timeline: number[] = [],
series: RawSerieData[] = [],
updateId: null | string | number = null,
useIncremental = false,
shouldRecalcData = false,
useFullyRedraw;
if (['number', 'string'].includes(typeof timelineOrSeriesOrId)) {
useIncremental = false;
useFullyRedraw = false;
series = [maybeSeries] as RawSerieData[];
updateId = timelineOrSeriesOrId as number | string;
} else if (typeof (timelineOrSeriesOrId as Array<number | RawSerieData>)[0] === 'number') {
timeline = timelineOrSeriesOrId as number[];
series = maybeSeries as RawSerieData[];
useIncremental = Boolean(options.incremental);
useFullyRedraw = !options.incremental;
} else {
series = timelineOrSeriesOrId as RawSerieData[];
useFullyRedraw = true;
}
const updateFns: (() => void)[] = [];
if (useFullyRedraw === false) {
let shouldUpdateCursror = false;
useIncremental && this.config.timeline.push(...timeline);
series.forEach((serie) => {
let matched =
typeof updateId === 'number'
? this.config.series[0]
: this.config.series.find(({id}) => id === serie.id || id === updateId);
let id: number | string | undefined = matched?.id;
if (typeof updateId === 'number' && this._y2uIdx[updateId]) {
matched = this.config.series[updateId];
id = updateId;
}
if (matched && id) {
const {data, ...rest} = serie;
const seriesIdx = this._y2uIdx[id];
if (useIncremental) {
matched.data = data ? matched.data.concat(data) : matched.data;
} else if (data?.length) {
matched.data = data;
shouldRecalcData = true;
}
const newSeries = configureSeries(this, Object.assign(matched, rest), seriesIdx);
const opts = this.options.series[seriesIdx];
const uOpts = this.uplot.series[seriesIdx];
if (uOpts.show !== newSeries.show) {
updateFns.push(() => {
this.uplot.setSeries(seriesIdx, {show: newSeries.show});
});
}
if (uOpts._focus === null ? true : uOpts._focus !== newSeries.focus) {
updateFns.push(() => {
this.uplot.setSeries(seriesIdx, {focus: newSeries.focus});
});
}
if (uOpts.color !== newSeries.color) {
shouldUpdateCursror = true;
}
if (newSeries.scale && this.config.scales[newSeries.scale]?.stacking) {
shouldRecalcData = true;
}
assignKeys(UPDATE_KEYS, opts, newSeries);
assignKeys(UPDATE_KEYS, uOpts, newSeries);
} else {
updateFns.push(() => {
const newSeries = configureSeries(this, serie, this.config.series.length);
this._y2uIdx[newSeries.id] = this.uplot.series.length;
this.uplot.addSeries(newSeries, this.config.series.length);
});
this.config.series.push(serie);
}
});
if (shouldUpdateCursror) {
updateFns.push(() => {
this.plugins.cursor?.updatePoints();
});
}
if (options.splice) {
const sliceLength = series[0].data.length;
this.config.series.forEach((s) => {
s.data.splice(0, sliceLength);
});
this.config.timeline.splice(0, timeline.length);
}
} else {
this.inStage('config', () => {
this.config.series = series;
this.config.timeline = timeline;
const uplotOptions = this.createUplotOptions();
this._cache = {height: uplotOptions.height, width: uplotOptions.width};
this.options = this.config.editUplotOptions ? this.config.editUplotOptions(uplotOptions) : uplotOptions;
})
.inStage('processing', () => {
const newSeries = this.transformSeries();
this.series = newSeries;
this.dispose();
})
.inStage('uplot', () => {
this.uplot = new UPlot(this.options, this.series, this.initRender);
this.init();
})
.inStage('listen');
}
if (timeline.length) {
const newData = this.transformSeries();
updateFns.push(() => {
this.uplot.setData(newData);
});
}
return [updateFns, shouldRecalcData];
}
private get clientHeight() {
const MARGIN = 8;
const offset = this.config.title.text ? (this.config.title.fontSize || DEFAULT_TITLE_FONT_SIZE) + MARGIN : 0;
return this.root.clientHeight - offset;
}
}
export default Yagr; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { AccessPolicies } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { VideoAnalyzerManagementClient } from "../videoAnalyzerManagementClient";
import {
AccessPolicyEntity,
AccessPoliciesListNextOptionalParams,
AccessPoliciesListOptionalParams,
AccessPoliciesListResponse,
AccessPoliciesGetOptionalParams,
AccessPoliciesGetResponse,
AccessPoliciesCreateOrUpdateOptionalParams,
AccessPoliciesCreateOrUpdateResponse,
AccessPoliciesDeleteOptionalParams,
AccessPoliciesUpdateOptionalParams,
AccessPoliciesUpdateResponse,
AccessPoliciesListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing AccessPolicies operations. */
export class AccessPoliciesImpl implements AccessPolicies {
private readonly client: VideoAnalyzerManagementClient;
/**
* Initialize a new instance of the class AccessPolicies class.
* @param client Reference to the service client
*/
constructor(client: VideoAnalyzerManagementClient) {
this.client = client;
}
/**
* Retrieves all existing access policy resources, along with their JSON representations.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName The Azure Video Analyzer account name.
* @param options The options parameters.
*/
public list(
resourceGroupName: string,
accountName: string,
options?: AccessPoliciesListOptionalParams
): PagedAsyncIterableIterator<AccessPolicyEntity> {
const iter = this.listPagingAll(resourceGroupName, accountName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(resourceGroupName, accountName, options);
}
};
}
private async *listPagingPage(
resourceGroupName: string,
accountName: string,
options?: AccessPoliciesListOptionalParams
): AsyncIterableIterator<AccessPolicyEntity[]> {
let result = await this._list(resourceGroupName, accountName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(
resourceGroupName,
accountName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
resourceGroupName: string,
accountName: string,
options?: AccessPoliciesListOptionalParams
): AsyncIterableIterator<AccessPolicyEntity> {
for await (const page of this.listPagingPage(
resourceGroupName,
accountName,
options
)) {
yield* page;
}
}
/**
* Retrieves all existing access policy resources, along with their JSON representations.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName The Azure Video Analyzer account name.
* @param options The options parameters.
*/
private _list(
resourceGroupName: string,
accountName: string,
options?: AccessPoliciesListOptionalParams
): Promise<AccessPoliciesListResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listOperationSpec
);
}
/**
* Retrieves an existing access policy resource with the given name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName The Azure Video Analyzer account name.
* @param accessPolicyName The Access Policy name.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
accountName: string,
accessPolicyName: string,
options?: AccessPoliciesGetOptionalParams
): Promise<AccessPoliciesGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, accessPolicyName, options },
getOperationSpec
);
}
/**
* Creates a new access policy resource or updates an existing one with the given name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName The Azure Video Analyzer account name.
* @param accessPolicyName The Access Policy name.
* @param parameters The request parameters
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
accountName: string,
accessPolicyName: string,
parameters: AccessPolicyEntity,
options?: AccessPoliciesCreateOrUpdateOptionalParams
): Promise<AccessPoliciesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, accessPolicyName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Deletes an existing access policy resource with the given name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName The Azure Video Analyzer account name.
* @param accessPolicyName The Access Policy name.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
accountName: string,
accessPolicyName: string,
options?: AccessPoliciesDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, accessPolicyName, options },
deleteOperationSpec
);
}
/**
* Updates individual properties of an existing access policy resource with the given name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName The Azure Video Analyzer account name.
* @param accessPolicyName The Access Policy name.
* @param parameters The request parameters
* @param options The options parameters.
*/
update(
resourceGroupName: string,
accountName: string,
accessPolicyName: string,
parameters: AccessPolicyEntity,
options?: AccessPoliciesUpdateOptionalParams
): Promise<AccessPoliciesUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, accessPolicyName, parameters, options },
updateOperationSpec
);
}
/**
* ListNext
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName The Azure Video Analyzer account name.
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
resourceGroupName: string,
accountName: string,
nextLink: string,
options?: AccessPoliciesListNextOptionalParams
): Promise<AccessPoliciesListNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/accessPolicies",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AccessPolicyEntityCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.top],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/accessPolicies/{accessPolicyName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AccessPolicyEntity
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.accessPolicyName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/accessPolicies/{accessPolicyName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.AccessPolicyEntity
},
201: {
bodyMapper: Mappers.AccessPolicyEntity
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters13,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.accessPolicyName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/accessPolicies/{accessPolicyName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.accessPolicyName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/accessPolicies/{accessPolicyName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.AccessPolicyEntity
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters13,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.accessPolicyName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AccessPolicyEntityCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.top],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { ChangeLogItem, ChangeLogKind, ContentProvider, Header, Image, Sponsor, IssueKind, SupportChannel, SponsorProvider, SocialMediaProvider } from "../../vscode-whats-new/src/ContentProvider";
export class ProjectManagerContentProvider implements ContentProvider {
public provideHeader(logoUrl: string): Header {
return <Header> {logo: <Image> {src: logoUrl, height: 50, width: 50},
message: `<b>Project Manager</b> helps you to easily access your <b>projects</b>,
no matter where they are located. <i>Don't miss those important projects anymore</i>.
<br><br>You can define your own <b>Projects</b> (also called <b>Favorites</b>), or choose
for auto-detect <b>Git</b>, <b>Mercurial</b> or <b>SVN</b> repositories, <b>VSCode</b>
folders or <b>any</b> other folder.`};
}
public provideChangeLog(): ChangeLogItem[] {
const changeLog: ChangeLogItem[] = [];
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.4.0", releaseDate: "August 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Adds <b>View as</b> option to Favorites View",
id: 484,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Adds <b>Sort by</b> option to Favorites View",
id: 484,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Adds setting to display the parent folder on duplicate (same-name) projects",
id: 306,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.CHANGED,
detail: {
message: "Side Bar tooltips now in Markdown",
id: 540,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.CHANGED,
detail: {
message: "Side Bar following <b>sortList</b> setting",
id: 366,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Typos in README",
id: 532,
kind: IssueKind.PR,
kudos: "@kant"
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.3.0", releaseDate: "June 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Organize your projects with <b>Tags</b>",
id: 50,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Documentation about how to use the extension on Remote Development",
id: 477,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Use specific icons for each kind of remote project",
id: 483,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.2.0", releaseDate: "May 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>Virtual Workspaces</b>",
id: 500,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>Workspace Trust</b>",
id: 499,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>.code-workspace</b> projects located on remotes",
id: 486,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Favorite projects missing icons for Folders when using None or Seti Icon Theme",
id: 496,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: lodash",
id: 503,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: ssri",
id: 495,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.1.0", releaseDate: "March 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Save GitHub Codespaces projects always as \"remote project\"",
id: 479,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.CHANGED,
detail: {
message: "Do not show welcome message if installed by Settings Sync",
id: 459,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Mercurial projects not found",
id: 438,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Update whats-new submodule API",
id: 456,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Add badages to Readme",
id: 359,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: y18n",
id: 482,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: elliptic",
id: 472,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.0.0", releaseDate: "November 2020" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Adds <b>Open Settings</b> command to the Side Bar",
id: 434,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Concatenates the \"Number of Projects\" on each Panel in the Side Bar",
id: 267,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Adds <b>Reveal in Finder/Explorer</b> command in the Side Bar's context menu",
id: 322,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Adds setting to decide if auto-detected projects should ignore projects found inside other projects",
id: 189,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Use <b>vscode-ext-help-and-feedback</b> package",
id: 432,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "11.3.0", releaseDate: "September 2020" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>$home</b> and <b>\"~\" (tilde)</b> symbol on projectLocation setting",
id: 384,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>~</b> (tilde) symbol on any path related setting",
id: 414,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>glob</b> patterns in <b>ignoredFolders</b> settings",
id: 278,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Czech - Simplified Chinese",
id: 412,
kind: IssueKind.PR,
kudos: "@Amereyeu"
}
});
return changeLog;
}
public provideSupportChannels(): SupportChannel[] {
const supportChannels: SupportChannel[] = [];
supportChannels.push({
title: "Become a sponsor on Patreon",
link: "https://www.patreon.com/alefragnani",
message: "Become a Sponsor"
});
supportChannels.push({
title: "Donate via PayPal",
link: "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=EP57F3B6FXKTU&lc=US&item_name=Alessandro%20Fragnani&item_number=vscode%20extensions¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted",
message: "Donate via PayPal"
});
return supportChannels;
}
}
export class ProjectManagerSponsorProvider implements SponsorProvider {
public provideSponsors(): Sponsor[] {
const sponsors: Sponsor[] = [];
const sponsorCodeStream: Sponsor = <Sponsor> {
title: "Learn more about CodeStream",
link: "https://sponsorlink.codestream.com/?utm_source=vscmarket&utm_campaign=projectmanager&utm_medium=banner",
image: {
dark: "https://alt-images.codestream.com/codestream_logo_projectmanager.png",
light: "https://alt-images.codestream.com/codestream_logo_projectmanager.png"
},
width: 35,
message: `<p>Eliminate context switching and costly distractions.
Create and merge PRs and perform code reviews from inside your
IDE while using jump-to-definition, your keybindings, and other IDE favorites.</p>`,
extra:
`<a title="Learn more about CodeStream" href="https://sponsorlink.codestream.com/?utm_source=vscmarket&utm_campaign=projectmanager&utm_medium=banner">
Learn more</a>`
};
sponsors.push(sponsorCodeStream);
return sponsors
}
}
export class ProjectManagerSocialMediaProvider implements SocialMediaProvider {
public provideSocialMedias() {
return [{
title: "Follow me on Twitter",
link: "https://www.twitter.com/alefragnani"
}];
}
} | the_stack |
'use strict';
import {TPromise} from 'vs/base/common/winjs.base';
import {WorkbenchShell, enableBrowserHack, BrowserHack} from 'vs/workbench/electron-browser/shell';
import {IOptions} from 'vs/workbench/common/options';
import {domContentLoaded} from 'vs/base/browser/dom';
import errors = require('vs/base/common/errors');
import platform = require('vs/base/common/platform');
import paths = require('vs/base/common/paths');
import timer = require('vs/base/common/timer');
import {assign} from 'vs/base/common/objects';
import uri from 'vs/base/common/uri';
import strings = require('vs/base/common/strings');
import {IResourceInput} from 'vs/platform/editor/common/editor';
import {EventService} from 'vs/platform/event/common/eventService';
import {LegacyWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService';
import {IWorkspace} from 'vs/platform/workspace/common/workspace';
import {WorkspaceConfigurationService} from 'vs/workbench/services/configuration/node/configurationService';
import {Github, Repository, Error as GithubError, UserInfo} from 'github';
import {GithubService, IGithubService} from 'ghedit/githubService';
import {IProcessEnvironment} from 'vs/code/electron-main/env';
import {ParsedArgs} from 'vs/code/node/argv';
// DESKTOP: import {realpath} from 'vs/base/node/pfs';
// DESKTOP: import {EnvironmentService} from 'vs/platform/environment/node/environmentService';
import {IEnvironmentService} from 'vs/platform/environment/common/environment';
// DESKTOP: import {IEnvService} from 'vs/code/electron-main/env';
// DESKTOP: import {IProductConfiguration} from 'vs/platform/product';
// DESKTOP: import path = require('path');
var path = {
normalize: function (_path) {
console.log('path.normalize(\'' + _path + '\')');
return _path;
},
basename: function (_path) {
console.log('path.basename(\'' + _path + '\')');
return _path;
}
};
// TODO: import fs = require('fs');
var fs = {
realpathSync: function (_path) {
console.log('fs.realpathSync(\'' + _path + '\')');
return _path;
}
};
// DESKTOP: import gracefulFs = require('graceful-fs');
// DESKTOP: gracefulFs.gracefulify(fs); // enable gracefulFs
const timers = (<any>window).MonacoEnvironment.timers;
export interface IPath {
filePath: string;
lineNumber?: number;
columnNumber?: number;
}
// TODO: Perhaps move these into IEnvironment? Then accessing them would be easier from IConfiguration.
export interface IWindowConfiguration extends ParsedArgs {
appRoot: string;
execPath: string;
userEnv: IProcessEnvironment;
workspacePath?: string;
filesToOpen?: IPath[];
filesToCreate?: IPath[];
filesToDiff?: IPath[];
extensionsToInstall?: string[];
github?: Github;
githubRepo?: string;
githubBranch?: string;
githubTag?: string;
gistRegEx?: RegExp;
rootPath?: string;
buildType?: string;
readOnly?: boolean;
}
class EnvironmentService implements IEnvironmentService {
// IEnvironmentService implementation
_serviceBrand = null;
execPath = '';
appRoot = '';
userHome = '';
userDataPath = '';
appSettingsHome = '';
appSettingsPath = '';
appKeybindingsPath = '';
disableExtensions = true;
extensionsPath = '';
extensionDevelopmentPath = '';
extensionTestsPath = '';
debugExtensionHost = { port: 0, break: false };
logExtensionHostCommunication = false;
isBuilt = false;
verbose = false;
performance = false;
mainIPCHandle = '';
sharedIPCHandle = '';
// IEnvService implementation (overlaps with IEnvironmentService)
cliArgs = null;
product = {
nameShort: 'GHEdit',
nameLong: 'GHEdit',
applicationName: 'applicationName',
win32AppUserModelId: 'win32AppUserModelId',
win32MutexName: 'win32MutexName',
darwinBundleIdentifier: 'darwinBundleIdentifier',
urlProtocol: 'urlProtocol',
dataFolderName: 'dataFolderName',
downloadUrl: 'downloadUrl',
// updateUrl?: string;
// quality?: string;
commit: 'commit',
date: 'date',
extensionsGallery: {
serviceUrl: 'extensionsGallery.surviceUrl',
itemUrl: 'extensionsGallery.itemUrl',
},
extensionTips: null,
extensionImportantTips: null,
crashReporter: null,
welcomePage: 'welcomePage',
enableTelemetry: false,
aiConfig: {
key: 'aiConfig.key',
asimovKey: 'aiConfig.asmiovKey'
},
sendASmile: {
reportIssueUrl: 'sendASmile.reportIssueUrl',
requestFeatureUrl: 'sendASmile.requestFeatureUrl'
},
documentationUrl: 'https://spiffcode.github.io/ghedit/documentation.html',
releaseNotesUrl: 'https://spiffcode.github.io/ghedit/releasenotes.html',
twitterUrl: null,
requestFeatureUrl: 'https://github.com/spiffcode/ghedit/labels/feedback',
reportIssueUrl: 'https://github.com/spiffcode/ghedit/issues?q=is%3Aissue%20is%3Aopen%20-label%3Afeedback',
licenseUrl: 'https://github.com/spiffcode/ghedit/blob/master/LICENSE.txt',
privacyStatementUrl: null,
npsSurveyUrl: null,
// GHEdit fields
sendFeedbackUrl: 'https://github.com/spiffcode/ghedit/issues/new?labels=feedback'
};
updateUrl = '';
quality = '';
currentWorkingDirectory = '';
appHome = '';
constructor(environment: IWindowConfiguration) {
assign(this, environment);
}
}
export function startup(configuration: IWindowConfiguration): TPromise<void> {
// Shell Options
const filesToOpen = configuration.filesToOpen && configuration.filesToOpen.length ? toInputs(configuration.filesToOpen) : null;
const filesToCreate = configuration.filesToCreate && configuration.filesToCreate.length ? toInputs(configuration.filesToCreate) : null;
const filesToDiff = configuration.filesToDiff && configuration.filesToDiff.length ? toInputs(configuration.filesToDiff) : null;
const shellOptions: IOptions = {
filesToOpen,
filesToCreate,
filesToDiff,
extensionsToInstall: configuration.extensionsToInstall
};
if (configuration.performance) {
timer.ENABLE_TIMER = true;
}
var options = {};
if (configuration.userEnv['githubToken']) {
options['token'] = configuration.userEnv['githubToken'];
} else if (configuration.userEnv['githubUsername'] && configuration.userEnv['githubPassword']) {
options['username'] = configuration.userEnv['githubUsername'];
options['password'] = configuration.userEnv['githubPassword'];
}
let githubService = new GithubService(options);
// TODO: indeterminate progress indicator
return githubService.authenticateUser().then((userInfo: UserInfo) => {
if (!configuration.githubRepo)
// Open workbench without a workspace.
return openWorkbench(configuration, null, shellOptions, githubService);
return githubService.openRepository(configuration.githubRepo, configuration.githubBranch ? configuration.githubBranch : configuration.githubTag, !configuration.githubBranch).then((repoInfo: any) => {
// Tags aren't editable.
if (!configuration.githubBranch)
configuration.readOnly = true;
return getWorkspace(configuration, repoInfo).then(workspace => {
return openWorkbench(configuration, workspace, shellOptions, githubService);
}, (err: Error) => {
// TODO: Welcome experience and/or error message (invalid repo, permissions, ...)
// Open workbench without a workspace.
return openWorkbench(configuration, null, shellOptions, githubService);
});
});
}, (err: Error) => {
// No user credentials or otherwise unable to authenticate them.
// TODO: Welcome experience and/or error message (bad credentials, ...)
// Open workbench without a workspace.
return openWorkbench(configuration, null, shellOptions, githubService);
});
}
function toInputs(paths: IPath[]): IResourceInput[] {
return paths.map(p => {
const input = <IResourceInput>{
resource: uri.file(p.filePath)
};
if (p.lineNumber) {
input.options = {
selection: {
startLineNumber: p.lineNumber,
startColumn: p.columnNumber
}
};
}
return input;
});
}
function getWorkspace(configuration: IWindowConfiguration, repoInfo: any): TPromise<IWorkspace> {
if (!configuration.workspacePath) {
return TPromise.as(null);
}
let workspaceResource = uri.file(configuration.workspacePath);
let workspace: IWorkspace = {
'resource': workspaceResource,
'name': configuration.githubRepo.split('/')[1], // Repository name minus the user name.
'uid': Date.parse(repoInfo.created_at)
};
return TPromise.as(workspace);
}
function openWorkbench(environment: IWindowConfiguration, workspace: IWorkspace, options: IOptions, githubService: IGithubService): TPromise<void> {
const eventService = new EventService();
// DESKTOP: const environmentService = new EnvironmentService(environment, environment.execPath);
const environmentService = new EnvironmentService(environment);
const contextService = new LegacyWorkspaceContextService(workspace, options);
const configurationService = new WorkspaceConfigurationService(contextService, eventService, environmentService, githubService);
// Since the configuration service is one of the core services that is used in so many places, we initialize it
// right before startup of the workbench shell to have its data ready for consumers
return configurationService.initialize().then(() => {
timers.beforeReady = new Date();
return domContentLoaded().then(() => {
timers.afterReady = new Date();
// Enable browser specific hacks
enableBrowserHack(BrowserHack.EDITOR_MOUSE_CLICKS);
enableBrowserHack(BrowserHack.MESSAGE_BOX_TEXT);
enableBrowserHack(BrowserHack.TAB_LABEL);
// Open Shell
const beforeOpen = new Date();
const shell = new WorkbenchShell(document.body, workspace, {
configurationService,
eventService,
contextService,
environmentService,
githubService
}, options);
shell.open();
shell.joinCreation().then(() => {
timer.start(timer.Topic.STARTUP, 'Open Shell, Viewlet & Editor', beforeOpen, 'Workbench has opened after this event with viewlet and editor restored').stop();
});
// Inform user about loading issues from the loader
(<any>self).require.config({
onError: (err: any) => {
if (err.errorCode === 'load') {
shell.onUnexpectedError(errors.loaderError(err));
}
}
});
});
});
} | the_stack |
import {
OnAfterSettingsUpdateTopicParams,
OnBeforeSettingsUpdateTopicParams,
PageBuilderContextObject,
PageBuilderStorageOperations,
PageSpecialType,
PbContext,
Settings,
SettingsCrud,
SettingsStorageOperationsCreateParams,
SettingsStorageOperationsGetParams,
SettingsUpdateTopicMetaParams
} from "~/types";
import { NotAuthorizedError } from "@webiny/api-security";
import { DefaultSettingsModel } from "~/utils/models";
import mergeWith from "lodash/mergeWith";
import WebinyError from "@webiny/error";
import lodashGet from "lodash/get";
import DataLoader from "dataloader";
import { createTopic } from "@webiny/pubsub";
interface SettingsParams {
tenant: false | string | undefined;
locale: false | string | undefined;
type: string;
}
interface SettingsParamsInput extends SettingsParams {
getLocaleCode: () => string;
getTenantId: () => string;
}
/**
* Possible types of settings.
* If a lot of types should be added maybe we can do it via the plugin.
*/
enum SETTINGS_TYPE {
DEFAULT = "default"
}
const checkBasePermissions = async (context: PbContext) => {
await context.i18n.checkI18NContentPermission();
const pbPagePermission = await context.security.getPermission("pb.settings");
if (!pbPagePermission) {
throw new NotAuthorizedError();
}
};
const createSettingsParams = (params: SettingsParamsInput): SettingsParams => {
const {
tenant: initialTenant,
locale: initialLocale,
type,
getLocaleCode,
getTenantId
} = params;
/**
* If tenant or locale are false, it means we want global settings.
*/
const tenant = initialTenant === false ? false : initialTenant || getTenantId();
const locale = initialLocale === false ? false : initialLocale || getLocaleCode();
return {
type,
tenant,
locale
};
};
export interface CreateSettingsCrudParams {
context: PbContext;
storageOperations: PageBuilderStorageOperations;
getTenantId: () => string;
getLocaleCode: () => string;
}
export const createSettingsCrud = (params: CreateSettingsCrudParams): SettingsCrud => {
const { context, storageOperations, getLocaleCode, getTenantId } = params;
const settingsDataLoader = new DataLoader<SettingsParams, Settings | null, string>(
async keys => {
const promises = keys.map(key => {
const params: SettingsStorageOperationsGetParams = {
where: createSettingsParams({
...key,
getLocaleCode,
getTenantId
})
};
return storageOperations.settings.get(params);
});
return await Promise.all(promises);
},
{
cacheKeyFn: (key: SettingsParams) => {
return [`T#${key.tenant}`, `L#${key.locale}`, `TYPE#${key.type}`].join("#");
}
}
);
const onBeforeSettingsUpdate = createTopic<OnBeforeSettingsUpdateTopicParams>();
const onAfterSettingsUpdate = createTopic<OnAfterSettingsUpdateTopicParams>();
return {
onBeforeSettingsUpdate,
onAfterSettingsUpdate,
/**
* For the cache key we use the identifier created by the storage operations.
* Initial, in the DynamoDB, it was PK + SK. It can be what ever
*/
getSettingsCacheKey(options) {
const tenant = options ? options.tenant : null;
const locale = options ? options.locale : null;
return storageOperations.settings.createCacheKey(
options || {
tenant: tenant === false ? false : tenant || getTenantId(),
locale: locale === false ? false : locale || getLocaleCode()
}
);
},
async getCurrentSettings(this: PageBuilderContextObject) {
// With this line commented, we made this endpoint public.
// We did this because of the public website pages which need to access the settings.
// It's possible we'll create another GraphQL field, made for this exact purpose.
// auth !== false && (await checkBasePermissions(context));
const current = await this.getSettings({
tenant: getTenantId(),
locale: getLocaleCode()
});
const defaults = await this.getDefaultSettings();
return mergeWith({}, defaults, current, (prev, next) => {
// No need to use falsy value if we have it set in the default settings.
if (prev && !next) {
return prev;
}
});
},
async getSettings(this: PageBuilderContextObject, options) {
// With this line commented, we made this endpoint public.
// We did this because of the public website pages which need to access the settings.
// It's possible we'll create another GraphQL field, made for this exact purpose.
// auth !== false && (await checkBasePermissions(context));
const { locale = undefined, tenant = undefined } = options || {};
const params = createSettingsParams({
locale,
tenant,
type: SETTINGS_TYPE.DEFAULT,
getLocaleCode,
getTenantId
});
const key = {
tenant: params.tenant,
locale: params.locale,
type: params.type
};
try {
return await settingsDataLoader.load(key);
} catch (ex) {
throw new WebinyError(
ex.message || "Could not get settings by given parameters.",
ex.code || "GET_SETTINGS_ERROR",
key
);
}
},
async getDefaultSettings(this: PageBuilderContextObject, options) {
const allTenants = await this.getSettings({
tenant: false,
locale: false
});
const tenantAllLocales = await this.getSettings({
tenant: options ? options.tenant : undefined,
locale: false
});
if (!allTenants && !tenantAllLocales) {
return null;
}
return mergeWith({}, allTenants, tenantAllLocales, (next, prev) => {
// No need to use falsy value if we have it set in the default settings.
if (prev && !next) {
return prev;
}
});
},
async updateSettings(this: PageBuilderContextObject, rawData, options) {
if (!options) {
options = {
tenant: getTenantId(),
locale: getLocaleCode()
};
}
options.auth !== false && (await checkBasePermissions(context));
const params = createSettingsParams({
tenant: options.tenant,
locale: options.locale,
type: SETTINGS_TYPE.DEFAULT,
getLocaleCode,
getTenantId
});
let original = (await this.getSettings(options)) as Settings;
if (!original) {
original = await new DefaultSettingsModel().populate({}).toJSON();
const data: SettingsStorageOperationsCreateParams = {
input: rawData,
settings: {
...original,
...params
}
};
try {
original = await storageOperations.settings.create(data);
/**
* Clear the cache of the data loader.
*/
settingsDataLoader.clearAll();
} catch (ex) {
throw new WebinyError(
ex.message || "Could not create settings record.",
ex.code || "CREATE_SETTINGS_ERROR",
data
);
}
}
const settingsModel = new DefaultSettingsModel().populate(original).populate(rawData);
await settingsModel.validate();
const data = await settingsModel.toJSON();
const settings: Settings = {
...original,
...data,
...params
};
// Before continuing, let's check for differences that matter.
// 1. Check differences in `pages` property (`home`, `notFound`). If there are
// differences, check if the pages can be set as the new `specialType` page, and then,
// after save, make sure to trigger events, on which other plugins can do their tasks.
const specialTypes = ["home", "notFound"];
const changedPages: SettingsUpdateTopicMetaParams["diff"]["pages"] = [];
for (let i = 0; i < specialTypes.length; i++) {
const specialType = specialTypes[i] as PageSpecialType;
const p = lodashGet(original, `pages.${specialType}`);
const n = lodashGet(settings, `pages.${specialType}`);
if (p !== n) {
// Only throw if previously we had a page (p), and now all of a sudden
// we don't (!n). Allows updating settings without sending these.
if (p && !n) {
throw new WebinyError(
`Cannot unset "${specialType}" page. Please provide a new page if you want to unset current one.`,
"CANNOT_UNSET_SPECIAL_PAGE"
);
}
// Only load if the next page (n) has been sent, which is always a
// must if previously a page was defined (p).
if (n) {
const page = await this.getPublishedPageById({
id: n
});
changedPages.push([specialType, p, n, page]);
}
}
}
const meta: SettingsUpdateTopicMetaParams = {
diff: {
pages: changedPages
}
};
try {
await onBeforeSettingsUpdate.publish({
original,
settings,
meta
});
const result = await storageOperations.settings.update({
input: rawData,
original,
settings
});
await onAfterSettingsUpdate.publish({
original,
settings,
meta
});
/**
* Clear the cache of the data loader.
*/
settingsDataLoader.clearAll();
return result;
} catch (ex) {
throw new WebinyError(
ex.message || "Could not update existing settings record.",
ex.code || "UPDATE_SETTINGS_ERROR",
{
original,
settings
}
);
}
}
};
}; | the_stack |
import { Injectable, ElementRef } from "@angular/core";
import { BehaviorSubject, Subject } from "rxjs";
import { TransformMatrixModel, TrackModel, SelectionRectModel, PanelInfoModel } from "./model";
import { PanelWidgetModel } from "./panel-widget/model";
import { cloneDeep, get } from "lodash";
import { CombinationWidgetModel } from "./panel-scope-enchantment/model";
import { AppDataService } from "../appdata/appdata.service";
import { uniqueId } from "@ng-public/util";
import { PanelSeniorVesselEditService } from "./panel-senior-vessel-edit/panel-senior-vessel-edit.service";
import { VesselWidgetModel } from "./panel-senior-vessel-edit/model";
import { WidgetModel } from "./panel-widget/model/widget.model";
import { HostItemModel } from "./panel-widget/model/host.model";
import { OrientationModel } from "./panel-widget/model/orientation.model";
@Injectable({
providedIn: "root",
})
export class PanelExtendService {
// 执行保存到本地数据库DB操作
public launchSaveIndexedDB$: Subject<never> = new Subject<never>();
// 执行记录面板panel的视图位置信息
public launchRecordPanelInfoRect$: Subject<never> = new Subject<never>();
// 面板区域的宿主元素
public panelMainEl: ElementRef;
// 主视图的transform的变换数据模型
public transformMatrixModel: TransformMatrixModel = new TransformMatrixModel();
// 中央画板主屏幕的页面信息数据膜 ( 若处于动态容器编辑模式下,则改变其对象数据指引 )
public panelInfoModel: PanelInfoModel = new PanelInfoModel();
// 滚动条数据模型
public trackModel: TrackModel = new TrackModel();
// 可选区域的矩形数据模型
public selectionRectModel: SelectionRectModel = new SelectionRectModel();
// 当前自由面板内的组件列表内容
public widgetList$: BehaviorSubject<Array<PanelWidgetModel>> = new BehaviorSubject<Array<PanelWidgetModel>>([]);
// 是否允许鼠标拖拽视图
public isOpenSpacebarMove$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(
private readonly appDataService: AppDataService,
private readonly panelSeniorVesselEditService: PanelSeniorVesselEditService
) {}
/**
* 获取zIndex层级的最小值和最大值
*/
public findZIndexExtremum(): { min: number; max: number } {
const widgetList = this.valueWidgetList();
let min = Infinity;
let max = -Infinity;
widgetList.forEach(_w => {
min = Math.min(min, _w.profileModel.zIndex);
max = Math.max(max, _w.profileModel.zIndex);
});
return { min, max };
}
/**
* 转化HostItemModel为PanelWidgetModel
* 对组合组件特殊转化
* 对动态容器组件特殊转化
*/
public handleFreeItemToPanelWidget(arr: Array<WidgetModel>): PanelWidgetModel[] {
if (Array.isArray(arr)) {
const res = [];
arr.forEach(_e => {
const copyE = cloneDeep(_e);
const widgetE = new PanelWidgetModel(<HostItemModel>{ autoWidget: copyE, type: copyE.type });
if (widgetE.type == "combination" && Array.isArray(widgetE.autoWidget.content)) {
const content = [];
widgetE.autoWidget.content.forEach((w: WidgetModel) => {
const copyW = cloneDeep(w);
const widgetW = new PanelWidgetModel(<HostItemModel>{
autoWidget: copyW,
type: copyW.type,
});
const combinationData = new CombinationWidgetModel(widgetE);
combinationData.setData({
left: w.orientationmodel.left,
top: w.orientationmodel.top,
width: w.orientationmodel.width,
height: w.orientationmodel.height,
rotate: w.orientationmodel.rotate,
});
widgetW.profileModel.setData({
left: combinationData.left + widgetE.profileModel.left,
top: combinationData.top + widgetE.profileModel.top,
});
widgetW.profileModel.combinationWidgetData$.next(combinationData);
// // 计算子集组件在组合组件里的位置比例
widgetW.profileModel.combinationWidgetData$.value.recordInsetProOuterSphereFourProportion();
widgetW.profileModel.recordImmobilizationData();
content.push(widgetW);
});
widgetE.autoWidget.content = content;
} else if (widgetE.type == "seniorvessel" && get(widgetE, "autoWidget.content.vesselWidget")) {
widgetE.autoWidget.content.vesselWidget = new VesselWidgetModel(
get(widgetE, "autoWidget.content.vesselWidget")
);
}
res.push(widgetE);
});
return res;
} else {
return [];
}
}
/**
* 执行保存操作的时候需要处理widget的orientationModel数据,以便映射在appDataModel每一个页面中的else数组
*/
public handleSaveWidgetToOrientationModelData(
widgetList: Array<PanelWidgetModel> = this.widgetList$.value
): Array<WidgetModel> {
const saveFreeItem = [];
if (Array.isArray(widgetList)) {
widgetList.forEach(w => {
w = cloneDeep(w);
if (w.type == "combination" && Array.isArray(w.autoWidget.content)) {
w.autoWidget.content = this.handleCombinationChildWidgetList(w);
} else if (w.type == "seniorvessel") {
w.autoWidget.orientationmodel.left = w.profileModel.left;
w.autoWidget.orientationmodel.top = w.profileModel.top;
w.autoWidget.orientationmodel.width = w.profileModel.width;
w.autoWidget.orientationmodel.height = w.profileModel.height;
w.autoWidget.orientationmodel.rotate = w.profileModel.rotate;
w.autoWidget.orientationmodel.zIndex = w.profileModel.zIndex;
w.autoWidget.customfeature = w.panelEventHandlerModel.autoWidgetEvent;
w.autoWidget.style.data = w.ultimatelyStyle;
}
saveFreeItem.push(w.autoWidget);
});
}
return saveFreeItem;
}
/**
* 转化组合组件里的子集组件,使其在简易版自由面板能够正确处理数据
*/
public handleCombinationChildWidgetList(widget: PanelWidgetModel): Array<HostItemModel> {
const childWidth = widget.autoWidget.content;
const saveFreeItem = [];
childWidth.forEach((w: PanelWidgetModel) => {
w = cloneDeep(w);
if (
(<Object>w).hasOwnProperty("autoWidget") &&
w.autoWidget.orientationmodel &&
w.profileModel.combinationWidgetData$
) {
const comW = w.profileModel.combinationWidgetData$.value;
w.autoWidget.orientationmodel.setData(<OrientationModel>{
left: comW.left,
top: comW.top,
width: comW.width,
height: comW.height,
rotate: comW.rotate,
});
w.autoWidget.style.data = w.ultimatelyStyle;
}
saveFreeItem.push(w.autoWidget);
});
return saveFreeItem;
}
/**
* 清除无效事件
*/
public clearInvalidEvent(): void {
const pageObj = this.appDataService.appDataModel.app_data;
if (pageObj) {
for (const e in pageObj) {
if (Array.isArray(pageObj[e].eles)) {
pageObj[e].eles.forEach(widget => {
if (widget.customfeature && widget.customfeature.eventHandler == "tapNavigateHandler") {
const _nav_url = widget.customfeature.eventParams.nav_url;
if (!Object.keys(pageObj).includes(_nav_url)) {
widget.customfeature.eventHandler = "";
widget.customfeature.eventParams = null;
}
}
});
}
}
}
}
/**
* 置于顶层或底层
* widgets是被选组件widget
*/
public handleZIndexTopOrBottom(widgets: Array<PanelWidgetModel>, type: "top" | "bottom"): void {
if (Array.isArray(widgets)) {
const { min, max } = this.findZIndexExtremum();
const uniqueidList = widgets.map(e => e.uniqueId);
if (type == "top") {
// 先按照zindex顺序从小排大
widgets = widgets.sort((a, b) => a.profileModel.zIndex - b.profileModel.zIndex);
widgets.forEach((w, i) => {
w.profileModel.setData({
zIndex: max + i + 1,
});
});
this.deletePanelWidget(uniqueidList);
this.nextWidgetList(this.valueWidgetList().concat(widgets));
} else if (type == "bottom") {
// 先按照zindex顺序从大排小
widgets = widgets.sort((a, b) => b.profileModel.zIndex - a.profileModel.zIndex);
widgets.forEach((w, i) => {
w.profileModel.setData({
zIndex: min - i - 1,
});
});
this.deletePanelWidget(uniqueidList);
widgets = widgets.reverse();
this.nextWidgetList([...widgets, ...this.valueWidgetList()]);
}
}
}
/**
* 根据唯一uniqueId删除widget组件
*/
public deletePanelWidget(nrId: string | Array<string | number>): void {
const nrid = Array.isArray(nrId) ? nrId : [nrId];
const repetWid = this.valueWidgetList().filter(e => !nrid.includes(e.uniqueId));
this.nextWidgetList(repetWid);
this.launchSaveIndexedDB$.next();
}
/**
* 添加新的widget组件
* 重新设置zindex的值
* 每次添加组件之前都记录数据并保存到indexedDB
*/
public addPanelWidget(newWidget: Array<PanelWidgetModel>): void {
if (Array.isArray(newWidget)) {
let arr = this.valueWidgetList();
const { max } = this.findZIndexExtremum();
newWidget.forEach((w, _i) => {
setTimeout(() => (w.uniqueId = `${uniqueId()}${Math.round(Math.random() * 10000)}`));
w.profileModel.setData({
zIndex: max == -Infinity ? 1 : max + _i + 1,
});
w.autoWidget.orientationmodel.left = w.profileModel.left;
w.autoWidget.orientationmodel.top = w.profileModel.top;
w.autoWidget.orientationmodel.width = w.profileModel.width;
w.autoWidget.orientationmodel.height = w.profileModel.height;
w.autoWidget.orientationmodel.rotate = w.profileModel.rotate;
w.autoWidget.orientationmodel.zIndex = w.profileModel.zIndex;
});
arr = arr.concat(newWidget);
this.nextWidgetList(arr);
setTimeout(() => {
this.launchSaveIndexedDB$.next();
}, 11);
}
}
/**
* next -> widgetlist数据的统一入口,用于作拦截处理
*/
public nextWidgetList(params: PanelWidgetModel[]): void {
if (this.panelSeniorVesselEditService.isEnterEditVesselCondition$.value) {
this.panelSeniorVesselEditService.riverDiversionWidgetList$.next(params);
} else {
this.widgetList$.next(params);
}
}
/**
* 获取widgetList$的value值
*/
public valueWidgetList(): PanelWidgetModel[] {
const isVesselMode = this.panelSeniorVesselEditService.isEnterEditVesselCondition$.value;
return isVesselMode
? this.panelSeniorVesselEditService.riverDiversionWidgetList$.value
: this.widgetList$.value;
}
} | the_stack |
'use strict';
import { inject, injectable } from 'inversify';
import { cloneDeep } from 'lodash';
import * as path from 'path';
import { QuickPick, QuickPickItem } from 'vscode';
import { IApplicationShell, ICommandManager, IWorkspaceService } from '../../../../common/application/types';
import { Commands, Octicons } from '../../../../common/constants';
import { arePathsSame } from '../../../../common/platform/fs-paths';
import { IPlatformService } from '../../../../common/platform/types';
import { IConfigurationService, IPathUtils, Resource } from '../../../../common/types';
import { getIcon } from '../../../../common/utils/icons';
import { Common, InterpreterQuickPickList } from '../../../../common/utils/localize';
import {
IMultiStepInput,
IMultiStepInputFactory,
InputStep,
IQuickPickParameters,
} from '../../../../common/utils/multiStepInput';
import { REFRESH_BUTTON_ICON } from '../../../../debugger/extension/attachQuickPick/types';
import { captureTelemetry, sendTelemetryEvent } from '../../../../telemetry';
import { EventName } from '../../../../telemetry/constants';
import { IInterpreterService, PythonEnvironmentsChangedEvent } from '../../../contracts';
import {
IInterpreterQuickPickItem,
IInterpreterSelector,
IPythonPathUpdaterServiceManager,
ISpecialQuickPickItem,
} from '../../types';
import { BaseInterpreterSelectorCommand } from './base';
const untildify = require('untildify');
export type InterpreterStateArgs = { path?: string; workspace: Resource };
type QuickPickType = IInterpreterQuickPickItem | ISpecialQuickPickItem;
function isInterpreterQuickPickItem(item: QuickPickType): item is IInterpreterQuickPickItem {
return 'interpreter' in item;
}
function isSpecialQuickPickItem(item: QuickPickType): item is ISpecialQuickPickItem {
return 'alwaysShow' in item;
}
@injectable()
export class SetInterpreterCommand extends BaseInterpreterSelectorCommand {
private readonly manualEntrySuggestion: ISpecialQuickPickItem = {
label: `${Octicons.Add} ${InterpreterQuickPickList.enterPath.label()}`,
alwaysShow: true,
};
constructor(
@inject(IApplicationShell) applicationShell: IApplicationShell,
@inject(IPathUtils) private readonly pathUtils: IPathUtils,
@inject(IPythonPathUpdaterServiceManager)
pythonPathUpdaterService: IPythonPathUpdaterServiceManager,
@inject(IConfigurationService) private readonly configurationService: IConfigurationService,
@inject(ICommandManager) commandManager: ICommandManager,
@inject(IMultiStepInputFactory) private readonly multiStepFactory: IMultiStepInputFactory,
@inject(IPlatformService) private readonly platformService: IPlatformService,
@inject(IInterpreterSelector) private readonly interpreterSelector: IInterpreterSelector,
@inject(IWorkspaceService) workspaceService: IWorkspaceService,
@inject(IInterpreterService) private readonly interpreterService: IInterpreterService,
) {
super(pythonPathUpdaterService, commandManager, applicationShell, workspaceService);
}
public async activate(): Promise<void> {
this.disposables.push(
this.commandManager.registerCommand(Commands.Set_Interpreter, this.setInterpreter.bind(this)),
);
}
public async _pickInterpreter(
input: IMultiStepInput<InterpreterStateArgs>,
state: InterpreterStateArgs,
): Promise<void | InputStep<InterpreterStateArgs>> {
// If the list is refreshing, it's crucial to maintain sorting order at all
// times so that the visible items do not change.
const preserveOrderWhenFiltering = !!this.interpreterService.refreshPromise;
const suggestions = this.getItems(state.workspace);
state.path = undefined;
const currentInterpreterPathDisplay = this.pathUtils.getDisplayName(
this.configurationService.getSettings(state.workspace).pythonPath,
state.workspace ? state.workspace.fsPath : undefined,
);
const selection = await input.showQuickPick<QuickPickType, IQuickPickParameters<QuickPickType>>({
placeholder: InterpreterQuickPickList.quickPickListPlaceholder().format(currentInterpreterPathDisplay),
items: suggestions,
sortByLabel: !preserveOrderWhenFiltering,
keepScrollPosition: true,
activeItem: this.getActiveItem(state.workspace, suggestions),
matchOnDetail: true,
matchOnDescription: true,
title: InterpreterQuickPickList.browsePath.openButtonLabel(),
customButtonSetup: {
button: {
iconPath: getIcon(REFRESH_BUTTON_ICON),
tooltip: InterpreterQuickPickList.refreshInterpreterList(),
},
callback: () => this.interpreterService.triggerRefresh().ignoreErrors(),
},
onChangeItem: {
event: this.interpreterService.onDidChangeInterpreters,
// It's essential that each callback is handled synchronously, as result of the previous
// callback influences the input for the next one. Input here is the quickpick itself.
callback: (event: PythonEnvironmentsChangedEvent, quickPick) => {
if (this.interpreterService.refreshPromise) {
quickPick.busy = true;
this.interpreterService.refreshPromise.then(() => {
// Items are in the final state as all previous callbacks have finished executing.
quickPick.busy = false;
// Ensure we set a recommended item after refresh has finished.
this.updateQuickPickItems(quickPick, {}, state.workspace);
});
}
this.updateQuickPickItems(quickPick, event, state.workspace);
},
},
});
if (selection === undefined) {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_SELECTED, undefined, { action: 'escape' });
} else if (selection.label === this.manualEntrySuggestion.label) {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTER_OR_FIND);
return this._enterOrBrowseInterpreterPath(input, state, suggestions);
} else {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_SELECTED, undefined, { action: 'selected' });
state.path = (selection as IInterpreterQuickPickItem).path;
}
return undefined;
}
private getItems(resource: Resource) {
const suggestions: QuickPickType[] = [this.manualEntrySuggestion];
const defaultInterpreterPathSuggestion = this.getDefaultInterpreterPathSuggestion(resource);
if (defaultInterpreterPathSuggestion) {
suggestions.push(defaultInterpreterPathSuggestion);
}
const interpreterSuggestions = this.interpreterSelector.getSuggestions(resource);
this.setRecommendedItem(interpreterSuggestions, resource);
suggestions.push(...interpreterSuggestions);
return suggestions;
}
private getActiveItem(resource: Resource, suggestions: QuickPickType[]) {
const currentPythonPath = this.configurationService.getSettings(resource).pythonPath;
const activeInterpreter = suggestions.filter((i) => i.path === currentPythonPath);
if (activeInterpreter.length > 0) {
return activeInterpreter[0];
}
const firstInterpreterSuggestion = suggestions.find((s) => isInterpreterQuickPickItem(s));
if (firstInterpreterSuggestion) {
return firstInterpreterSuggestion;
}
return suggestions[0];
}
private getDefaultInterpreterPathSuggestion(resource: Resource): ISpecialQuickPickItem | undefined {
const config = this.workspaceService.getConfiguration('python', resource);
const defaultInterpreterPathValue = config.get<string>('defaultInterpreterPath');
if (defaultInterpreterPathValue && defaultInterpreterPathValue !== 'python') {
return {
label: `${Octicons.Gear} ${InterpreterQuickPickList.defaultInterpreterPath.label()}`,
detail: this.pathUtils.getDisplayName(
defaultInterpreterPathValue,
resource ? resource.fsPath : undefined,
),
path: defaultInterpreterPathValue,
alwaysShow: true,
};
}
return undefined;
}
/**
* Updates quickpick using the change event received.
*/
private updateQuickPickItems(
quickPick: QuickPick<QuickPickType>,
event: PythonEnvironmentsChangedEvent,
resource: Resource,
) {
// Active items are reset once we replace the current list with updated items, so save it.
const activeItemBeforeUpdate = quickPick.activeItems.length > 0 ? quickPick.activeItems[0] : undefined;
quickPick.items = this.getUpdatedItems(quickPick.items, event, resource);
// Ensure we maintain the same active item as before.
const activeItem = activeItemBeforeUpdate
? quickPick.items.find((item) => {
if (isInterpreterQuickPickItem(item) && isInterpreterQuickPickItem(activeItemBeforeUpdate)) {
return arePathsSame(item.interpreter.path, activeItemBeforeUpdate.interpreter.path);
}
if (isSpecialQuickPickItem(item) && isSpecialQuickPickItem(activeItemBeforeUpdate)) {
// 'label' is a constant here instead of 'path'.
return item.label === activeItemBeforeUpdate.label;
}
return false;
})
: undefined;
quickPick.activeItems = activeItem ? [activeItem] : [];
}
/**
* Prepare updated items to replace the quickpick list with.
*/
private getUpdatedItems(
items: readonly QuickPickType[],
event: PythonEnvironmentsChangedEvent,
resource: Resource,
): QuickPickType[] {
const updatedItems = [...items.values()];
const env = event.old ?? event.new;
let envIndex = -1;
if (env) {
envIndex = updatedItems.findIndex(
(item) => isInterpreterQuickPickItem(item) && arePathsSame(item.interpreter.path, env.path),
);
}
if (event.new) {
const newSuggestion: QuickPickType = this.interpreterSelector.suggestionToQuickPickItem(
event.new,
resource,
);
if (envIndex === -1) {
updatedItems.push(newSuggestion);
} else {
updatedItems[envIndex] = newSuggestion;
}
}
if (envIndex !== -1 && event.new === undefined) {
updatedItems.splice(envIndex, 1);
}
this.setRecommendedItem(updatedItems, resource);
return updatedItems;
}
private setRecommendedItem(items: QuickPickType[], resource: Resource) {
const interpreterSuggestions = this.interpreterSelector.getSuggestions(resource);
if (!this.interpreterService.refreshPromise && interpreterSuggestions.length > 0) {
// List is in the final state, so first suggestion is the recommended one.
const recommended = cloneDeep(interpreterSuggestions[0]);
recommended.label = `${Octicons.Star} ${recommended.label}`;
recommended.description = Common.recommended();
const index = items.findIndex(
(item) =>
isInterpreterQuickPickItem(item) &&
arePathsSame(item.interpreter.path, recommended.interpreter.path),
);
if (index !== -1) {
items[index] = recommended;
}
}
}
@captureTelemetry(EventName.SELECT_INTERPRETER_ENTER_BUTTON)
public async _enterOrBrowseInterpreterPath(
input: IMultiStepInput<InterpreterStateArgs>,
state: InterpreterStateArgs,
suggestions: QuickPickType[],
): Promise<void | InputStep<InterpreterStateArgs>> {
const items: QuickPickItem[] = [
{
label: InterpreterQuickPickList.browsePath.label(),
detail: InterpreterQuickPickList.browsePath.detail(),
},
];
const selection = await input.showQuickPick({
placeholder: InterpreterQuickPickList.enterPath.placeholder(),
items,
acceptFilterBoxTextAsSelection: true,
});
if (typeof selection === 'string') {
// User entered text in the filter box to enter path to python, store it
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTER_CHOICE, undefined, { choice: 'enter' });
state.path = selection;
this.sendInterpreterEntryTelemetry(selection, state.workspace, suggestions);
} else if (selection && selection.label === InterpreterQuickPickList.browsePath.label()) {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTER_CHOICE, undefined, { choice: 'browse' });
const filtersKey = 'Executables';
const filtersObject: { [name: string]: string[] } = {};
filtersObject[filtersKey] = ['exe'];
const uris = await this.applicationShell.showOpenDialog({
filters: this.platformService.isWindows ? filtersObject : undefined,
openLabel: InterpreterQuickPickList.browsePath.openButtonLabel(),
canSelectMany: false,
title: InterpreterQuickPickList.browsePath.title(),
});
if (uris && uris.length > 0) {
state.path = uris[0].fsPath;
this.sendInterpreterEntryTelemetry(state.path!, state.workspace, suggestions);
}
}
}
@captureTelemetry(EventName.SELECT_INTERPRETER)
public async setInterpreter(): Promise<void> {
const targetConfig = await this.getConfigTarget();
if (!targetConfig) {
return;
}
const { configTarget } = targetConfig;
const wkspace = targetConfig.folderUri;
const interpreterState: InterpreterStateArgs = { path: undefined, workspace: wkspace };
const multiStep = this.multiStepFactory.create<InterpreterStateArgs>();
await multiStep.run((input, s) => this._pickInterpreter(input, s), interpreterState);
if (interpreterState.path !== undefined) {
// User may choose to have an empty string stored, so variable `interpreterState.path` may be
// an empty string, in which case we should update.
// Having the value `undefined` means user cancelled the quickpick, so we update nothing in that case.
await this.pythonPathUpdaterService.updatePythonPath(interpreterState.path, configTarget, 'ui', wkspace);
}
}
/**
* Check if the interpreter that was entered exists in the list of suggestions.
* If it does, it means that it had already been discovered,
* and we didn't do a good job of surfacing it.
*
* @param selection Intepreter path that was either entered manually or picked by browsing through the filesystem.
*/
// eslint-disable-next-line class-methods-use-this
private sendInterpreterEntryTelemetry(selection: string, workspace: Resource, suggestions: QuickPickType[]): void {
let interpreterPath = path.normalize(untildify(selection));
if (!path.isAbsolute(interpreterPath)) {
interpreterPath = path.resolve(workspace?.fsPath || '', selection);
}
const expandedPaths = suggestions.map((s) => {
const suggestionPath = isInterpreterQuickPickItem(s) ? s.interpreter.path : '';
let expandedPath = path.normalize(untildify(suggestionPath));
if (!path.isAbsolute(suggestionPath)) {
expandedPath = path.resolve(workspace?.fsPath || '', suggestionPath);
}
return expandedPath;
});
const discovered = expandedPaths.includes(interpreterPath);
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTERED_EXISTS, undefined, { discovered });
return undefined;
}
} | the_stack |
import type { _Object } from "@aws-sdk/client-s3";
import {
DeleteObjectCommand,
GetObjectCommand,
HeadBucketCommand,
HeadObjectCommand,
HeadObjectCommandOutput,
ListObjectsV2Command,
ListObjectsV2CommandInput,
PutObjectCommand,
S3Client,
} from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
import { HttpHandler, HttpRequest, HttpResponse } from "@aws-sdk/protocol-http";
import {
FetchHttpHandler,
FetchHttpHandlerOptions,
} from "@aws-sdk/fetch-http-handler";
// @ts-ignore
import { requestTimeout } from "@aws-sdk/fetch-http-handler/dist-es/request-timeout";
import { buildQueryString } from "@aws-sdk/querystring-builder";
import { HeaderBag, HttpHandlerOptions, Provider } from "@aws-sdk/types";
import { Buffer } from "buffer";
import * as mime from "mime-types";
import { Vault, requestUrl, RequestUrlParam } from "obsidian";
import { Readable } from "stream";
import AggregateError from "aggregate-error";
import {
DEFAULT_CONTENT_TYPE,
RemoteItem,
S3Config,
VALID_REQURL,
} from "./baseTypes";
import { decryptArrayBuffer, encryptArrayBuffer } from "./encrypt";
import {
arrayBufferToBuffer,
bufferToArrayBuffer,
mkdirpInVault,
} from "./misc";
export { S3Client } from "@aws-sdk/client-s3";
import { log } from "./moreOnLog";
////////////////////////////////////////////////////////////////////////////////
// special handler using Obsidian requestUrl
////////////////////////////////////////////////////////////////////////////////
/**
* This is close to origin implementation of FetchHttpHandler
* https://github.com/aws/aws-sdk-js-v3/blob/main/packages/fetch-http-handler/src/fetch-http-handler.ts
* that is released under Apache 2 License.
* But this uses Obsidian requestUrl instead.
*/
class ObsHttpHandler extends FetchHttpHandler {
requestTimeoutInMs: number;
constructor(options?: FetchHttpHandlerOptions) {
super(options);
this.requestTimeoutInMs =
options === undefined ? undefined : options.requestTimeout;
}
async handle(
request: HttpRequest,
{ abortSignal }: HttpHandlerOptions = {}
): Promise<{ response: HttpResponse }> {
if (abortSignal?.aborted) {
const abortError = new Error("Request aborted");
abortError.name = "AbortError";
return Promise.reject(abortError);
}
let path = request.path;
if (request.query) {
const queryString = buildQueryString(request.query);
if (queryString) {
path += `?${queryString}`;
}
}
const { port, method } = request;
const url = `${request.protocol}//${request.hostname}${
port ? `:${port}` : ""
}${path}`;
const body =
method === "GET" || method === "HEAD" ? undefined : request.body;
const transformedHeaders: Record<string, string> = {};
for (const key of Object.keys(request.headers)) {
const keyLower = key.toLowerCase();
if (keyLower === "host" || keyLower === "content-length") {
continue;
}
transformedHeaders[keyLower] = request.headers[key];
}
let contentType: string = undefined;
if (transformedHeaders["content-type"] !== undefined) {
contentType = transformedHeaders["content-type"];
}
let transformedBody: any = body;
if (ArrayBuffer.isView(body)) {
transformedBody = bufferToArrayBuffer(body);
}
const param: RequestUrlParam = {
body: transformedBody,
headers: transformedHeaders,
method: method,
url: url,
contentType: contentType,
};
const raceOfPromises = [
requestUrl(param).then((rsp) => {
const headers = rsp.headers;
const headersLower: Record<string, string> = {};
for (const key of Object.keys(headers)) {
headersLower[key.toLowerCase()] = headers[key];
}
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(rsp.arrayBuffer));
controller.close();
},
});
return {
response: new HttpResponse({
headers: headersLower,
statusCode: rsp.status,
body: stream,
}),
};
}),
requestTimeout(this.requestTimeoutInMs),
];
if (abortSignal) {
raceOfPromises.push(
new Promise<never>((resolve, reject) => {
abortSignal.onabort = () => {
const abortError = new Error("Request aborted");
abortError.name = "AbortError";
reject(abortError);
};
})
);
}
return Promise.race(raceOfPromises);
}
}
////////////////////////////////////////////////////////////////////////////////
// other stuffs
////////////////////////////////////////////////////////////////////////////////
export const DEFAULT_S3_CONFIG = {
s3Endpoint: "",
s3Region: "",
s3AccessKeyID: "",
s3SecretAccessKey: "",
s3BucketName: "",
bypassCorsLocally: true,
partsConcurrency: 20,
forcePathStyle: false,
};
export type S3ObjectType = _Object;
const fromS3ObjectToRemoteItem = (x: S3ObjectType) => {
return {
key: x.Key,
lastModified: x.LastModified.valueOf(),
size: x.Size,
remoteType: "s3",
etag: x.ETag,
} as RemoteItem;
};
const fromS3HeadObjectToRemoteItem = (
key: string,
x: HeadObjectCommandOutput
) => {
return {
key: key,
lastModified: x.LastModified.valueOf(),
size: x.ContentLength,
remoteType: "s3",
etag: x.ETag,
} as RemoteItem;
};
export const getS3Client = (s3Config: S3Config) => {
let endpoint = s3Config.s3Endpoint;
if (!(endpoint.startsWith("http://") || endpoint.startsWith("https://"))) {
endpoint = `https://${endpoint}`;
}
let s3Client: S3Client;
if (VALID_REQURL && s3Config.bypassCorsLocally) {
s3Client = new S3Client({
region: s3Config.s3Region,
endpoint: endpoint,
forcePathStyle: s3Config.forcePathStyle,
credentials: {
accessKeyId: s3Config.s3AccessKeyID,
secretAccessKey: s3Config.s3SecretAccessKey,
},
requestHandler: new ObsHttpHandler(),
});
} else {
s3Client = new S3Client({
region: s3Config.s3Region,
endpoint: endpoint,
forcePathStyle: s3Config.forcePathStyle,
credentials: {
accessKeyId: s3Config.s3AccessKeyID,
secretAccessKey: s3Config.s3SecretAccessKey,
},
});
}
s3Client.middlewareStack.add(
(next, context) => (args) => {
(args.request as any).headers["cache-control"] = "no-cache";
return next(args);
},
{
step: "build",
}
);
return s3Client;
};
export const getRemoteMeta = async (
s3Client: S3Client,
s3Config: S3Config,
fileOrFolderPath: string
) => {
const res = await s3Client.send(
new HeadObjectCommand({
Bucket: s3Config.s3BucketName,
Key: fileOrFolderPath,
})
);
return fromS3HeadObjectToRemoteItem(fileOrFolderPath, res);
};
export const uploadToRemote = async (
s3Client: S3Client,
s3Config: S3Config,
fileOrFolderPath: string,
vault: Vault,
isRecursively: boolean = false,
password: string = "",
remoteEncryptedKey: string = "",
uploadRaw: boolean = false,
rawContent: string | ArrayBuffer = ""
) => {
let uploadFile = fileOrFolderPath;
if (password !== "") {
uploadFile = remoteEncryptedKey;
}
const isFolder = fileOrFolderPath.endsWith("/");
if (isFolder && isRecursively) {
throw Error("upload function doesn't implement recursive function yet!");
} else if (isFolder && !isRecursively) {
if (uploadRaw) {
throw Error(`you specify uploadRaw, but you also provide a folder key!`);
}
// folder
const contentType = DEFAULT_CONTENT_TYPE;
await s3Client.send(
new PutObjectCommand({
Bucket: s3Config.s3BucketName,
Key: uploadFile,
Body: "",
ContentType: contentType,
})
);
return await getRemoteMeta(s3Client, s3Config, uploadFile);
} else {
// file
// we ignore isRecursively parameter here
let contentType = DEFAULT_CONTENT_TYPE;
if (password === "") {
contentType =
mime.contentType(
mime.lookup(fileOrFolderPath) || DEFAULT_CONTENT_TYPE
) || DEFAULT_CONTENT_TYPE;
}
let localContent = undefined;
if (uploadRaw) {
if (typeof rawContent === "string") {
localContent = new TextEncoder().encode(rawContent).buffer;
} else {
localContent = rawContent;
}
} else {
localContent = await vault.adapter.readBinary(fileOrFolderPath);
}
let remoteContent = localContent;
if (password !== "") {
remoteContent = await encryptArrayBuffer(localContent, password);
}
const bytesIn5MB = 5242880;
const body = new Uint8Array(remoteContent);
const upload = new Upload({
client: s3Client,
queueSize: s3Config.partsConcurrency, // concurrency
partSize: bytesIn5MB, // minimal 5MB by default
leavePartsOnError: false,
params: {
Bucket: s3Config.s3BucketName,
Key: uploadFile,
Body: body,
ContentType: contentType,
},
});
upload.on("httpUploadProgress", (progress) => {
// log.info(progress);
});
await upload.done();
return await getRemoteMeta(s3Client, s3Config, uploadFile);
}
};
export const listFromRemote = async (
s3Client: S3Client,
s3Config: S3Config,
prefix?: string
) => {
const confCmd = {
Bucket: s3Config.s3BucketName,
} as ListObjectsV2CommandInput;
if (prefix !== undefined) {
confCmd.Prefix = prefix;
}
const contents = [] as _Object[];
let isTruncated = true;
do {
const rsp = await s3Client.send(new ListObjectsV2Command(confCmd));
if (rsp.$metadata.httpStatusCode !== 200) {
throw Error("some thing bad while listing remote!");
}
if (rsp.Contents === undefined) {
break;
}
contents.push(...rsp.Contents);
isTruncated = rsp.IsTruncated;
confCmd.ContinuationToken = rsp.NextContinuationToken;
if (
isTruncated &&
(confCmd.ContinuationToken === undefined ||
confCmd.ContinuationToken === "")
) {
throw Error("isTruncated is true but no continuationToken provided");
}
} while (isTruncated);
// ensemble fake rsp
return {
Contents: contents.map((x) => fromS3ObjectToRemoteItem(x)),
};
};
/**
* The Body of resp of aws GetObject has mix types
* and we want to get ArrayBuffer here.
* See https://github.com/aws/aws-sdk-js-v3/issues/1877
* @param b The Body of GetObject
* @returns Promise<ArrayBuffer>
*/
const getObjectBodyToArrayBuffer = async (
b: Readable | ReadableStream | Blob
) => {
if (b instanceof Readable) {
return (await new Promise((resolve, reject) => {
const chunks: Uint8Array[] = [];
b.on("data", (chunk) => chunks.push(chunk));
b.on("error", reject);
b.on("end", () => resolve(bufferToArrayBuffer(Buffer.concat(chunks))));
})) as ArrayBuffer;
} else if (b instanceof ReadableStream) {
return await new Response(b, {}).arrayBuffer();
} else if (b instanceof Blob) {
return await b.arrayBuffer();
} else {
throw TypeError(`The type of ${b} is not one of the supported types`);
}
};
const downloadFromRemoteRaw = async (
s3Client: S3Client,
s3Config: S3Config,
fileOrFolderPath: string
) => {
const data = await s3Client.send(
new GetObjectCommand({
Bucket: s3Config.s3BucketName,
Key: fileOrFolderPath,
})
);
const bodyContents = await getObjectBodyToArrayBuffer(data.Body);
return bodyContents;
};
export const downloadFromRemote = async (
s3Client: S3Client,
s3Config: S3Config,
fileOrFolderPath: string,
vault: Vault,
mtime: number,
password: string = "",
remoteEncryptedKey: string = "",
skipSaving: boolean = false
) => {
const isFolder = fileOrFolderPath.endsWith("/");
if (!skipSaving) {
await mkdirpInVault(fileOrFolderPath, vault);
}
// the file is always local file
// we need to encrypt it
if (isFolder) {
// mkdirp locally is enough
// do nothing here
return new ArrayBuffer(0);
} else {
let downloadFile = fileOrFolderPath;
if (password !== "") {
downloadFile = remoteEncryptedKey;
}
const remoteContent = await downloadFromRemoteRaw(
s3Client,
s3Config,
downloadFile
);
let localContent = remoteContent;
if (password !== "") {
localContent = await decryptArrayBuffer(remoteContent, password);
}
if (!skipSaving) {
await vault.adapter.writeBinary(fileOrFolderPath, localContent, {
mtime: mtime,
});
}
return localContent;
}
};
/**
* This function deals with file normally and "folder" recursively.
* @param s3Client
* @param s3Config
* @param fileOrFolderPath
* @returns
*/
export const deleteFromRemote = async (
s3Client: S3Client,
s3Config: S3Config,
fileOrFolderPath: string,
password: string = "",
remoteEncryptedKey: string = ""
) => {
if (fileOrFolderPath === "/") {
return;
}
let remoteFileName = fileOrFolderPath;
if (password !== "") {
remoteFileName = remoteEncryptedKey;
}
await s3Client.send(
new DeleteObjectCommand({
Bucket: s3Config.s3BucketName,
Key: remoteFileName,
})
);
if (fileOrFolderPath.endsWith("/") && password === "") {
const x = await listFromRemote(s3Client, s3Config, fileOrFolderPath);
x.Contents.forEach(async (element) => {
await s3Client.send(
new DeleteObjectCommand({
Bucket: s3Config.s3BucketName,
Key: element.key,
})
);
});
} else if (fileOrFolderPath.endsWith("/") && password !== "") {
// TODO
} else {
// pass
}
};
/**
* Check the config of S3 by heading bucket
* https://stackoverflow.com/questions/50842835
* @param s3Client
* @param s3Config
* @returns
*/
export const checkConnectivity = async (
s3Client: S3Client,
s3Config: S3Config,
callbackFunc?: any
) => {
try {
const results = await s3Client.send(
new HeadBucketCommand({ Bucket: s3Config.s3BucketName })
);
if (
results === undefined ||
results.$metadata === undefined ||
results.$metadata.httpStatusCode === undefined
) {
const err = "results or $metadata or httStatusCode is undefined";
log.debug(err);
if (callbackFunc !== undefined) {
callbackFunc(err);
}
return false;
}
return results.$metadata.httpStatusCode === 200;
} catch (err) {
log.debug(err);
if (callbackFunc !== undefined) {
if (s3Config.s3Endpoint.contains(s3Config.s3BucketName)) {
const err2 = new AggregateError([
err,
new Error(
"Maybe you've included the bucket name inside the endpoint setting. Please remove the bucket name and try again."
),
]);
callbackFunc(err2);
} else {
callbackFunc(err);
}
}
return false;
}
}; | the_stack |
import { toQueryString } from "../../utils";
import { SdkClient } from "../common/sdk-client";
import { DataExchangeModels } from "./data-exchange-models";
import { dataExchangeTemplate, putFileTemplate } from "./data-exchange-template";
/**
*
* Offers data transfer operations as part of the Analytics package,
* in a single endpoint providing various operations like upload/download, move, (recursive) delete,
* share within tenant.It also provides an abstraction that helps callers easily share files and folders
* between the users of tHe same tenant, while allowing uploads with different visibilities private, or
* public (within a tenant only) When looking to p[lace a file or directory
* (either when creating a new one or moving it) into the root of the storage,
* simply set the parentId of the file or folder to one of the "_PUBLIC_ROOT_ID" or "_PRIVATE_ROOT_ID"
* allowing in this way to specify its visibility space.
*
* Allowed and safe characters to use in both filename and directyory names are the following:
* Alphanumeric characters [0-9a-zA-Z]
* Special characters -, _, ., (, ), and the space character The following are examples of valid object key names:
* 4my-data
* _test_dir./myfile.csv
* Not allowed is using &$@=;:+,?,^{}%`[]"<>#|~!*' in filenames and directory names.
mode
The maximum length of the composed path, that is filename and directories names separated by '/' that is used in a request is 1024 bytes in UTF-8 encoding.
*
*
* @export
* @class DataExchangeClient
* @extends {SdkClient}
*/
export class DataExchangeClient extends SdkClient {
private _baseUrl: string = "/api/dataexchange/v3";
/**
* * Files
*
* Performs a new file upload
*
* Uploads a file using the specified form data parameters, and returns the created file resource.
* The service verifies whether the user or the tenant under which the operation occurs has access
* to the specified parent and generates an error in case of an unautorhized access.
*
* @param {DataExchangeModels.ResourcePatch} metadata
* @param {Buffer} file
* @returns {Promise<DataExchangeModels.File>}
*
* @memberOf DataExchangeClient
*/
public async PostFile(metadata: DataExchangeModels.ResourcePatch, file: Buffer): Promise<DataExchangeModels.File> {
const body = dataExchangeTemplate(metadata, file);
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/files`,
body: body,
multiPartFormData: true,
additionalHeaders: { enctype: "multipart/form-data" },
});
return result as DataExchangeModels.File;
}
/**
* * Files
*
* Downloads the file identified by the specified ID.
*
* @param {string} id
* @returns {Promise<Response>}
*
* @memberOf DataExchangeClient
*/
public async GetFile(id: string): Promise<Response> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/files/${id}`,
additionalHeaders: { "Content-Type": "application/octet-stream" },
rawResponse: true,
});
return result as Response;
}
/**
* * Files
*
* Uploads a file on top of an existing file
*
* @param {string} id
* @param {Buffer} file
* @returns {Promise<DataExchangeModels.File>}
*
* @memberOf DataExchangeClient
*/
public async PutFile(id: string, file: Buffer): Promise<DataExchangeModels.File> {
const body = putFileTemplate(file);
const result = await this.HttpAction({
verb: "PUT",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/files/${id}`,
body: body,
multiPartFormData: true,
additionalHeaders: { enctype: "multipart/form-data" },
});
return result as DataExchangeModels.File;
}
/**
* * Files
*
* Deletes a file (both metadata and the actual content).
*
* @param {string} id
*
* @memberOf DataExchangeClient
*/
public async DeleteFile(id: string) {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/files/${id}`,
noResponse: true,
});
}
/**
*
* Retrieves metadata of the file identified by the specified ID.
*
* @param {string} id
* @returns {Promise<DataExchangeModels.File>}
*
* @memberOf DataExchangeClient
*/
public async GetFileProperties(id: string): Promise<DataExchangeModels.File> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/files/${id}/properties`,
// !fix: manual fix - this is actually illegal call according to mindsphere rules
additionalHeaders: { "Content-Type": "application/json" },
});
return result as DataExchangeModels.File;
}
/**
* * Files
*
* Allows updating specific properties associated with the file, namely its name and parent (by ID).
* Updating the visibility (namely tenant-wide or user-only) for a file is not available but can be achieved
* via changing the current file's parent to a directory that has a different visibility space.
*
* @param {string} id
* @param {DataExchangeModels.ResourcePatch} options
* @returns {Promise<DataExchangeModels.File>}
*
* @memberOf DataExchangeClient
*/
public async PatchFileProperties(
id: string,
options: DataExchangeModels.ResourcePatch
): Promise<DataExchangeModels.File> {
const result = await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/files/${id}/properties`,
body: options,
});
return result as DataExchangeModels.File;
}
/**
* * Directories
*
* creates a directory
*
* @param {DataExchangeModels.ResourcePatch} metadata
* @returns {Promise<DataExchangeModels.Directory>}
*
* @memberOf DataExchangeClient
*/
public async PostDirectory(metadata: DataExchangeModels.ResourcePatch): Promise<DataExchangeModels.Directory> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/directories`,
body: metadata,
});
return result as DataExchangeModels.Directory;
}
/**
*
* Retreives updatable directory options, i.e the name and the parentId.
*
* @param {string} id
* @returns {Promise<DataExchangeModels.Directory>}
*
* @memberOf DataExchangeClient
*/
public async GetDirectoryProperties(id: string): Promise<DataExchangeModels.Directory> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/directories/${id}/properties`,
// !fix: manual fix - this is actually illegal call according to mindsphere rules
additionalHeaders: { "Content-Type": "application/json" },
});
return result as DataExchangeModels.Directory;
}
/**
* * Directories
*
* Allows updating directory's properties.
*
* Allows updating directory metadata, including the parentId (which triggers a move of the current directory),
* or its visibility by moving it under a parentId that has a different visibility,
* causing this change to propagate to its inner contents.
* Changing the parentId to a parent that already contains a folder with the same name is not possible,
* an error will be thrown.
*
* @param {string} id
* @param {DataExchangeModels.ResourcePatch} options
* @returns {Promise<DataExchangeModels.Directory>}
*
* @memberOf DataExchangeClient
*/
public async PatchDirectoryProperties(
id: string,
options: DataExchangeModels.ResourcePatch
): Promise<DataExchangeModels.Directory> {
const result = await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/directories/${id}/properties`,
body: options,
});
return result as DataExchangeModels.Directory;
}
/**
*
* * Directories
*
* Using GET on this endpoint to get a list of the source's contents
*
* Specifies the id for which it will list the contents.
* By convention, when listing a root folder also implies specifying the visibility
* that the caller is looking after, that is, if listing the private space root, then this parameter requires
* "_PUBLIC_ROOT_ID" or "_PRIVATE_ROOT_ID" value instead of a real directory id.
*
* @param {string} id
* @param {{ pageNumber?: number; pageSize?: number; filter: string }} params
* @returns {Promise<DataExchangeModels.DirectoriesFilesArray>}
*
* @memberOf DataExchangeClient
*/
public async GetDirectory(
id: string,
params?: { pageNumber?: number; pageSize?: number; filter?: string }
): Promise<DataExchangeModels.DirectoriesFilesArray> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/directories/${id}?${toQueryString(parameters)}`,
});
return result as DataExchangeModels.DirectoriesFilesArray;
}
/**
* * Directories
*
* Deletes a directory and its contents if recursive=true
*
* @param {string} id
* @param {{ recursive?: boolean }} [params]
*
* @param params.recursive specifies if the deletion will be performed recursively
*
* @memberOf DataExchangeClient
*/
public async DeleteDirectory(id: string, params?: { recursive?: boolean }) {
const parameters = params || {};
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/directories/${id}?${toQueryString(parameters)}`,
noResponse: true,
});
}
} | the_stack |
class Afl {
/**
* Field containing the `Module` object for `afl-frida-trace.so` (the FRIDA mode
* implementation).
*/
public static module: Module = Process.getModuleByName("afl-frida-trace.so");
/**
* This is equivalent to setting a value in `AFL_FRIDA_EXCLUDE_RANGES`,
* it takes as arguments a `NativePointer` and a `number`. It can be
* called multiple times to exclude several ranges.
*/
public static addExcludedRange(addressess: NativePointer, size: number): void {
Afl.jsApiAddExcludeRange(addressess, size);
}
/**
* This is equivalent to setting a value in `AFL_FRIDA_INST_RANGES`,
* it takes as arguments a `NativePointer` and a `number`. It can be
* called multiple times to include several ranges.
*/
public static addIncludedRange(addressess: NativePointer, size: number): void {
Afl.jsApiAddIncludeRange(addressess, size);
}
/**
* This must always be called at the end of your script. This lets
* FRIDA mode know that your configuration is finished and that
* execution has reached the end of your script. Failure to call
* this will result in a fatal error.
*/
public static done(): void {
Afl.jsApiDone();
}
/**
* This function can be called within your script to cause FRIDA
* mode to trigger a fatal error. This is useful if for example you
* discover a problem you weren't expecting and want everything to
* stop. The user will need to enable `AFL_DEBUG_CHILD=1` to view
* this error message.
*/
public static error(msg: string): void {
const buf = Memory.allocUtf8String(msg);
Afl.jsApiError(buf);
}
/**
* Function used to provide access to `__afl_fuzz_ptr`, which contains the length of
* fuzzing data when using in-memory test case fuzzing.
*/
public static getAflFuzzLen(): NativePointer {
return Afl.jsApiGetSymbol("__afl_fuzz_len");
}
/**
* Function used to provide access to `__afl_fuzz_ptr`, which contains the fuzzing
* data when using in-memory test case fuzzing.
*/
public static getAflFuzzPtr(): NativePointer {
return Afl.jsApiGetSymbol("__afl_fuzz_ptr");
}
/**
* Print a message to the STDOUT. This should be preferred to
* FRIDA's `console.log` since FRIDA will queue it's log messages.
* If `console.log` is used in a callback in particular, then there
* may no longer be a thread running to service this queue.
*/
public static print(msg: string): void {
const STDOUT_FILENO = 2;
const log = `${msg}\n`;
const buf = Memory.allocUtf8String(log);
Afl.jsApiWrite(STDOUT_FILENO, buf, log.length);
}
/**
* See `AFL_FRIDA_STALKER_NO_BACKPATCH`.
*/
public static setBackpatchDisable(): void {
Afl.jsApiSetBackpatchDisable();
}
/**
* See `AFL_FRIDA_INST_NO_CACHE`.
*/
public static setCacheDisable(): void {
Afl.jsApiSetCacheDisable();
}
/**
* See `AFL_FRIDA_DEBUG_MAPS`.
*/
public static setDebugMaps(): void {
Afl.jsApiSetDebugMaps();
}
/**
* This has the same effect as setting `AFL_ENTRYPOINT`, but has the
* convenience of allowing you to use FRIDAs APIs to determine the
* address you would like to configure, rather than having to grep
* the output of `readelf` or something similarly ugly. This
* function should be called with a `NativePointer` as its
* argument.
*/
public static setEntryPoint(address: NativePointer): void {
Afl.jsApiSetEntryPoint(address);
}
/**
* Function used to enable in-memory test cases for fuzzing.
*/
public static setInMemoryFuzzing(): void {
Afl.jsApiAflSharedMemFuzzing.writeInt(1);
}
/**
* See `AFL_FRIDA_INST_CACHE_SIZE`. This function takes a single `number`
* as an argument.
*/
public static setInstrumentCacheSize(size: number): void {
Afl.jsApiSetInstrumentCacheSize(size);
}
/**
* See `AFL_FRIDA_INST_COVERAGE_FILE`. This function takes a single `string`
* as an argument.
*/
public static setInstrumentCoverageFile(file: string): void {
const buf = Memory.allocUtf8String(file);
Afl.jsApiSetInstrumentCoverageFile(buf);
}
/**
* See `AFL_FRIDA_INST_DEBUG_FILE`. This function takes a single `string` as
* an argument.
*/
public static setInstrumentDebugFile(file: string): void {
const buf = Memory.allocUtf8String(file);
Afl.jsApiSetInstrumentDebugFile(buf);
}
/**
* See `AFL_FRIDA_INST_TRACE`.
*/
public static setInstrumentEnableTracing(): void {
Afl.jsApiSetInstrumentTrace();
}
/**
* See `AFL_FRIDA_INST_INSN`
*/
public static setInstrumentInstructions(): void {
Afl.jsApiSetInstrumentInstructions();
}
/**
* See `AFL_FRIDA_INST_JIT`.
*/
public static setInstrumentJit(): void {
Afl.jsApiSetInstrumentJit();
}
/**
* See `AFL_INST_LIBS`.
*/
public static setInstrumentLibraries(): void {
Afl.jsApiSetInstrumentLibraries();
}
/**
* See `AFL_FRIDA_INST_NO_OPTIMIZE`
*/
public static setInstrumentNoOptimize(): void {
Afl.jsApiSetInstrumentNoOptimize();
}
/*
* See `AFL_FRIDA_INST_SEED`
*/
public static setInstrumentSeed(seed: NativePointer): void {
Afl.jsApiSetInstrumentSeed(seed);
}
/**
* See `AFL_FRIDA_INST_TRACE_UNIQUE`.
*/
public static setInstrumentTracingUnique(): void {
Afl.jsApiSetInstrumentTraceUnique();
}
/**
* See `AFL_FRIDA_INST_UNSTABLE_COVERAGE_FILE`. This function takes a single
* `string` as an argument.
*/
public static setInstrumentUnstableCoverageFile(file: string): void {
const buf = Memory.allocUtf8String(file);
Afl.jsApiSetInstrumentUnstableCoverageFile(buf);
}
/*
* Set a callback to be called in place of the usual `main` function. This see
* `Scripting.md` for details.
*/
public static setJsMainHook(address: NativePointer): void {
Afl.jsApiSetJsMainHook(address);
}
/**
* This is equivalent to setting `AFL_FRIDA_PERSISTENT_ADDR`, again a
* `NativePointer` should be provided as it's argument.
*/
public static setPersistentAddress(address: NativePointer): void {
Afl.jsApiSetPersistentAddress(address);
}
/**
* This is equivalent to setting `AFL_FRIDA_PERSISTENT_CNT`, a
* `number` should be provided as it's argument.
*/
public static setPersistentCount(count: number): void {
Afl.jsApiSetPersistentCount(count);
}
/**
* See `AFL_FRIDA_PERSISTENT_DEBUG`.
*/
public static setPersistentDebug(): void {
Afl.jsApiSetPersistentDebug();
}
/**
* See `AFL_FRIDA_PERSISTENT_ADDR`. This function takes a NativePointer as an
* argument. See above for examples of use.
*/
public static setPersistentHook(address: NativePointer): void {
Afl.jsApiSetPersistentHook(address);
}
/**
* This is equivalent to setting `AFL_FRIDA_PERSISTENT_RET`, again a
* `NativePointer` should be provided as it's argument.
*/
public static setPersistentReturn(address: NativePointer): void {
Afl.jsApiSetPersistentReturn(address);
}
/**
* See `AFL_FRIDA_INST_NO_PREFETCH_BACKPATCH`.
*/
public static setPrefetchBackpatchDisable(): void {
Afl.jsApiSetPrefetchBackpatchDisable();
}
/**
* See `AFL_FRIDA_INST_NO_PREFETCH`.
*/
public static setPrefetchDisable(): void {
Afl.jsApiSetPrefetchDisable();
}
/**
* See `AFL_FRIDA_SECCOMP_FILE`. This function takes a single `string` as
* an argument.
*/
public static setSeccompFile(file: string): void {
const buf = Memory.allocUtf8String(file);
Afl.jsApiSetSeccompFile(buf);
}
/**
* See `AFL_FRIDA_STALKER_ADJACENT_BLOCKS`.
*/
public static setStalkerAdjacentBlocks(val: number): void {
Afl.jsApiSetStalkerAdjacentBlocks(val);
}
/*
* Set a function to be called for each instruction which is instrumented
* by AFL FRIDA mode.
*/
public static setStalkerCallback(callback: NativePointer): void {
Afl.jsApiSetStalkerCallback(callback);
}
/**
* See `AFL_FRIDA_STALKER_IC_ENTRIES`.
*/
public static setStalkerIcEntries(val: number): void {
Afl.jsApiSetStalkerIcEntries(val);
}
/**
* See `AFL_FRIDA_STATS_FILE`. This function takes a single `string` as
* an argument.
*/
public static setStatsFile(file: string): void {
const buf = Memory.allocUtf8String(file);
Afl.jsApiSetStatsFile(buf);
}
/**
* See `AFL_FRIDA_STATS_INTERVAL`. This function takes a `number` as an
* argument
*/
public static setStatsInterval(interval: number): void {
Afl.jsApiSetStatsInterval(interval);
}
/**
* See `AFL_FRIDA_OUTPUT_STDERR`. This function takes a single `string` as
* an argument.
*/
public static setStdErr(file: string): void {
const buf = Memory.allocUtf8String(file);
Afl.jsApiSetStdErr(buf);
}
/**
* See `AFL_FRIDA_OUTPUT_STDOUT`. This function takes a single `string` as
* an argument.
*/
public static setStdOut(file: string): void {
const buf = Memory.allocUtf8String(file);
Afl.jsApiSetStdOut(buf);
}
/**
* See `AFL_FRIDA_TRACEABLE`.
*/
public static setTraceable(): void {
Afl.jsApiSetTraceable();
}
/**
* See `AFL_FRIDA_VERBOSE`
*/
public static setVerbose(): void {
Afl.jsApiSetVerbose();
}
private static readonly jsApiAddExcludeRange = Afl.jsApiGetFunction(
"js_api_add_exclude_range",
"void",
["pointer", "size_t"]);
private static readonly jsApiAddIncludeRange = Afl.jsApiGetFunction(
"js_api_add_include_range",
"void",
["pointer", "size_t"]);
private static readonly jsApiAflSharedMemFuzzing = Afl.jsApiGetSymbol("__afl_sharedmem_fuzzing");
private static readonly jsApiDone = Afl.jsApiGetFunction(
"js_api_done",
"void",
[]);
private static readonly jsApiError = Afl.jsApiGetFunction(
"js_api_error",
"void",
["pointer"]);
private static readonly jsApiSetBackpatchDisable = Afl.jsApiGetFunction(
"js_api_set_backpatch_disable",
"void",
[]);
private static readonly jsApiSetCacheDisable = Afl.jsApiGetFunction(
"js_api_set_cache_disable",
"void",
[]);
private static readonly jsApiSetDebugMaps = Afl.jsApiGetFunction(
"js_api_set_debug_maps",
"void",
[]);
private static readonly jsApiSetEntryPoint = Afl.jsApiGetFunction(
"js_api_set_entrypoint",
"void",
["pointer"]);
private static readonly jsApiSetInstrumentCacheSize = Afl.jsApiGetFunction(
"js_api_set_instrument_cache_size",
"void",
["size_t"]);
private static readonly jsApiSetInstrumentCoverageFile = Afl.jsApiGetFunction(
"js_api_set_instrument_coverage_file",
"void",
["pointer"]);
private static readonly jsApiSetInstrumentDebugFile = Afl.jsApiGetFunction(
"js_api_set_instrument_debug_file",
"void",
["pointer"]);
private static readonly jsApiSetInstrumentInstructions = Afl.jsApiGetFunction(
"js_api_set_instrument_instructions",
"void",
[]);
private static readonly jsApiSetInstrumentJit = Afl.jsApiGetFunction(
"js_api_set_instrument_jit",
"void",
[]);
private static readonly jsApiSetInstrumentLibraries = Afl.jsApiGetFunction(
"js_api_set_instrument_libraries",
"void",
[]);
private static readonly jsApiSetInstrumentNoOptimize = Afl.jsApiGetFunction(
"js_api_set_instrument_no_optimize",
"void",
[]);
private static readonly jsApiSetInstrumentSeed = Afl.jsApiGetFunction(
"js_api_set_instrument_seed",
"void",
["uint64"]);
private static readonly jsApiSetInstrumentTrace = Afl.jsApiGetFunction(
"js_api_set_instrument_trace",
"void",
[]);
private static readonly jsApiSetInstrumentTraceUnique = Afl.jsApiGetFunction(
"js_api_set_instrument_trace_unique",
"void",
[]);
private static readonly jsApiSetInstrumentUnstableCoverageFile = Afl.jsApiGetFunction(
"js_api_set_instrument_unstable_coverage_file",
"void",
["pointer"]);
private static readonly jsApiSetJsMainHook = Afl.jsApiGetFunction(
"js_api_set_js_main_hook",
"void",
["pointer"]);
private static readonly jsApiSetPersistentAddress = Afl.jsApiGetFunction(
"js_api_set_persistent_address",
"void",
["pointer"]);
private static readonly jsApiSetPersistentCount = Afl.jsApiGetFunction(
"js_api_set_persistent_count",
"void",
["uint64"]);
private static readonly jsApiSetPersistentDebug = Afl.jsApiGetFunction(
"js_api_set_persistent_debug",
"void",
[]);
private static readonly jsApiSetPersistentHook = Afl.jsApiGetFunction(
"js_api_set_persistent_hook",
"void",
["pointer"]);
private static readonly jsApiSetPersistentReturn = Afl.jsApiGetFunction(
"js_api_set_persistent_return",
"void",
["pointer"]);
private static readonly jsApiSetPrefetchBackpatchDisable = Afl.jsApiGetFunction(
"js_api_set_prefetch_backpatch_disable",
"void",
[]);
private static readonly jsApiSetPrefetchDisable = Afl.jsApiGetFunction(
"js_api_set_prefetch_disable",
"void",
[]);
private static readonly jsApiSetSeccompFile = Afl.jsApiGetFunction(
"js_api_set_seccomp_file",
"void",
["pointer"]);
private static readonly jsApiSetStalkerAdjacentBlocks = Afl.jsApiGetFunction(
"js_api_set_stalker_adjacent_blocks",
"void",
["uint32"]);
private static readonly jsApiSetStalkerCallback = Afl.jsApiGetFunction(
"js_api_set_stalker_callback",
"void",
["pointer"]);
private static readonly jsApiSetStalkerIcEntries = Afl.jsApiGetFunction(
"js_api_set_stalker_ic_entries",
"void",
["uint32"]);
private static readonly jsApiSetStatsFile = Afl.jsApiGetFunction(
"js_api_set_stats_file",
"void",
["pointer"]);
private static readonly jsApiSetStatsInterval = Afl.jsApiGetFunction(
"js_api_set_stats_interval",
"void",
["uint64"]);
private static readonly jsApiSetStdErr = Afl.jsApiGetFunction(
"js_api_set_stderr",
"void",
["pointer"]);
private static readonly jsApiSetStdOut = Afl.jsApiGetFunction(
"js_api_set_stdout",
"void",
["pointer"]);
private static readonly jsApiSetTraceable = Afl.jsApiGetFunction(
"js_api_set_traceable",
"void",
[]);
private static readonly jsApiSetVerbose = Afl.jsApiGetFunction(
"js_api_set_verbose",
"void",
[]);
private static readonly jsApiWrite = new NativeFunction(
/* tslint:disable-next-line:no-null-keyword */
Module.getExportByName(null, "write"),
"int",
["int", "pointer", "int"]);
private static jsApiGetFunction(name: string, retType: NativeType, argTypes: NativeType[]): NativeFunction {
const addr: NativePointer = Afl.module.getExportByName(name);
return new NativeFunction(addr, retType, argTypes);
}
private static jsApiGetSymbol(name: string): NativePointer {
return Afl.module.getExportByName(name);
}
}
export { Afl }; | the_stack |
import { getLogger } from 'pinus-logger';
import {MonitorAgent} from './monitor/monitorAgent';
import { EventEmitter } from 'events';
import { MasterAgent, MasterAgentOptions } from './master/masterAgent';
import * as schedule from 'pinus-scheduler';
import * as protocol from './util/protocol';
import * as utils from './util/utils';
import * as util from 'util';
import { AdminServerInfo, ServerInfo, AdminUserInfo, Callback } from './util/constants';
import * as path from 'path';
let logger = getLogger('pinus-admin', path.basename(__filename));
let MS_OF_SECOND = 1000;
export enum ModuleType {
push = 'push',
pull = 'pull',
Normal = ''
}
export type MasterCallback = (err?: string , data?: any) => void;
export type MonitorCallback = (err?: Error , data?: any) => void;
export interface IModule {
moduleId ?: string;
type ?: ModuleType;
interval ?: number;
delay ?: number;
start?: (cb: (err?: Error) => void) => void;
masterHandler ?: (agent: MasterAgent, msg: any, cb: MasterCallback) => void;
monitorHandler ?: (agent: MonitorAgent, msg: any, cb: MonitorCallback) => void;
}
export interface ModuleRecord {
moduleId: string;
module: any;
enable: boolean;
delay ?: number;
interval ?: number;
schedule ?: boolean;
jobId?: number;
}
export interface IModuleFactory {
new (opts: any , consoleService ?: ConsoleService): IModule;
moduleId: string;
}
export interface MasterConsoleServiceOpts extends MasterAgentOptions {
master?: boolean;
port?: number;
env?: string;
authUser ?: typeof utils.defaultAuthUser;
authServer ?: typeof utils.defaultAuthServerMaster;
}
export interface MonitorConsoleServiceOpts {
type?: string;
id?: string;
host?: string;
info?: ServerInfo;
port?: number;
env?: string;
authServer ?: typeof utils.defaultAuthServerMaster;
}
export type ConsoleServiceOpts = MasterConsoleServiceOpts | MonitorConsoleServiceOpts;
export interface AdminLogInfo {
action: string;
moduleId: string;
method?: string;
msg: any;
error?: Error | string | number;
}
/**
* ConsoleService Constructor
*
* @class ConsoleService
* @constructor
* @param {Object} opts construct parameter
* opts.type {String} server type, 'master', 'connector', etc.
* opts.id {String} server id
* opts.host {String} (monitor only) master server host
* opts.port {String | Number} listen port for master or master port for monitor
* opts.master {Boolean} current service is master or monitor
* opts.info {Object} more server info for current server, {id, serverType, host, port}
* @api public
*/
export class ConsoleService extends EventEmitter {
port: number;
env: string;
values: {[key: string]: any};
master: boolean;
modules: {[key: string]: ModuleRecord};
commands: {[key: string]: (consoleService: ConsoleService, moduleId: string, msg: any, cb: Callback) => void};
authUser: typeof utils.defaultAuthUser;
authServer: typeof utils.defaultAuthServerMonitor;
agent: MasterAgent | MonitorAgent;
id: string;
host: string;
type: string;
constructor(_opts: ConsoleServiceOpts) {
super();
this.port = _opts.port;
this.env = _opts.env;
this.values = {};
let masterOpts = _opts as MasterConsoleServiceOpts;
let monitorOpts = _opts as MonitorConsoleServiceOpts;
this.master = masterOpts.master;
this.modules = {};
this.commands = {
'list': listCommand,
'enable': enableCommand,
'disable': disableCommand
};
if (this.master) {
this.authUser = masterOpts.authUser || utils.defaultAuthUser;
this.authServer = masterOpts.authServer || utils.defaultAuthServerMaster;
this.agent = new MasterAgent(this, masterOpts);
} else {
this.type = monitorOpts.type;
this.id = monitorOpts.id;
this.host = monitorOpts.host;
this.authServer = monitorOpts.authServer || utils.defaultAuthServerMonitor;
this.agent = new MonitorAgent({
consoleService: this,
id: this.id,
type: this.type,
info: monitorOpts.info
});
}
}
/**
* start master or monitor
*
* @param {Function} cb callback function
* @api public
*/
start(cb: (err?: Error) => void) {
if (this.master) {
let self = this;
(this.agent as MasterAgent).listen(this.port, function (err) {
if (!!err) {
utils.invokeCallback(cb, err);
return;
}
exportEvent(self, self.agent, 'register');
exportEvent(self, self.agent, 'disconnect');
exportEvent(self, self.agent, 'reconnect');
process.nextTick(function () {
utils.invokeCallback(cb);
});
});
} else {
logger.info('try to connect master: %j, %j, %j', this.type, this.host, this.port);
(this.agent as MonitorAgent).connect(this.port, this.host, cb);
exportEvent(this, this.agent, 'close');
}
exportEvent(this, this.agent, 'error');
for (let mid in this.modules) {
this.enable(mid);
}
}
/**
* stop console modules and stop master server
*
* @api public
*/
stop() {
for (let mid in this.modules) {
this.disable(mid);
}
this.agent.close();
}
/**
* register a new adminConsole module
*
* @param {String} moduleId adminConsole id/name
* @param {Object} module module object
* @api public
*/
register(moduleId: string, module: IModule) {
this.modules[moduleId] = registerRecord(this, moduleId, module);
}
/**
* enable adminConsole module
*
* @param {String} moduleId adminConsole id/name
* @api public
*/
enable(moduleId: string) {
let record = this.modules[moduleId];
if (record && !record.enable) {
record.enable = true;
addToSchedule(this, record);
return true;
}
return false;
}
/**
* disable adminConsole module
*
* @param {String} moduleId adminConsole id/name
* @api public
*/
disable(moduleId: string) {
let record = this.modules[moduleId];
if (record && record.enable) {
record.enable = false;
if (record.schedule && record.jobId) {
schedule.cancelJob(record.jobId);
record.jobId = null;
}
return true;
}
return false;
}
/**
* call concrete module and handler(monitorHandler,masterHandler,clientHandler)
*
* @param {String} moduleId adminConsole id/name
* @param {String} method handler
* @param {Object} msg message
* @param {Function} cb callback function
* @api public
*/
execute(moduleId: string, method: string, msg: any, cb: (err ?: Error|string , msg?: any) => void) {
let self = this;
let m = this.modules[moduleId];
if (!m) {
logger.error('unknown module: %j.', moduleId);
cb('unknown moduleId:' + moduleId);
return;
}
if (!m.enable) {
logger.error('module %j is disable.', moduleId);
cb('module ' + moduleId + ' is disable');
return;
}
let module = m.module;
if (!module || typeof module[method] !== 'function') {
logger.error('module %j dose not have a method called %j.', moduleId, method);
cb('module ' + moduleId + ' dose not have a method called ' + method);
return;
}
let log: AdminLogInfo = {
action: 'execute',
moduleId: moduleId,
method: method,
msg: msg
};
let aclMsg = aclControl(self.agent as MasterAgent, 'execute', method, moduleId, msg);
if (aclMsg !== 0 && aclMsg !== 1) {
log['error'] = aclMsg;
self.emit('admin-log', log, aclMsg);
cb(new Error(aclMsg.toString()), null);
return;
}
if (method === 'clientHandler') {
self.emit('admin-log', log);
}
module[method](this.agent, msg, cb);
}
command(command: string, moduleId: string, msg: any, cb: (err ?: Error|string , msg?: any) => void) {
let self = this;
let fun = this.commands[command];
if (!fun || typeof fun !== 'function') {
cb('unknown command:' + command);
return;
}
let log: AdminLogInfo = {
action: 'command',
moduleId: moduleId,
msg: msg
};
let aclMsg = aclControl(self.agent as MasterAgent, 'command', null, moduleId, msg);
if (aclMsg !== 0 && aclMsg !== 1) {
log['error'] = aclMsg;
self.emit('admin-log', log, aclMsg);
cb(new Error(aclMsg.toString()), null);
return;
}
self.emit('admin-log', log);
fun(this, moduleId, msg, cb);
}
/**
* set module data to a map
*
* @param {String} moduleId adminConsole id/name
* @param {Object} value module data
* @api public
*/
set(moduleId: string, value: any) {
this.values[moduleId] = value;
}
/**
* get module data from map
*
* @param {String} moduleId adminConsole id/name
* @api public
*/
get(moduleId: string) {
return this.values[moduleId];
}
}
/**
* register a module service
*
* @param {Object} service consoleService object
* @param {String} moduleId adminConsole id/name
* @param {Object} module module object
* @api private
*/
let registerRecord = function (service: ConsoleService, moduleId: string, module: IModule) {
let record: any = {
moduleId: moduleId,
module: module,
enable: false
};
if (module.type && module.interval) {
if (!service.master && record.module.type === 'push' || service.master && record.module.type !== 'push') {
// push for monitor or pull for master(default)
record.delay = module.delay || 0;
record.interval = module.interval || 1;
// normalize the arguments
if (record.delay < 0) {
record.delay = 0;
}
if (record.interval < 0) {
record.interval = 1;
}
record.interval = Math.ceil(record.interval);
record.delay *= MS_OF_SECOND;
record.interval *= MS_OF_SECOND;
record.schedule = true;
}
}
return record;
};
/**
* schedule console module
*
* @param {Object} service consoleService object
* @param {Object} record module object
* @api private
*/
let addToSchedule = function (service: ConsoleService, record: ModuleRecord) {
if (record && record.schedule) {
record.jobId = schedule.scheduleJob({
start: Date.now() + record.delay,
period: record.interval
},
doScheduleJob, {
service: service,
record: record
});
}
};
/**
* run schedule job
*
* @param {Object} args argments
* @api private
*/
let doScheduleJob = function (args: {service: ConsoleService , record: ModuleRecord}) {
let service: ConsoleService = args.service;
let record = args.record;
if (!service || !record || !record.module || !record.enable) {
return;
}
if (service.master) {
record.module.masterHandler(service.agent as MasterAgent, null, function (err: Error) {
logger.error('interval push should not have a callback.');
});
} else {
record.module.monitorHandler(service.agent as MonitorAgent, null, function (err: Error) {
logger.error('interval push should not have a callback.');
});
}
};
/**
* export closure function out
*
* @param {Function} outer outer function
* @param {Function} inner inner function
* @param {object} event
* @api private
*/
let exportEvent = function (outer: ConsoleService, inner: MasterAgent | MonitorAgent, event: string) {
inner.on(event, function () {
let args = Array.prototype.slice.call(arguments, 0);
args.unshift(event);
outer.emit.apply(outer, args);
});
};
/**
* List current modules
*/
let listCommand = function (consoleService: ConsoleService, moduleId: string, msg: any, cb: Callback) {
let modules = consoleService.modules;
let result = [];
for (let moduleId in modules) {
if (/^__\w+__$/.test(moduleId)) {
continue;
}
result.push(moduleId);
}
cb(null, {
modules: result
});
};
/**
* enable module in current server
*/
let enableCommand = function (consoleService: ConsoleService, moduleId: string, msg: any, cb: Callback) {
if (!moduleId) {
logger.error('fail to enable admin module for ' + moduleId);
cb('empty moduleId');
return;
}
let modules = consoleService.modules;
if (!modules[moduleId]) {
cb(null, protocol.PRO_FAIL);
return;
}
if (consoleService.master) {
consoleService.enable(moduleId);
(consoleService.agent as MasterAgent).notifyCommand('enable', moduleId, msg);
cb(null, protocol.PRO_OK);
} else {
consoleService.enable(moduleId);
cb(null, protocol.PRO_OK);
}
};
/**
* disable module in current server
*/
let disableCommand = function (consoleService: ConsoleService, moduleId: string, msg: any, cb: Callback) {
if (!moduleId) {
logger.error('fail to enable admin module for ' + moduleId);
cb('empty moduleId');
return;
}
let modules = consoleService.modules;
if (!modules[moduleId]) {
cb(null, protocol.PRO_FAIL);
return;
}
if (consoleService.master) {
consoleService.disable(moduleId);
(consoleService.agent as MasterAgent).notifyCommand('disable', moduleId, msg);
cb(null, protocol.PRO_OK);
} else {
consoleService.disable(moduleId);
cb(null, protocol.PRO_OK);
}
};
let aclControl = function (agent: MasterAgent, action: string, method: string, moduleId: string, msg: any) {
if (action === 'execute') {
if (method !== 'clientHandler' || moduleId !== '__console__') {
return 0;
}
let signal = msg.signal;
if (!signal || !(signal === 'stop' || signal === 'add' || signal === 'kill')) {
return 0;
}
}
let clientId = msg.clientId;
if (!clientId) {
return 'Unknow clientId';
}
let _client = agent.getClientById(clientId);
if (_client && _client.info && (_client.info as AdminUserInfo).level) {
let level = (_client.info as AdminUserInfo).level;
if (level > 1) {
return 'Command permission denied';
}
} else {
return 'Client info error';
}
return 1;
};
/**
* Create master ConsoleService
*
* @param {Object} opts construct parameter
* opts.port {String | Number} listen port for master console
*/
export function createMasterConsole(opts: ConsoleServiceOpts) {
(opts as MasterConsoleServiceOpts).master = true;
return new ConsoleService(opts);
}
/**
* Create monitor ConsoleService
*
* @param {Object} opts construct parameter
* opts.type {String} server type, 'master', 'connector', etc.
* opts.id {String} server id
* opts.host {String} master server host
* opts.port {String | Number} master port
*/
export function createMonitorConsole(opts: ConsoleServiceOpts) {
return new ConsoleService(opts);
} | the_stack |
import * as React from 'react';
import { cloneElement, Component, createElement, CSSProperties } from 'react';
import raf, { cancel as caf } from 'raf';
import css from 'dom-css';
//
import { ScrollValues, ScrollbarsProps, StyleKeys } from './types';
import {
getFinalClasses,
getScrollbarWidth,
returnFalse,
getInnerWidth,
getInnerHeight,
} from '../utils';
import { createStyles } from './styles';
interface State {
didMountUniversal: boolean;
scrollbarWidth: number;
}
export class Scrollbars extends Component<ScrollbarsProps, State> {
container: Element | null = null;
detectScrollingInterval: any; // Node timeout bug
dragging: boolean = false;
hideTracksTimeout: any; // Node timeout bug
lastViewScrollLeft?: number;
lastViewScrollTop?: number;
prevPageX?: number;
prevPageY?: number;
requestFrame?: number;
scrolling: boolean = false;
styles: Record<StyleKeys, CSSProperties>;
thumbHorizontal?: HTMLDivElement;
thumbVertical?: HTMLDivElement;
trackHorizontal?: HTMLDivElement;
trackMouseOver: boolean = false;
trackVertical?: HTMLDivElement;
view?: HTMLElement;
viewScrollLeft?: number;
viewScrollTop?: number;
static defaultProps = {
autoHeight: false,
autoHeightMax: 200,
autoHeightMin: 0,
autoHide: false,
autoHideDuration: 200,
autoHideTimeout: 1000,
disableDefaultStyles: false,
hideTracksWhenNotNeeded: false,
renderThumbHorizontal: (props) => <div {...props} />,
renderThumbVertical: (props) => <div {...props} />,
renderTrackHorizontal: (props) => <div {...props} />,
renderTrackVertical: (props) => <div {...props} />,
renderView: (props) => <div {...props} />,
tagName: 'div',
thumbMinSize: 30,
universal: false,
};
constructor(props: ScrollbarsProps) {
super(props);
this.styles = createStyles(this.props.disableDefaultStyles);
this.getScrollLeft = this.getScrollLeft.bind(this);
this.getScrollTop = this.getScrollTop.bind(this);
this.getScrollWidth = this.getScrollWidth.bind(this);
this.getScrollHeight = this.getScrollHeight.bind(this);
this.getClientWidth = this.getClientWidth.bind(this);
this.getClientHeight = this.getClientHeight.bind(this);
this.getValues = this.getValues.bind(this);
this.getThumbHorizontalWidth = this.getThumbHorizontalWidth.bind(this);
this.getThumbVerticalHeight = this.getThumbVerticalHeight.bind(this);
this.getScrollLeftForOffset = this.getScrollLeftForOffset.bind(this);
this.getScrollTopForOffset = this.getScrollTopForOffset.bind(this);
this.scrollLeft = this.scrollLeft.bind(this);
this.scrollTop = this.scrollTop.bind(this);
this.scrollToLeft = this.scrollToLeft.bind(this);
this.scrollToTop = this.scrollToTop.bind(this);
this.scrollToRight = this.scrollToRight.bind(this);
this.scrollToBottom = this.scrollToBottom.bind(this);
this.handleTrackMouseEnter = this.handleTrackMouseEnter.bind(this);
this.handleTrackMouseLeave = this.handleTrackMouseLeave.bind(this);
this.handleHorizontalTrackMouseDown = this.handleHorizontalTrackMouseDown.bind(this);
this.handleVerticalTrackMouseDown = this.handleVerticalTrackMouseDown.bind(this);
this.handleHorizontalThumbMouseDown = this.handleHorizontalThumbMouseDown.bind(this);
this.handleVerticalThumbMouseDown = this.handleVerticalThumbMouseDown.bind(this);
this.handleWindowResize = this.handleWindowResize.bind(this);
this.handleScroll = this.handleScroll.bind(this);
this.handleDrag = this.handleDrag.bind(this);
this.handleDragEnd = this.handleDragEnd.bind(this);
this.state = {
didMountUniversal: false,
scrollbarWidth: getScrollbarWidth(),
};
}
componentDidMount() {
this.addListeners();
this.update();
this.componentDidMountUniversal();
}
componentDidMountUniversal() {
// eslint-disable-line react/sort-comp
const { universal } = this.props;
if (!universal) return;
this.setState({ didMountUniversal: true });
}
componentDidUpdate() {
this.update();
}
componentWillUnmount() {
this.removeListeners();
this.requestFrame && caf(this.requestFrame);
clearTimeout(this.hideTracksTimeout);
clearInterval(this.detectScrollingInterval);
}
getScrollLeft() {
if (!this.view) return 0;
return this.view.scrollLeft;
}
getScrollTop() {
if (!this.view) return 0;
return this.view.scrollTop;
}
getScrollWidth() {
if (!this.view) return 0;
return this.view.scrollWidth;
}
getScrollHeight() {
if (!this.view) return 0;
return this.view.scrollHeight;
}
getClientWidth() {
if (!this.view) return 0;
return this.view.clientWidth;
}
getClientHeight() {
if (!this.view) return 0;
return this.view.clientHeight;
}
getValues() {
const {
scrollLeft = 0,
scrollTop = 0,
scrollWidth = 0,
scrollHeight = 0,
clientWidth = 0,
clientHeight = 0,
} = this.view || {};
return {
left: scrollLeft / (scrollWidth - clientWidth) || 0,
top: scrollTop / (scrollHeight - clientHeight) || 0,
scrollLeft,
scrollTop,
scrollWidth,
scrollHeight,
clientWidth,
clientHeight,
};
}
getThumbHorizontalWidth() {
if (!this.view || !this.trackHorizontal) return 0;
const { thumbSize, thumbMinSize } = this.props;
const { scrollWidth, clientWidth } = this.view;
const trackWidth = getInnerWidth(this.trackHorizontal);
const width = Math.ceil((clientWidth / scrollWidth) * trackWidth);
if (trackWidth === width) return 0;
if (thumbSize) return thumbSize;
return Math.max(width, thumbMinSize);
}
getThumbVerticalHeight() {
if (!this.view || !this.trackVertical) return 0;
const { thumbSize, thumbMinSize } = this.props;
const { scrollHeight, clientHeight } = this.view;
const trackHeight = getInnerHeight(this.trackVertical);
const height = Math.ceil((clientHeight / scrollHeight) * trackHeight);
if (trackHeight === height) return 0;
if (thumbSize) return thumbSize;
return Math.max(height, thumbMinSize);
}
getScrollLeftForOffset(offset) {
if (!this.view || !this.trackHorizontal) return 0;
const { scrollWidth, clientWidth } = this.view;
const trackWidth = getInnerWidth(this.trackHorizontal);
const thumbWidth = this.getThumbHorizontalWidth();
return (offset / (trackWidth - thumbWidth)) * (scrollWidth - clientWidth);
}
getScrollTopForOffset(offset) {
if (!this.view || !this.trackVertical) return 0;
const { scrollHeight, clientHeight } = this.view;
const trackHeight = getInnerHeight(this.trackVertical);
const thumbHeight = this.getThumbVerticalHeight();
return (offset / (trackHeight - thumbHeight)) * (scrollHeight - clientHeight);
}
scrollLeft(left = 0) {
if (!this.view) return;
this.view.scrollLeft = left;
}
scrollTop(top = 0) {
if (!this.view) return;
this.view.scrollTop = top;
}
scrollToLeft() {
if (!this.view) return;
this.view.scrollLeft = 0;
}
scrollToTop() {
if (!this.view) return;
this.view.scrollTop = 0;
}
scrollToRight() {
if (!this.view) return;
this.view.scrollLeft = this.view.scrollWidth;
}
scrollToBottom() {
if (!this.view) return;
this.view.scrollTop = this.view.scrollHeight;
}
scrollToY(y: number) {
if (!this.view) return;
this.view.scrollTop = y;
}
addListeners() {
/* istanbul ignore if */
if (
typeof document === 'undefined' ||
!this.view ||
!this.trackHorizontal ||
!this.trackVertical ||
!this.thumbVertical ||
!this.thumbHorizontal
)
return;
const { view, trackHorizontal, trackVertical, thumbHorizontal, thumbVertical } = this;
view.addEventListener('scroll', this.handleScroll);
if (!this.state.scrollbarWidth) return;
trackHorizontal.addEventListener('mouseenter', this.handleTrackMouseEnter);
trackHorizontal.addEventListener('mouseleave', this.handleTrackMouseLeave);
trackHorizontal.addEventListener('mousedown', this.handleHorizontalTrackMouseDown);
trackVertical.addEventListener('mouseenter', this.handleTrackMouseEnter);
trackVertical.addEventListener('mouseleave', this.handleTrackMouseLeave);
trackVertical.addEventListener('mousedown', this.handleVerticalTrackMouseDown);
thumbHorizontal.addEventListener('mousedown', this.handleHorizontalThumbMouseDown);
thumbVertical.addEventListener('mousedown', this.handleVerticalThumbMouseDown);
window.addEventListener('resize', this.handleWindowResize);
}
removeListeners() {
/* istanbul ignore if */
if (
typeof document === 'undefined' ||
!this.view ||
!this.trackHorizontal ||
!this.trackVertical ||
!this.thumbVertical ||
!this.thumbHorizontal
)
return;
const { view, trackHorizontal, trackVertical, thumbHorizontal, thumbVertical } = this;
view.removeEventListener('scroll', this.handleScroll);
if (!this.state.scrollbarWidth) return;
trackHorizontal.removeEventListener('mouseenter', this.handleTrackMouseEnter);
trackHorizontal.removeEventListener('mouseleave', this.handleTrackMouseLeave);
trackHorizontal.removeEventListener('mousedown', this.handleHorizontalTrackMouseDown);
trackVertical.removeEventListener('mouseenter', this.handleTrackMouseEnter);
trackVertical.removeEventListener('mouseleave', this.handleTrackMouseLeave);
trackVertical.removeEventListener('mousedown', this.handleVerticalTrackMouseDown);
thumbHorizontal.removeEventListener('mousedown', this.handleHorizontalThumbMouseDown);
thumbVertical.removeEventListener('mousedown', this.handleVerticalThumbMouseDown);
window.removeEventListener('resize', this.handleWindowResize);
// Possibly setup by `handleDragStart`
this.teardownDragging();
}
handleScroll(event) {
const { onScroll, onScrollFrame } = this.props;
if (onScroll) onScroll(event);
this.update((values: ScrollValues) => {
const { scrollLeft, scrollTop } = values;
this.viewScrollLeft = scrollLeft;
this.viewScrollTop = scrollTop;
if (onScrollFrame) onScrollFrame(values);
});
this.detectScrolling();
}
handleScrollStart() {
const { onScrollStart } = this.props;
if (onScrollStart) onScrollStart();
this.handleScrollStartAutoHide();
}
handleScrollStartAutoHide() {
const { autoHide } = this.props;
if (!autoHide) return;
this.showTracks();
}
handleScrollStop() {
const { onScrollStop } = this.props;
if (onScrollStop) onScrollStop();
this.handleScrollStopAutoHide();
}
handleScrollStopAutoHide() {
const { autoHide } = this.props;
if (!autoHide) return;
this.hideTracks();
}
handleWindowResize() {
this.update();
}
handleHorizontalTrackMouseDown(event) {
if (!this.view) return;
event.preventDefault();
const { target, clientX } = event;
const { left: targetLeft } = target.getBoundingClientRect();
const thumbWidth = this.getThumbHorizontalWidth();
const offset = Math.abs(targetLeft - clientX) - thumbWidth / 2;
this.view.scrollLeft = this.getScrollLeftForOffset(offset);
}
handleVerticalTrackMouseDown(event) {
if (!this.view) return;
event.preventDefault();
const { target, clientY } = event;
const { top: targetTop } = target.getBoundingClientRect();
const thumbHeight = this.getThumbVerticalHeight();
const offset = Math.abs(targetTop - clientY) - thumbHeight / 2;
this.view.scrollTop = this.getScrollTopForOffset(offset);
}
handleHorizontalThumbMouseDown(event) {
event.preventDefault();
this.handleDragStart(event);
const { target, clientX } = event;
const { offsetWidth } = target;
const { left } = target.getBoundingClientRect();
this.prevPageX = offsetWidth - (clientX - left);
}
handleVerticalThumbMouseDown(event) {
event.preventDefault();
this.handleDragStart(event);
const { target, clientY } = event;
const { offsetHeight } = target;
const { top } = target.getBoundingClientRect();
this.prevPageY = offsetHeight - (clientY - top);
}
setupDragging() {
css(document.body, this.styles.disableSelectStyle);
document.addEventListener('mousemove', this.handleDrag);
document.addEventListener('mouseup', this.handleDragEnd);
document.onselectstart = returnFalse;
}
teardownDragging() {
css(document.body, this.styles.disableSelectStyleReset);
document.removeEventListener('mousemove', this.handleDrag);
document.removeEventListener('mouseup', this.handleDragEnd);
document.onselectstart = null;
}
handleDragStart(event) {
this.dragging = true;
event.stopImmediatePropagation();
this.setupDragging();
}
handleDrag(event) {
if (this.prevPageX && this.trackHorizontal && this.view) {
const { clientX } = event;
const { left: trackLeft } = this.trackHorizontal.getBoundingClientRect();
const thumbWidth = this.getThumbHorizontalWidth();
const clickPosition = thumbWidth - this.prevPageX;
const offset = -trackLeft + clientX - clickPosition;
this.view.scrollLeft = this.getScrollLeftForOffset(offset);
}
if (this.prevPageY && this.trackVertical && this.view) {
const { clientY } = event;
const { top: trackTop } = this.trackVertical.getBoundingClientRect();
const thumbHeight = this.getThumbVerticalHeight();
const clickPosition = thumbHeight - this.prevPageY;
const offset = -trackTop + clientY - clickPosition;
this.view.scrollTop = this.getScrollTopForOffset(offset);
}
return false;
}
handleDragEnd() {
this.dragging = false;
this.prevPageX = this.prevPageY = 0;
this.teardownDragging();
this.handleDragEndAutoHide();
}
handleDragEndAutoHide() {
const { autoHide } = this.props;
if (!autoHide) return;
this.hideTracks();
}
handleTrackMouseEnter() {
this.trackMouseOver = true;
this.handleTrackMouseEnterAutoHide();
}
handleTrackMouseEnterAutoHide() {
const { autoHide } = this.props;
if (!autoHide) return;
this.showTracks();
}
handleTrackMouseLeave() {
this.trackMouseOver = false;
this.handleTrackMouseLeaveAutoHide();
}
handleTrackMouseLeaveAutoHide() {
const { autoHide } = this.props;
if (!autoHide) return;
this.hideTracks();
}
showTracks() {
clearTimeout(this.hideTracksTimeout);
css(this.trackHorizontal, { opacity: 1 });
css(this.trackVertical, { opacity: 1 });
}
hideTracks() {
if (this.dragging) return;
if (this.scrolling) return;
if (this.trackMouseOver) return;
const { autoHideTimeout } = this.props;
clearTimeout(this.hideTracksTimeout);
this.hideTracksTimeout = setTimeout(() => {
css(this.trackHorizontal, { opacity: 0 });
css(this.trackVertical, { opacity: 0 });
}, autoHideTimeout);
}
detectScrolling() {
if (this.scrolling) return;
this.scrolling = true;
this.handleScrollStart();
this.detectScrollingInterval = setInterval(() => {
if (
this.lastViewScrollLeft === this.viewScrollLeft &&
this.lastViewScrollTop === this.viewScrollTop
) {
clearInterval(this.detectScrollingInterval);
this.scrolling = false;
this.handleScrollStop();
}
this.lastViewScrollLeft = this.viewScrollLeft;
this.lastViewScrollTop = this.viewScrollTop;
}, 100);
}
raf(callback) {
if (this.requestFrame) raf.cancel(this.requestFrame);
this.requestFrame = raf(() => {
this.requestFrame = undefined;
callback();
});
}
update(callback?: (values: ScrollValues) => void) {
this.raf(() => this._update(callback));
}
_update(callback) {
const { onUpdate, hideTracksWhenNotNeeded } = this.props;
const values = this.getValues();
const freshScrollbarWidth = getScrollbarWidth();
if (this.state.scrollbarWidth !== freshScrollbarWidth) {
this.setState({ scrollbarWidth: freshScrollbarWidth });
}
if (this.state.scrollbarWidth) {
const { scrollLeft, clientWidth, scrollWidth } = values;
const trackHorizontalWidth = getInnerWidth(this.trackHorizontal);
const thumbHorizontalWidth = this.getThumbHorizontalWidth();
const thumbHorizontalX =
(scrollLeft / (scrollWidth - clientWidth)) * (trackHorizontalWidth - thumbHorizontalWidth);
const thumbHorizontalStyle = {
width: thumbHorizontalWidth,
transform: `translateX(${thumbHorizontalX}px)`,
};
const { scrollTop, clientHeight, scrollHeight } = values;
const trackVerticalHeight = getInnerHeight(this.trackVertical);
const thumbVerticalHeight = this.getThumbVerticalHeight();
const thumbVerticalY =
(scrollTop / (scrollHeight - clientHeight)) * (trackVerticalHeight - thumbVerticalHeight);
const thumbVerticalStyle = {
height: thumbVerticalHeight,
transform: `translateY(${thumbVerticalY}px)`,
};
if (hideTracksWhenNotNeeded) {
const trackHorizontalStyle = {
visibility: scrollWidth > clientWidth ? 'visible' : 'hidden',
};
const trackVerticalStyle = {
visibility: scrollHeight > clientHeight ? 'visible' : 'hidden',
};
css(this.trackHorizontal, trackHorizontalStyle);
css(this.trackVertical, trackVerticalStyle);
}
css(this.thumbHorizontal, thumbHorizontalStyle);
css(this.thumbVertical, thumbVerticalStyle);
}
if (onUpdate) onUpdate(values);
if (typeof callback !== 'function') return;
callback(values);
}
render() {
const { scrollbarWidth, didMountUniversal } = this.state;
/* eslint-disable no-unused-vars */
const {
autoHeight,
autoHeightMax,
autoHeightMin,
autoHide,
autoHideDuration,
autoHideTimeout,
children,
classes,
hideTracksWhenNotNeeded,
onScroll,
onScrollFrame,
onScrollStart,
onScrollStop,
onUpdate,
renderThumbHorizontal,
renderThumbVertical,
renderTrackHorizontal,
renderTrackVertical,
renderView,
style,
tagName,
thumbMinSize,
thumbSize,
universal,
disableDefaultStyles,
...props
} = this.props;
/* eslint-enable no-unused-vars */
const {
containerStyleAutoHeight,
containerStyleDefault,
thumbStyleDefault,
trackHorizontalStyleDefault,
trackVerticalStyleDefault,
viewStyleAutoHeight,
viewStyleDefault,
viewStyleUniversalInitial,
} = this.styles;
const containerStyle = {
...containerStyleDefault,
...(autoHeight && {
...containerStyleAutoHeight,
minHeight: autoHeightMin,
maxHeight: autoHeightMax,
}),
...style,
};
const viewStyle = {
...viewStyleDefault,
// Hide scrollbars by setting a negative margin
marginRight: scrollbarWidth ? -scrollbarWidth : 0,
marginBottom: scrollbarWidth ? -scrollbarWidth : 0,
...(autoHeight && {
...viewStyleAutoHeight,
// Add scrollbarWidth to autoHeight in order to compensate negative margins
minHeight:
typeof autoHeightMin === 'string'
? `calc(${autoHeightMin} + ${scrollbarWidth}px)`
: autoHeightMin + scrollbarWidth,
maxHeight:
typeof autoHeightMax === 'string'
? `calc(${autoHeightMax} + ${scrollbarWidth}px)`
: autoHeightMax + scrollbarWidth,
}),
// Override min/max height for initial universal rendering
...(autoHeight &&
universal &&
!didMountUniversal && {
minHeight: autoHeightMin,
maxHeight: autoHeightMax,
}),
// Override
...(universal && !didMountUniversal && viewStyleUniversalInitial),
};
const trackAutoHeightStyle = {
transition: `opacity ${autoHideDuration}ms`,
opacity: 0,
};
const trackHorizontalStyle = {
...trackHorizontalStyleDefault,
...(autoHide && trackAutoHeightStyle),
...((!scrollbarWidth || (universal && !didMountUniversal)) && {
display: 'none',
}),
};
const trackVerticalStyle = {
...trackVerticalStyleDefault,
...(autoHide && trackAutoHeightStyle),
...((!scrollbarWidth || (universal && !didMountUniversal)) && {
display: 'none',
}),
};
const mergedClasses = getFinalClasses(this.props);
return createElement(
tagName,
{
...props,
className: mergedClasses.root,
style: containerStyle,
ref: (ref) => {
this.container = ref;
},
},
[
cloneElement(
renderView({
style: viewStyle,
className: mergedClasses.view,
}),
{
key: 'view',
ref: (ref) => {
this.view = ref;
},
},
children,
),
cloneElement(
renderTrackHorizontal({
style: trackHorizontalStyle,
className: mergedClasses.trackHorizontal,
}),
{
key: 'trackHorizontal',
ref: (ref) => {
this.trackHorizontal = ref;
},
},
cloneElement(
renderThumbHorizontal({
style: thumbStyleDefault,
className: mergedClasses.thumbHorizontal,
}),
{
ref: (ref) => {
this.thumbHorizontal = ref;
},
},
),
),
cloneElement(
renderTrackVertical({
style: trackVerticalStyle,
className: mergedClasses.trackVertical,
}),
{
key: 'trackVertical',
ref: (ref) => {
this.trackVertical = ref;
},
},
cloneElement(
renderThumbVertical({
style: thumbStyleDefault,
className: mergedClasses.thumbVertical,
}),
{
ref: (ref) => {
this.thumbVertical = ref;
},
},
),
),
],
);
}
} | the_stack |
import * as path from 'path';
import * as npmRun from 'npm-run';
import * as assert from "yeoman-assert";
import * as lodash from 'lodash';
import * as helpers from "yeoman-test";
export const DEPENDENCIES = [
'../../../generators/tab',
'../../../generators/bot',
'../../../generators/connector',
'../../../generators/custombot',
'../../../generators/messageExtension',
'../../../generators/localization'
];
export const GENERATOR_PATH = path.join(__dirname, '../../generators/app');
export const TEMP_GENERATOR_PATTERN = './temp-templates/**/*.*';
export const TEMP_TEST_PATH = path.join(__dirname, '../../temp-templates');
export const TEMP_TAB_GENERATOR_PATH = path.join(__dirname, '../../temp-templates/tab');
export const TEMP_BOT_GENERATOR_PATH = path.join(__dirname, '../../temp-templates/bot');
export const TEMP_MESSAGEEXTSION_GENERATOR_PATH = path.join(__dirname, '../../temp-templates/messageExtension');
export const TEMP_CONNECTOR_GENERATOR_PATH = path.join(__dirname, '../../temp-templates/connector');
export const TEMP_CUSTOMBOT_GENERATOR_PATH = path.join(__dirname, '../../temp-templates/custombot');
export const TEMP_LOCALIZATION_GENERATOR_PATH = path.join(__dirname, '../../temp-templates/localization');
export const ROOT_FILES = [
'.gitignore',
'gulpfile.js',
'package.json',
'README.md',
'webpack.config.js',
'Dockerfile'
];
export const VSCODE_FILES = [
'.vscode/launch.json'
];
export const LINT_FILES = [
".eslintrc.json",
".eslintignore",
"src/server/.eslintrc.json",
"src/client/.eslintrc.json"
]
export const TEST_FILES = [
'src/test/test-setup.js',
'src/test/test-shim.js',
'src/client/jest.config.js',
'src/server/jest.config.js'
];
export const MANIFEST_FILES = [
'src/manifest/icon-color.png',
'src/manifest/icon-outline.png',
'src/manifest/manifest.json',
];
export const WEB_FILES = [
'src/public/assets/icon.png',
'src/public/index.html',
'src/public/privacy.html',
'src/public/tou.html',
"src/public/styles/main.scss"
];
export const APP_FILES = [
'src/server/server.ts',
'src/server/TeamsAppsComponents.ts',
"src/server/tsconfig.json"
];
export const SCRIPT_FILES = [
'src/client/client.ts',
"src/client/tsconfig.json"
];
export const DIST_FILES = [
'dist/server.js',
'dist/web/index.html',
'dist/web/privacy.html',
'dist/web/tou.html',
'dist/web/assets/icon.png',
'dist/web/scripts/client.js',
'dist/web/styles/main.css',
];
export const PACKAGE_FILES = [
'package/teamssolution.zip'
];
export const basePrompts = {
"solutionName": "teams-solution",
"whichFolder": "current",
"name": "teamsSolution",
"developer": "generator teams developer",
"lintingSupport": true
};
export async function runNpmCommand(command: string, path: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
npmRun.exec(command, { cwd: path },
function (err: any, stdout: any, stderr: any) {
if (err) {
console.log("err:" + err);
console.log("stdout:" + stdout);
console.log("stderr:" + stderr);
resolve(false);
} else {
resolve(true);
}
});
});
}
// Define the available schemas
export const SCHEMA_18 = 'https://developer.microsoft.com/en-us/json-schemas/teams/v1.8/MicrosoftTeams.schema.json';
export const SCHEMA_19 = 'https://developer.microsoft.com/en-us/json-schemas/teams/v1.9/MicrosoftTeams.schema.json';
export const SCHEMA_110 = 'https://developer.microsoft.com/en-us/json-schemas/teams/v1.10/MicrosoftTeams.schema.json';
export const SCHEMA_111 = 'https://developer.microsoft.com/en-us/json-schemas/teams/v1.11/MicrosoftTeams.schema.json';
export const SCHEMA_DEVPREVIEW = 'https://raw.githubusercontent.com/OfficeDev/microsoft-teams-app-schema/preview/DevPreview/MicrosoftTeams.schema.json';
export const INTEGRATION_TEST_VERSIONS = ["v1.9", "v1.10"]; // only keep two versions, so we can stay under Github 360 minute rule
export const SCHEMAS: { [key: string]: string } = {
"v1.8": SCHEMA_18,
"v1.9": SCHEMA_19,
"v1.10": SCHEMA_110,
"v1.11": SCHEMA_111,
"devPreview": SCHEMA_DEVPREVIEW
}
// All the paths for upgrading
const UPGRADE_PATHS: { [key: string]: string[] } = {
"v1.8": ["v1.9", "v1.10", "devPreview"],
"v1.9": ["v1.10", "v1.11", "devPreview"],
"v1.10": ["v1.11", "devPreview"],
"v1.11": ["devPreview"]
}
export enum TestTypes {
UNIT = "UNIT",
INTEGRATION = "INTEGRATION"
}
export function coreTests(manifestVersion: string, prompts: any, projectPath: string) {
it("Should have root files", async () => {
assert.file(ROOT_FILES);
});
it("Should have app files", async () => {
assert.file(APP_FILES);
});
it("Should have script files", async () => {
assert.file(SCRIPT_FILES);
});
it("Should have web files", async () => {
assert.file(WEB_FILES);
});
it("Should have vscode files", async () => {
assert.file(VSCODE_FILES);
});
it("Should have manifest files", async () => {
assert.file(MANIFEST_FILES);
});
it("Should have correct schema", async () => {
assert.fileContent("src/manifest/manifest.json", SCHEMAS[manifestVersion]);
});
it("Should have correct React version", async () => {
assert.jsonFileContent("package.json", { dependencies: { "react": "^16.8.6", "react-dom": "^16.8.6" } });
});
it("Should have correct React typings version", async () => {
assert.jsonFileContent("package.json", { devDependencies: { "@types/react": "16.8.10", "@types/react-dom": "16.8.3" } });
});
it("Should have a reference to Fluentui", async () => {
assert.jsonFileContent("package.json", { dependencies: { "@fluentui/react-northstar": {} } });
});
it("Should have engines >=12", async () => {
assert.jsonFileContent("package.json", { engines: { "node": ">=12" } });
});
if (prompts.lintingSupport) {
it("Should have linting files", async () => {
assert.file(LINT_FILES);
});
it("Should have a lint script", async () => {
assert.jsonFileContent("package.json", { scripts: { "lint": "eslint ./src --ext .js,.jsx,.ts,.tsx" } });
})
it("Should reference ESLint plugin in webpack config", async () => {
assert.fileContent("webpack.config.js", "ESLintPlugin");
})
} else {
it("Should not have linting files", async () => {
assert.noFile(LINT_FILES);
});
it("Should not have a lint script", async () => {
assert.noJsonFileContent("package.json", { scripts: { "lint": "eslint ./src --ext .js,.jsx,.ts,.tsx" } });
})
it("Should not reference ESLint plugin in webpack config", async () => {
assert.noFileContent("webpack.config.js", "ESLintPlugin");
})
}
if (prompts.unitTestsEnabled) {
it("Should have unit test files", async () => {
assert.file(TEST_FILES);
});
it("Should have a test script", async () => {
assert.jsonFileContent("package.json", { scripts: { "test": "jest" } });
})
it("Should have a coverage script", async () => {
assert.jsonFileContent("package.json", { scripts: { "coverage": "jest --coverage" } });
})
} else {
it("Should not have unit test files", async () => {
assert.noFile(TEST_FILES);
});
it("Should not have a test script", async () => {
assert.noJsonFileContent("package.json", { scripts: { "test": "jest" } });
})
it("Should not have a coverage script", async () => {
assert.noJsonFileContent("package.json", { scripts: { "coverage": "jest --coverage" } });
})
}
if (prompts.isFullScreen) {
it("Should be full screen", async () => {
assert.jsonFileContent("src/manifest/manifest.json", {
isFullScreen: true
});
});
} else {
it("Should not be full screen", async () => {
assert.noJsonFileContent("src/manifest/manifest.json", {
isFullScreen: true
});
});
}
if (prompts.showLoadingIndicator) {
it("Should show loading indicator", async () => {
assert.jsonFileContent("src/manifest/manifest.json", {
showLoadingIndicator: true
});
});
} else {
it("Should not show loading indicator", async () => {
assert.jsonFileContent("src/manifest/manifest.json", {
showLoadingIndicator: false
});
});
}
if (prompts.useAzureAppInsights) {
it("Should define an environmental app insights key in .env", async () => {
assert.fileContent(
".env",
"APPINSIGHTS_INSTRUMENTATIONKEY=12341234-1234-1234-1234-123412341234"
);
})
it("Should include applicationinsights package", async () => {
assert.fileContent("package.json", `"applicationinsights": "^1.3.1"`);
})
it("Should reference app insights in html files", async () => {
assert.fileContent(
"src/public/index.html",
`var appInsights = window.appInsights`
);
})
} else {
it("Should define an environmental app insights key in .env", async () => {
assert.fileContent(
".env",
"APPINSIGHTS_INSTRUMENTATIONKEY="
);
})
it("Should not include applicationinsights package", async () => {
assert.noFileContent("package.json", `"applicationinsights": "^1.3.1"`);
})
it("Should not reference app insights in html files", async () => {
assert.noFileContent(
"src/public/index.html",
`var appInsights = window.appInsights`
);
})
}
if (prompts.mpnId) {
it("Should have MPN information", () => {
assert.jsonFileContent("src/manifest/manifest.json", {
developer: {
mpnId: "1234567890"
}
});
})
} else {
it("Should not have MPN information", () => {
assert.noJsonFileContent("src/manifest/manifest.json", {
developer: {
mpnId: "1234567890"
}
});
})
}
}
export function integrationTests(manifestVersion: string, prompts: any, projectPath: string, unitTesting: boolean) {
// Integration tests
if (process.env.TEST_TYPE == TestTypes.INTEGRATION && INTEGRATION_TEST_VERSIONS.includes(manifestVersion)) {
describe("Integration tests", () => {
it("Should run npm install successfully", async () => {
const npmInstallResult = await runNpmCommand("npm install --prefer-offline --no-audit", projectPath);
assert.strictEqual(true, npmInstallResult);
});
it("Should run npm build successfully", async () => {
const npmRunBuildResult = await runNpmCommand("npm run build", projectPath);
assert.strictEqual(true, npmRunBuildResult);
});
it("Should have ./dist files", async () => {
assert.file(DIST_FILES);
});
it("Should validate manifest successfully", async () => {
const npmResult = await runNpmCommand("npm run manifest", projectPath);
assert.strictEqual(true, npmResult);
});
it("Should have ./package files", async () => {
assert.file(PACKAGE_FILES);
});
if (unitTesting) {
it("Should run unit tests successfully", async () => {
const npmResult = await runNpmCommand("npm run test -- -u", projectPath); // pass in -u to Jest to always recreate snapshots in CI
assert.strictEqual(true, npmResult);
});
}
if (prompts.lintingSupport) {
it("Should run lint successfully", async () => {
const npmResult = await runNpmCommand("npm run lint", projectPath);
assert.strictEqual(true, npmResult);
});
}
// clean up
after(async () => {
await runNpmCommand("rm node_modules -rf", projectPath);
await runNpmCommand("rm dist -rf", projectPath);
});
});
}
}
export async function runTests(prefix: string, tests: any[], additionalTests: Function) {
for (const test of tests) {
describe(test.description, () => {
for (const manifestVersion of test.manifestVersions as string[]) {
// run without unit tests
runTest(manifestVersion, test, false);
// run with tests
runTest(manifestVersion, test, true);
// upgrade if possible
if (UPGRADE_PATHS[manifestVersion]) {
for (const upgradeTo of UPGRADE_PATHS[manifestVersion])
runUpgradeTest(manifestVersion, upgradeTo, test, false);
}
}
});
}
async function runTest(manifestVersion: string, test: any, unitTesting: boolean) {
describe(`Schema ${manifestVersion}${unitTesting ? ", with Unit tests" : ""}`, () => {
let projectPath = TEMP_TEST_PATH + `/${prefix}/${manifestVersion}-${lodash.snakeCase(test.description)}`;
let prompts = { manifestVersion, ...basePrompts, ...test.prompts };
if (unitTesting) {
prompts = {
mpnId: "",
...prompts,
"quickScaffolding": false,
"unitTestsEnabled": true
};
projectPath += "-withUnitTests"
}
before(async () => {
await helpers
.run(GENERATOR_PATH)
.inDir(projectPath)
.withArguments(["--no-telemetry"])
.withPrompts(prompts)
.withGenerators(DEPENDENCIES);
});
coreTests(manifestVersion, prompts, projectPath);
integrationTests(manifestVersion, prompts, projectPath, unitTesting);
if (additionalTests) {
additionalTests(prompts);
}
});
}
async function runUpgradeTest(from: string, to: string, test: any, unitTesting: boolean) {
describe(`Schema ${from} upgrading to ${to}${unitTesting ? ", with Unit tests" : ""}`, async () => {
let projectPath = TEMP_TEST_PATH + `/${prefix}/${from}-${to}-${lodash.snakeCase(test.description)}`;
let prompts = { mpnId: "", manifestVersion: from, ...basePrompts, ...test.prompts };
if (unitTesting) {
prompts = {
...prompts, "quickScaffolding": false, "unitTestsEnabled": true
};
projectPath += "-withUnitTests"
}
before(async () => {
await helpers
.run(GENERATOR_PATH)
.inDir(projectPath)
.withArguments(["--no-telemetry"])
.withPrompts(prompts)
.withGenerators(DEPENDENCIES);
prompts = {
manifestVersion: to,
confirmedAdd: true,
updateBuildSystem: true,
updateManifestVersion: true,
parts: ""
};
await helpers
.run(GENERATOR_PATH)
.cd(projectPath)
.withArguments(["--no-telemetry"])
.withPrompts(prompts)
.withGenerators(DEPENDENCIES);
});
coreTests(to, prompts, projectPath);
integrationTests(to, prompts, projectPath, unitTesting);
});
}
} | the_stack |
import test from 'ava';
import * as fse from 'fs-extra';
import { join } from '../src/path';
import { getRandomPath } from './helper';
import { FILTER, Repository, StatusEntry } from '../src/repository';
import { IgnoreManager } from '../src/ignore';
function createFiles(workdir : string, ...names : string[]) {
for (let i = 0; i < names.length; i++) {
const f = join(workdir, names[i]);
fse.createFileSync(f);
}
}
function testIgnore(t, pattern: string[], ignored: string[], unignored: string[]): void {
const ignore = new IgnoreManager();
ignore.loadPatterns(pattern);
const areIgnored: Set<string> = ignore.getIgnoreItems(ignored.concat(unignored));
t.is(areIgnored.size, ignored.length, `Ignored: ${Array.from(areIgnored).sort()}\nvs.\nExpected; ${ignored.sort()}`);
let success = true;
for (const i of ignored) {
const res = areIgnored.has(i);
t.true(res);
if (!res) {
t.log('Expected:');
t.log(ignored.sort());
t.log('Received:');
t.log(Array.from(areIgnored).sort());
success = false;
break;
}
}
if (success && areIgnored.size === ignored.length) {
t.log('---');
t.log(`Ignore Pattern: [${pattern.map((x: string) => `'${x}'`).join(', ')}]`);
t.log(`Ignored Items: [${ignored.map((x: string) => `'${x}'`).join(', ')}]`);
t.log(`Unignored Items: [${unignored.map((x: string) => `'${x}'`).join(', ')}]`);
}
}
test('Ignore Manager plain [foo, bar, bas]', async (t) => {
const pattern = ['foo', 'bar', 'bas'];
const ignored = [
'foo',
'abc/bar', // because of 'bar'
'foo/bar', // because of 'foo' and 'bar'
'foo/test/abc.jpg',
'bar',
'bas',
'a/foo/b',
'a/b/c/foo',
];
const unignored = [
// must not be ignored
'baz',
'baz/abc',
'afoo',
'foob',
'afoob',
'a-foo',
'foo-b',
'a-foo-b',
'a/b/c/foo.jpg',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager plain [foo/bar]', async (t) => {
const pattern = ['foo/bar'];
const ignored = [
'foo/bar',
'foo/bar/baz',
// ignore even if foo is in a subdirectory
'x/foo/bar',
'x/foo/bar/baz',
];
const unignored = [
'foo',
'bar/foo',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager [*.jpg, *.mov]', async (t) => {
const pattern = ['*.jpg', '*.mov'];
const ignored = [
'.jpg', // bc of '*.jpg', also like Git.
'abc.jpg', // bc of '*.jpg'
'foo/bar.jpg', // bc of '*.jpg'
'foo/bar/bas.jpg', // bc of '*.jpg'
'abc.mov', // bc of '*.mov'
'foo/bar.mov', // bc of '*.mov'
'foo/bar.mov/xyz', // bc of '*.mov'
'foo/bar/bas.mov', // bc of '*.mov'
];
const unignored = [
'jpg',
'jpg.',
'foo.jpg.abc',
'foo/jpg.',
'foo/bar/jpg.baz',
'foo/bar.jpg.abc',
'foo/bar/bas.jpg.abc',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager [*.log, !important.log]', async (t) => {
const pattern = ['*.log', '!important.log'];
const ignored = [
'debug.log',
'trace.log',
'foo/test.log',
'foo/log.log',
];
const unignored = [
'important.log',
'logs/important.log',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager [pic.*, bar.*]', async (t) => {
const pattern = ['pic.*', 'bar.*'];
const ignored = [
'pic.', // because of 'pic.*', is ignored, same behaviour in Git
'pic.jpg', // because of 'pic.*'
'pic.jpg.abc', // because of 'pic.*'
'foo/pic.jpg', // because of 'pic.*'
'foo/pic.jpg.abc', // because of 'pic.*'
'foo/baz/pic.jpg', // because of 'pic.*'
'foo/baz/pic.jpg.abc', // because of 'pic.*'
'foo/bar.xyz', // because of 'bar.*'
'foo/bar.baz/xyz', // because of 'bar.*'
];
const unignored = [
'pic',
'foo.pic',
'foo/bar/bas.pic',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager [foo, !foo/bar/bas]', async (t) => {
const pattern = ['foo', '!foo/bar/bas'];
const ignored = [
'foo',
'foo/bar',
'foo/bar/baz',
// ignore even if foo is in a subdirectory
'x/foo',
'x/foo/bar',
'x/foo/bar/baz',
];
const unignored = [
'foo/bar/bas',
// 'x/foo/bar/bas/baz',
'bar',
'bar/bas',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager [foo/*/bar, !foo/*/bas]', async (t) => {
const pattern = ['foo/*/bas', '!foo/*/bas/a'];
const ignored = [
'foo/bar/bas',
'foo/bar/bas/b',
'foo/bar/bas/c',
];
const unignored = [
'foo/bar',
'foo/bar/bas/a',
'foo/bar/bas/b',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Root Test 1 [/foo]', async (t) => {
for (const pattern of [['/foo'], ['/foo/'], ['/foo/**']]) {
const ignored = [
'foo',
'foo/',
'foo/bar',
'foo/bar/',
'foo/bar/bas',
];
const unignored = [
'fooo',
'fooo/',
'fooo/bar',
'x/foo',
'x/foo/',
'x/foo/bar',
'x/foo/bar/bas',
];
testIgnore(t, pattern, ignored, unignored);
}
});
test('Root Test 2 [**/logs]', async (t) => {
const pattern = ['**logs'];
const ignored = [
'logs/monday/foo.bar',
'build/logs/debug.log',
'logs/debug.log',
];
const unignored = [
'logs-files',
'file-log',
'log/logs.txt',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Root Test 2 [**/logs/debug.log]', async (t) => {
const pattern = ['**/logs/debug.log'];
const ignored = [
'logs/debug.log',
'build/logs/debug.log',
];
const unignored = [
'logs/build/debug.log',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Root Test 2 [/foo/bar] [/foo/bar/] [/foo/bar/**]', async (t) => {
for (const pattern of [['/foo/bar'], ['/foo/bar/'], ['/foo/bar/**']]) {
const ignored = [
'foo/bar',
'foo/bar/',
'foo/bar/bas',
];
const unignored = [
'fooo',
'fooo/',
'fooo/bar',
'x/foo',
'x/foo/',
'x/foo/bar',
'x/foo/bar/bas',
];
testIgnore(t, pattern, ignored, unignored);
}
});
test('Ignore Manager [foo/*/baz], [foo/*/baz/], [foo/*/baz/**]', async (t) => {
const patterns = [['foo/*/baz'], ['foo/*/baz/'], ['foo/*/baz/**']];
for (const pattern of patterns) {
const ignored = [
'foo/bar/baz',
'x/foo/bar/baz',
'x/foo/bar/baz/y',
];
const unignored = [
'foo',
'foo/bar',
'foo/baz',
];
// eslint-disable-next-line no-await-in-loop
testIgnore(t, pattern, ignored, unignored);
}
});
test('Ignore Manager [debug[01].log]', async (t) => {
// Square brackets match a single character form the specified set.
const pattern = ['debug[01].log'];
const ignored = [
'debug0.log',
'debug1.log',
'foo/debug0.log',
'foo/debug1.log',
];
const unignored = [
'debug2.log',
'debug01.log',
'foo/debug2.log',
'foo/debug01.log',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager [debug?.log]', async (t) => {
// A question mark matches exactly one character.
const pattern = ['debug?.log'];
const ignored = [
'debug0.log',
'debugg.log',
'foo/debugg.log',
];
const unignored = [
'debug10.log',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Manager [foo/bar[1-4]]', async (t) => {
const pattern = ['foo/bar[1-4].jpg'];
const ignored = [
'foo/bar1.jpg',
'foo/bar2.jpg',
'foo/bar3.jpg',
'foo/bar4.jpg',
];
const unignored = [
'foo/bar0.jpg',
'foo/bar5.jpg',
'foo/bar6.jpg',
'foo/bar7.jpg',
'foo/bar8.jpg',
'foo/bar11.jpg',
'bar1.jpg',
'bar11.jpg',
];
testIgnore(t, pattern, ignored, unignored);
});
test('Ignore Test in getStatus: Ignore single file in root', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(repoPath, 'ignore-me.txt');
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, 'ignore-me.txt');
// In Default mode ignored filed are not included,
return repo.getStatus(FILTER.DEFAULT);
}).then((items: StatusEntry[]) => {
// 0 items because ignore-me.txt is ignored and .snowignore (by default)
t.is(items.length, 0);
}).then(() => {
// Also return the ignored files
return repo.getStatus(FILTER.ALL);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 1);
t.true(!items[0].isdir);
t.true(items[0].isIgnored());
t.is(items[0].path, 'ignore-me.txt');
});
});
test('Ignore Test in getStatus: Ignore multiple files in root', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'ignore-me.txt',
'file1.txt',
'file2.txt',
'file3.txt',
'file4.txt',
);
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, 'ignore-me.txt');
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 5);
t.is(items[0].path, 'file1.txt');
t.is(items[1].path, 'file2.txt');
t.is(items[2].path, 'file3.txt');
t.is(items[3].path, 'file4.txt');
t.is(items[4].path, 'ignore-me.txt');
t.true(items[0].isNew());
t.true(items[1].isNew());
t.true(items[2].isNew());
t.true(items[3].isNew());
t.true(items[4].isIgnored());
});
});
test('Ignore Test in getStatus: Ignore *.txt', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'file1.txt',
'file2.txt',
'file3.txt',
'file4.txt',
'file5.foo',
);
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, '*.txt');
// Don't return any ignored files
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 1);
t.is(items[0].path, 'file5.foo');
t.true(items[0].isNew());
}).then(() => {
// now return all the ignored files
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items[0].path, 'file1.txt');
t.is(items[1].path, 'file2.txt');
t.is(items[2].path, 'file3.txt');
t.is(items[3].path, 'file4.txt');
t.is(items[4].path, 'file5.foo');
t.true(items[0].isIgnored());
t.true(items[1].isIgnored());
t.true(items[2].isIgnored());
t.true(items[3].isIgnored());
t.true(items[4].isNew());
});
});
test('Ignore Test in getStatus: Ignore subdirectory', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'file1.txt',
'file2.txt',
'file3.txt',
'file4.txt',
'file5.txt',
join('subdir', 'file1.txt'),
join('subdir', 'file2.txt'),
join('subdir', 'file3.txt'),
join('subdir', 'file4.txt'),
join('subdir', 'file5.foo'),
);
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, 'subdir');
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 5);
t.is(items[0].path, 'file1.txt');
t.is(items[1].path, 'file2.txt');
t.is(items[2].path, 'file3.txt');
t.is(items[3].path, 'file4.txt');
t.is(items[4].path, 'file5.txt');
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 11);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'file1.txt');
t.is(items[2].path, 'file2.txt');
t.is(items[3].path, 'file3.txt');
t.is(items[4].path, 'file4.txt');
t.is(items[5].path, 'file5.txt');
t.is(items[6].path, 'subdir/file1.txt');
t.is(items[7].path, 'subdir/file2.txt');
t.is(items[8].path, 'subdir/file3.txt');
t.is(items[9].path, 'subdir/file4.txt');
t.is(items[10].path, 'subdir/file5.foo');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isNew());
t.true(items[2].isNew());
t.true(items[3].isNew());
t.true(items[4].isNew());
t.true(items[5].isNew());
t.true(items[6].isIgnored());
t.true(items[7].isIgnored());
t.true(items[8].isIgnored());
t.true(items[9].isIgnored());
t.true(items[10].isIgnored());
});
});
test('Ignore Test in getStatus: Ignore nested subdirectory', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'file1.txt',
'file2.txt',
'file3.txt',
'file4.txt',
'file5.txt',
join('subdir', 'file1.txt'),
join('subdir', 'file2.txt'),
join('subdir', 'file3.txt'),
join('subdir', 'file4.txt'),
join('subdir', 'file5.txt'),
join('subdir', 'subdir', 'file1.txt'),
join('subdir', 'subdir', 'file2.txt'),
join('subdir', 'subdir', 'file3.txt'),
join('subdir', 'subdir', 'file4.txt'),
join('subdir', 'subdir', 'file5.txt'),
);
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, 'subdir/subdir');
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 11);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'file1.txt');
t.is(items[2].path, 'file2.txt');
t.is(items[3].path, 'file3.txt');
t.is(items[4].path, 'file4.txt');
t.is(items[5].path, 'file5.txt');
t.is(items[6].path, 'subdir/file1.txt');
t.is(items[7].path, 'subdir/file2.txt');
t.is(items[8].path, 'subdir/file3.txt');
t.is(items[9].path, 'subdir/file4.txt');
t.is(items[10].path, 'subdir/file5.txt');
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 17);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'subdir/subdir');
t.is(items[2].path, 'file1.txt');
t.is(items[3].path, 'file2.txt');
t.is(items[4].path, 'file3.txt');
t.is(items[5].path, 'file4.txt');
t.is(items[6].path, 'file5.txt');
t.is(items[7].path, 'subdir/file1.txt');
t.is(items[8].path, 'subdir/file2.txt');
t.is(items[9].path, 'subdir/file3.txt');
t.is(items[10].path, 'subdir/file4.txt');
t.is(items[11].path, 'subdir/file5.txt');
t.is(items[12].path, 'subdir/subdir/file1.txt');
t.is(items[13].path, 'subdir/subdir/file2.txt');
t.is(items[14].path, 'subdir/subdir/file3.txt');
t.is(items[15].path, 'subdir/subdir/file4.txt');
t.is(items[16].path, 'subdir/subdir/file5.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isDirectory()); // subdir/subdir
t.true(items[2].isNew());
t.true(items[3].isNew());
t.true(items[4].isNew());
t.true(items[5].isNew());
t.true(items[6].isNew());
t.true(items[7].isNew());
t.true(items[8].isNew());
t.true(items[9].isNew());
t.true(items[10].isNew());
t.true(items[11].isNew());
t.true(items[12].isIgnored());
t.true(items[13].isIgnored());
t.true(items[14].isIgnored());
t.true(items[15].isIgnored());
t.true(items[16].isIgnored());
});
});
test('Ignore Test in getStatus: Ignore comments in ignore', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'file1.txt',
'file2.txt',
'file3.txt',
'file4.txt',
'file5.txt',
join('subdir', 'file1.txt'),
join('subdir', 'file2.txt'),
join('subdir', 'file3.txt'),
join('subdir', 'file4.txt'),
join('subdir', 'file5.txt'),
join('subdir', 'subdir', 'file1.txt'),
join('subdir', 'subdir', 'file2.txt'),
join('subdir', 'subdir', 'file3.txt'),
join('subdir', 'subdir', 'file4.txt'),
join('subdir', 'subdir', 'file5.txt'),
);
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, '// subsubdir\nsubdir/subdir\n/*subdir*/');
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 11);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'file1.txt');
t.is(items[2].path, 'file2.txt');
t.is(items[3].path, 'file3.txt');
t.is(items[4].path, 'file4.txt');
t.is(items[5].path, 'file5.txt');
t.is(items[6].path, 'subdir/file1.txt');
t.is(items[7].path, 'subdir/file2.txt');
t.is(items[8].path, 'subdir/file3.txt');
t.is(items[9].path, 'subdir/file4.txt');
t.is(items[10].path, 'subdir/file5.txt');
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 17);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'subdir/subdir');
t.is(items[2].path, 'file1.txt');
t.is(items[3].path, 'file2.txt');
t.is(items[4].path, 'file3.txt');
t.is(items[5].path, 'file4.txt');
t.is(items[6].path, 'file5.txt');
t.is(items[7].path, 'subdir/file1.txt');
t.is(items[8].path, 'subdir/file2.txt');
t.is(items[9].path, 'subdir/file3.txt');
t.is(items[10].path, 'subdir/file4.txt');
t.is(items[11].path, 'subdir/file5.txt');
t.is(items[12].path, 'subdir/subdir/file1.txt');
t.is(items[13].path, 'subdir/subdir/file2.txt');
t.is(items[14].path, 'subdir/subdir/file3.txt');
t.is(items[15].path, 'subdir/subdir/file4.txt');
t.is(items[16].path, 'subdir/subdir/file5.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isDirectory()); // subdir/subdir
t.true(items[2].isNew());
t.true(items[3].isNew());
t.true(items[4].isNew());
t.true(items[5].isNew());
t.true(items[6].isNew());
t.true(items[7].isNew());
t.true(items[8].isNew());
t.true(items[9].isNew());
t.true(items[10].isNew());
t.true(items[11].isNew());
t.true(items[12].isIgnored());
t.true(items[13].isIgnored());
t.true(items[14].isIgnored());
t.true(items[15].isIgnored());
t.true(items[16].isIgnored());
});
});
test('Ignore Test in getStatus: Ignore inline comments in ignore', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'file1.txt',
'file2.txt',
'file3.txt',
'file4.txt',
'file5.txt',
join('subdir', 'file1.txt'),
join('subdir', 'file2.txt'),
join('subdir', 'file3.txt'),
join('subdir', 'file4.txt'),
join('subdir', 'file5.txt'),
join('subdir', 'subdir', 'file1.txt'),
join('subdir', 'subdir', 'file2.txt'),
join('subdir', 'subdir', 'file3.txt'),
join('subdir', 'subdir', 'file4.txt'),
join('subdir', 'subdir', 'file5.txt'),
);
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, 'sub/*comment*/dir');
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 5);
t.is(items[0].path, 'file1.txt');
t.is(items[1].path, 'file2.txt');
t.is(items[2].path, 'file3.txt');
t.is(items[3].path, 'file4.txt');
t.is(items[4].path, 'file5.txt');
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 17);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'subdir/subdir');
t.is(items[2].path, 'file1.txt');
t.is(items[3].path, 'file2.txt');
t.is(items[4].path, 'file3.txt');
t.is(items[5].path, 'file4.txt');
t.is(items[6].path, 'file5.txt');
t.is(items[7].path, 'subdir/file1.txt');
t.is(items[8].path, 'subdir/file2.txt');
t.is(items[9].path, 'subdir/file3.txt');
t.is(items[10].path, 'subdir/file4.txt');
t.is(items[11].path, 'subdir/file5.txt');
t.is(items[12].path, 'subdir/subdir/file1.txt');
t.is(items[13].path, 'subdir/subdir/file2.txt');
t.is(items[14].path, 'subdir/subdir/file3.txt');
t.is(items[15].path, 'subdir/subdir/file4.txt');
t.is(items[16].path, 'subdir/subdir/file5.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isDirectory()); // subdir/subdir
t.true(items[2].isNew());
t.true(items[3].isNew());
t.true(items[4].isNew());
t.true(items[5].isNew());
t.true(items[6].isNew());
t.true(items[7].isIgnored());
t.true(items[8].isIgnored());
t.true(items[9].isIgnored());
t.true(items[10].isIgnored());
t.true(items[11].isIgnored());
t.true(items[12].isIgnored());
t.true(items[13].isIgnored());
t.true(items[14].isIgnored());
t.true(items[15].isIgnored());
t.true(items[16].isIgnored());
});
});
test('Ignore Test in getStatus: Ignore inverse', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'file1.txt',
'file2.txt',
'file3.txt',
'file4.txt',
'file5.txt',
join('subdir', 'file1.txt'),
join('subdir', 'file2.txt'),
join('subdir', 'file3.txt'),
join('subdir', 'file4.txt'),
join('subdir', 'file5.txt'),
);
// add file to ignore
const ignoreFile = join(repoPath, '.snowignore');
fse.writeFileSync(ignoreFile, 'subdir\n!subdir/file5.txt');
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 6);
t.is(items[0].path, 'file1.txt');
t.is(items[1].path, 'file2.txt');
t.is(items[2].path, 'file3.txt');
t.is(items[3].path, 'file4.txt');
t.is(items[4].path, 'file5.txt');
t.is(items[5].path, 'subdir/file5.txt');
t.true(items[0].isNew());
t.true(items[1].isNew());
t.true(items[2].isNew());
t.true(items[3].isNew());
t.true(items[4].isNew());
t.true(items[5].isNew());
}).then(() => {
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 11);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'file1.txt');
t.is(items[2].path, 'file2.txt');
t.is(items[3].path, 'file3.txt');
t.is(items[4].path, 'file4.txt');
t.is(items[5].path, 'file5.txt');
t.is(items[6].path, 'subdir/file1.txt');
t.is(items[7].path, 'subdir/file2.txt');
t.is(items[8].path, 'subdir/file3.txt');
t.is(items[9].path, 'subdir/file4.txt');
t.is(items[10].path, 'subdir/file5.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isNew());
t.true(items[2].isNew());
t.true(items[3].isNew());
t.true(items[4].isNew());
t.true(items[5].isNew());
t.true(items[6].isIgnored());
t.true(items[7].isIgnored());
t.true(items[8].isIgnored());
t.true(items[9].isIgnored());
t.true(items[10].isNew()); // remember, isNew because subdir/file5.foo is included
});
});
test('Ignore Test in getStatus: nodefaultignore [default false]', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
createFiles(
repoPath,
'subdir/file1.txt', // is NOT ignored by default
'tmp/foo.txt', // is ignored by default
);
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 2);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'subdir/file1.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[0].isNew());
t.true(items[1].isNew());
}).then(() => {
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 4);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'tmp');
t.is(items[2].path, 'subdir/file1.txt');
t.is(items[3].path, 'tmp/foo.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isDirectory()); // tmp
t.true(items[0].isNew());
t.true(items[1].isIgnored());
t.true(items[2].isNew());
t.true(items[3].isIgnored());
});
});
test('Ignore Test in getStatus: nodefaultignore [true]', async (t) => {
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath)
.then(async (repoResult: Repository) => {
// set 'nodefaultignore' to true
const configPath = join(repoResult.commondir(), 'config');
const config: any = fse.readJsonSync(configPath);
config.nodefaultignore = true;
fse.writeJsonSync(configPath, config);
// Since we modified the repo config, we reload
// the repo to have a fresh start for the test
repo = await Repository.open(repoPath);
createFiles(
repoPath,
'subdir/file1.txt', // is NOT ignored by default
'tmp/foo.txt', // is ignored by default
);
return repo.getStatus(FILTER.DEFAULT | FILTER.SORT_CASE_SENSITIVELY);
}).then((items: StatusEntry[]) => {
t.is(items.length, 4);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'tmp');
t.is(items[2].path, 'subdir/file1.txt');
t.is(items[3].path, 'tmp/foo.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isDirectory()); // tmp
t.true(items[0].isNew());
t.true(items[1].isNew());
t.true(items[2].isNew());
t.true(items[3].isNew());
}).then(() => {
return repo.getStatus(FILTER.ALL | FILTER.SORT_CASE_SENSITIVELY);
})
.then((items: StatusEntry[]) => {
t.is(items.length, 4);
t.is(items[0].path, 'subdir');
t.is(items[1].path, 'tmp');
t.is(items[2].path, 'subdir/file1.txt');
t.is(items[3].path, 'tmp/foo.txt');
t.true(items[0].isDirectory()); // subdir
t.true(items[1].isDirectory()); // tmp
t.true(items[0].isNew());
t.true(items[1].isNew());
t.true(items[2].isNew());
t.true(items[3].isNew());
});
}); | the_stack |
import React, { useCallback, useEffect, useMemo, useRef, ReactNode } from 'react';
import noop from 'src/utils/noop';
export type Key = number | string;
export type KeyMap = Map<Key, boolean>;
export type ChildrenMap = Map<Key, ReactNode>;
export interface GroupContext {
selectedKeyMap?: KeyMap;
selectedKeys?: Key[];
toggleKey: (key: Key, selected?: boolean) => void;
toggleKeys: (keys: Key[], selected: boolean) => void;
multiple?: boolean;
subGroupMap?: SubGroupMap;
}
export const defaultContext: GroupContext = {
toggleKey: noop,
toggleKeys: noop
};
export type SelectedStatus = 'NONE' | 'ALL' | 'PART' | 'UNKNOWN';
export type SubGroupMap = Map<Key, { validKeys: Key[]; disabledKeys: Key[] }>;
const emptyKeys: Key[] = [];
const formatKeys = (keys: Key[]): Key[] => {
return Array.isArray(keys) ? keys : emptyKeys;
};
const union = (keys: Key[], anotherKeys: Key[]) => {
if (!keys.length || !anotherKeys.length) return [];
const unionKeys: Key[] = [];
const map: KeyMap = new Map();
keys.forEach(key => map.set(key, true));
anotherKeys.forEach(key => {
if (map.has(key)) unionKeys.push(key);
});
return unionKeys;
};
const getSelectedStatusByUnionCount = (selectedKeys: Key[], validKeys: Key[]) => {
const validSelectedKeys = union(selectedKeys, validKeys);
const vsL = validSelectedKeys.length;
return vsL === 0 ? 'NONE' : vsL >= validKeys.length ? 'ALL' : 'PART';
};
const getSelectedStatus = (selectedKeys: Key[], validKeys: Key[], disabledKeys: Key[]): SelectedStatus => {
const sL = selectedKeys.length;
if (sL === 0) return 'NONE';
const vL = validKeys.length,
dL = disabledKeys.length;
if (sL >= vL + dL) return 'ALL';
if (dL === 0 && sL < vL) return 'PART';
return getSelectedStatusByUnionCount(selectedKeys, validKeys);
};
const getSubSelectedStatus = (selectedKeys: Key[], validKeys: Key[]): SelectedStatus => {
const sL = selectedKeys.length;
if (sL === 0) return 'NONE';
return getSelectedStatusByUnionCount(selectedKeys, validKeys);
};
const getSelectedKeysAfterSelectAll = (
allSelectedStatus: SelectedStatus,
selectedKeys: Key[],
validKeys: Key[],
disabledKeys: Key[]
) => {
const disabledSelectedKeys = union(selectedKeys, disabledKeys);
if (allSelectedStatus === 'ALL') {
return disabledSelectedKeys;
} else {
return validKeys.concat(disabledSelectedKeys);
}
};
/**
* @param selectedKeys all selected keys
* @param onChange callback when selectedKeys change
*/
const useGroup = (
selectedKeys: Key[],
onChange: (keys: Key[], selectedStatus?: SelectedStatus) => void,
multiple = true,
validKeys?: Key[],
disabledKeys?: Key[],
subGroupMap?: SubGroupMap
): [GroupContext, SelectedStatus, () => void] => {
// avoid unknown type of keys
selectedKeys = formatKeys(selectedKeys);
const selectedStatus: SelectedStatus = useMemo(
() =>
multiple && validKeys && disabledKeys
? getSelectedStatus(selectedKeys, validKeys, disabledKeys)
: 'UNKNOWN',
[selectedKeys, validKeys, disabledKeys, multiple]
);
const selectedKeyMap = useMemo(() => {
const m: KeyMap = new Map();
selectedKeys.forEach(v => m.set(v, true));
return m;
}, [selectedKeys]);
// use ref to reduce toggle rebuild
const cacheRef = useRef({
selectedKeys,
selectedKeyMap,
validKeys,
disabledKeys,
multiple,
selectedStatus
});
// update cache
useEffect(() => {
cacheRef.current = { selectedKeys, selectedKeyMap, validKeys, disabledKeys, multiple, selectedStatus };
}, [disabledKeys, selectedKeyMap, multiple, selectedKeys, selectedStatus, validKeys]);
const toggleKeys = useCallback(
(keys: Key[], selected?: boolean) => {
const cache = cacheRef.current;
const { selectedKeyMap, validKeys, disabledKeys, multiple } = cache;
if (multiple) {
const newKeyMap: KeyMap = new Map(selectedKeyMap);
if (selected) {
keys.forEach(key => newKeyMap.set(key, true));
} else {
keys.forEach(key => newKeyMap.delete(key));
}
const newKeys = Array.from(newKeyMap.keys());
const selectedStatus =
validKeys && disabledKeys ? getSelectedStatus(newKeys, validKeys, disabledKeys) : 'UNKNOWN';
onChange(newKeys, selectedStatus);
} else {
if (selected !== false) {
const key = keys.slice(0, 1);
onChange(key);
} else {
onChange([]);
}
}
},
[onChange]
);
const toggleKey = useCallback(
(key: Key, selected?: boolean) => {
const cache = cacheRef.current;
const { selectedKeyMap, multiple } = cache;
toggleKeys([key], multiple && selected === undefined ? !selectedKeyMap.get(key) : selected);
},
[toggleKeys]
);
const groupContext = {
selectedKeys,
selectedKeyMap,
toggleKey,
toggleKeys,
multiple,
subGroupMap
};
const toggleAllItems = useCallback(() => {
const cache = cacheRef.current;
const { selectedKeys, validKeys, disabledKeys, selectedStatus, multiple } = cache;
if (!multiple || !validKeys || !disabledKeys) return;
const newSelectedKeys = getSelectedKeysAfterSelectAll(selectedStatus, selectedKeys, validKeys, disabledKeys);
onChange(newSelectedKeys, selectedStatus === 'ALL' ? 'NONE' : 'ALL');
}, [onChange]);
return [groupContext, selectedStatus, toggleAllItems];
};
/**
* @param key key of this item
* @param groupContext context
* @param selected selected prop from item
*/
const useItem = (key: Key, groupContext: GroupContext, selected = false): [boolean, (selected?: boolean) => void] => {
const { selectedKeyMap, toggleKey } = groupContext;
// save toggle to ref for better performance
const toggleRef = useRef((selected?: boolean) => toggleKey(key, selected));
useEffect(() => {
toggleRef.current = (selected?: boolean) => toggleKey(key, selected);
}, [toggleKey, key]);
if (selectedKeyMap) {
selected = !!selectedKeyMap.get(key);
}
const toggle = useCallback((selected?: boolean) => toggleRef.current(selected), []);
return [selected, toggle];
};
/**
* @param groupContext context from group
* @param validKeys valid wrapped item keys
* @param disabledKeys disabled wrapped item keys
*/
const useSubGroup = (key: Key, groupContext: GroupContext): [SelectedStatus, () => void] => {
const { selectedKeys = [], toggleKeys, multiple, subGroupMap } = groupContext;
const { validKeys = [], disabledKeys = [] } = subGroupMap?.get(key) || {};
const selectedStatus: SelectedStatus = useMemo(
() =>
multiple
? validKeys && disabledKeys && selectedKeys
? getSubSelectedStatus(selectedKeys, validKeys)
: 'UNKNOWN'
: getSubSelectedStatus(selectedKeys, [...validKeys, ...disabledKeys]),
[selectedKeys, validKeys, disabledKeys, multiple]
);
// use ref to reduce toggle rebuild
const cacheRef = useRef({
selectedKeys,
validKeys,
disabledKeys,
toggleKeys,
selectedStatus
});
// update cache
useEffect(() => {
cacheRef.current = {
selectedKeys,
validKeys,
disabledKeys,
toggleKeys,
selectedStatus
};
}, [selectedKeys, validKeys, disabledKeys, toggleKeys, selectedStatus]);
const toggleAllItems = useCallback(() => {
const cache = cacheRef.current;
const { validKeys, toggleKeys, selectedStatus } = cache;
toggleKeys(validKeys, selectedStatus !== 'ALL');
}, []);
return [selectedStatus, toggleAllItems];
};
const groupChildrenAsDataSource = (
children: ReactNode,
globalDisabled = false,
{
itemTag,
subGroupTag,
itemKeyName,
subGroupKeyName
}: {
itemTag: string;
subGroupTag?: string;
itemKeyName: string;
subGroupKeyName?: string;
} = {
itemTag: 'isItem',
subGroupTag: 'isSubGroup',
itemKeyName: 'itemKey',
subGroupKeyName: 'subGroupKey'
}
): [Key[], Key[], ReactNode, SubGroupMap, ChildrenMap] => {
const subGroupMap: SubGroupMap = new Map();
const childrenMap: ChildrenMap = new Map();
const group = (children: ReactNode, disabled: boolean, prefix: string): [Key[], Key[], ReactNode] => {
const validKeys: Key[] = [];
const disabledKeys: Key[] = [];
const l = React.Children.count(children);
const renderChildren: ReactNode = React.Children.map(children, (child, i) => {
const isFirst = i === 0;
const isLast = i === l - 1;
if (React.isValidElement(child)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((child.type as any)?.[itemTag]) {
const props = child.props;
const key = props[itemKeyName] === undefined ? child.key : props[itemKeyName];
const isDisabled = disabled || props.disabled;
if (isDisabled) {
disabledKeys.push(key);
} else {
validKeys.push(key);
}
childrenMap.set(key, props.children);
return React.cloneElement(child, {
[itemKeyName]: key,
disabled: globalDisabled || isDisabled,
isFirst,
isLast
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} else if (subGroupTag && subGroupKeyName && (child.type as any)?.[subGroupTag]) {
const props = child.props;
const key = props[subGroupKeyName] || child.key || `${prefix}-${i}`;
const isDisabled = disabled || props.disabled;
const [subValidKeys, subDisabledKeys, subRenderChildren] = group(
child.props.children,
isDisabled,
key
);
subGroupMap.set(key, { validKeys: subValidKeys, disabledKeys: subDisabledKeys });
validKeys.push(...subValidKeys);
disabledKeys.push(...subDisabledKeys);
return React.cloneElement(
child,
{
disabled: globalDisabled || isDisabled,
[subGroupKeyName]: key,
isFirst,
isLast
},
subRenderChildren
);
}
return child;
}
});
return [validKeys, disabledKeys, renderChildren];
};
return [...group(children, false, 'group-root'), subGroupMap, childrenMap];
};
export { useGroup, useItem, useSubGroup, groupChildrenAsDataSource }; | the_stack |
import { right } from '../../core/shared/either'
import {
emptyComments,
jsxAttributesEntry,
jsxAttributeValue,
jsxElementWithoutUID,
} from '../../core/shared/element-template'
import { importAlias, importDetails } from '../../core/shared/project-file-types'
import { DispatchPriority, EditorAction, EditorDispatch } from '../editor/action-types'
import {
addRegisteredControls,
ControlsToCheck,
clearAllRegisteredControls,
validateControlsToCheck,
} from './canvas-globals'
import {
ComponentDescriptor,
ComponentDescriptorWithName,
PropertyControlsInfo,
} from '../custom-code/code-file'
const cardComponentDescriptor: ComponentDescriptor = {
properties: right({
title: right({
control: 'string-input',
label: 'Title',
}),
}),
variants: [
{
insertMenuLabel: 'Card Default',
elementToInsert: jsxElementWithoutUID(
'Card',
[jsxAttributesEntry('title', jsxAttributeValue('Default', emptyComments), emptyComments)],
[],
),
importsToAdd: {
['/src/card']: importDetails(null, [importAlias('Card')], null),
},
},
],
}
const cardComponentDescriptorWithName: ComponentDescriptorWithName = {
...cardComponentDescriptor,
componentName: 'Card',
}
const cardControlsToCheck: ControlsToCheck = Promise.resolve(
right([cardComponentDescriptorWithName]),
)
const cardPropertyControlsInfo: PropertyControlsInfo = {
['/src/card']: {
Card: cardComponentDescriptor,
},
}
const modifiedCardComponentDescriptor: ComponentDescriptor = {
properties: right({
title: right({
control: 'string-input',
label: 'Title',
}),
border: right({
control: 'string-input',
label: 'Border',
}),
}),
variants: [
{
insertMenuLabel: 'Card Default',
elementToInsert: jsxElementWithoutUID(
'Card',
[
jsxAttributesEntry('title', jsxAttributeValue('Default', emptyComments), emptyComments),
jsxAttributesEntry('border', jsxAttributeValue('shiny', emptyComments), emptyComments),
],
[],
),
importsToAdd: {
['/src/card']: importDetails(null, [importAlias('Card')], null),
},
},
],
}
const modifiedCardComponentDescriptorWithName: ComponentDescriptorWithName = {
...modifiedCardComponentDescriptor,
componentName: 'Card',
}
const modifiedCardControlsToCheck: ControlsToCheck = Promise.resolve(
right([modifiedCardComponentDescriptorWithName]),
)
const selectorComponentDescriptor: ComponentDescriptor = {
properties: right({
value: right({
control: 'popuplist',
label: 'Value',
options: ['True', 'False', 'FileNotFound'],
}),
}),
variants: [
{
insertMenuLabel: 'True False Selector',
elementToInsert: jsxElementWithoutUID(
'Selector',
[
jsxAttributesEntry(
'value',
jsxAttributeValue(`'FileNotFound'`, emptyComments),
emptyComments,
),
],
[],
),
importsToAdd: {
['/src/selector']: importDetails(null, [importAlias('Selector')], null),
},
},
],
}
const selectorComponentDescriptorWithName: ComponentDescriptorWithName = {
...selectorComponentDescriptor,
componentName: 'Selector',
}
const selectorControlsToCheck: ControlsToCheck = Promise.resolve(
right([selectorComponentDescriptorWithName]),
)
const selectorPropertyControlsInfo: PropertyControlsInfo = {
['/src/selector']: {
Selector: selectorComponentDescriptor,
},
}
const otherCardComponentDescriptorWithName: ComponentDescriptorWithName = {
...cardComponentDescriptor,
componentName: 'Other Card',
}
const otherCardControlsToCheck: ControlsToCheck = Promise.resolve(
right([otherCardComponentDescriptorWithName]),
)
describe('validateControlsToCheck', () => {
beforeEach(() => {
clearAllRegisteredControls()
})
afterAll(() => {
clearAllRegisteredControls()
})
it('does nothing if no controls are added', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
await validateControlsToCheck(dispatch, {}, [], [])
expect(actionsDispatched).toMatchInlineSnapshot(`Array []`)
})
it('includes some controls added', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
addRegisteredControls('test.js', '/src/card', cardControlsToCheck)
await validateControlsToCheck(dispatch, {}, ['test.js'], ['test.js'])
expect(actionsDispatched).toMatchInlineSnapshot(`
Array [
Object {
"action": "UPDATE_PROPERTY_CONTROLS_INFO",
"moduleNamesOrPathsToDelete": Array [],
"propertyControlsInfo": Object {
"/src/card": Object {
"Card": Object {
"properties": Object {
"type": "RIGHT",
"value": Object {
"title": Object {
"type": "RIGHT",
"value": Object {
"control": "string-input",
"label": "Title",
},
},
},
},
"variants": Array [
Object {
"elementToInsert": Object {
"children": Array [],
"name": Object {
"baseVariable": "Card",
"propertyPath": Object {
"propertyElements": Array [],
},
},
"props": Array [
Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"key": "title",
"type": "JSX_ATTRIBUTES_ENTRY",
"value": Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"type": "ATTRIBUTE_VALUE",
"value": "Default",
},
},
],
},
"importsToAdd": Object {
"/src/card": Object {
"importedAs": null,
"importedFromWithin": Array [
Object {
"alias": "Card",
"name": "Card",
},
],
"importedWithName": null,
},
},
"insertMenuLabel": "Card Default",
},
],
},
},
},
},
]
`)
})
it('deletes the controls removed from a file', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
// First add the controls
addRegisteredControls('test.js', '/src/card', cardControlsToCheck)
await validateControlsToCheck(dispatch, {}, ['test.js'], ['test.js'])
// Clear the captured actions because we only care about actions dispatched by the next call
actionsDispatched = []
// As the second "evaluation" of 'test.js' didn't register controls, controls registered by the previous
// evaluation will be removed
await validateControlsToCheck(dispatch, cardPropertyControlsInfo, ['test.js'], ['test.js'])
expect(actionsDispatched).toMatchInlineSnapshot(`
Array [
Object {
"action": "UPDATE_PROPERTY_CONTROLS_INFO",
"moduleNamesOrPathsToDelete": Array [
"/src/card",
],
"propertyControlsInfo": Object {},
},
]
`)
})
it('deletes the controls no longer imported', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
// First add the controls
addRegisteredControls('test.js', '/src/card', cardControlsToCheck)
await validateControlsToCheck(dispatch, {}, ['test.js'], ['test.js'])
// Clear the captured actions because we only care about actions dispatched by the next call
actionsDispatched = []
// As 'test.js' is no longer imported, it removes the controls registered by 'test.js' previously
await validateControlsToCheck(dispatch, cardPropertyControlsInfo, [], [])
expect(actionsDispatched).toMatchInlineSnapshot(`
Array [
Object {
"action": "UPDATE_PROPERTY_CONTROLS_INFO",
"moduleNamesOrPathsToDelete": Array [
"/src/card",
],
"propertyControlsInfo": Object {},
},
]
`)
})
it('not evaluating a file will not remove the controls registered by it', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
// First add the controls
addRegisteredControls('test.js', '/src/card', cardControlsToCheck)
await validateControlsToCheck(dispatch, {}, ['test.js'], ['test.js'])
// Clear the captured actions because we only care about actions dispatched by the next call
actionsDispatched = []
// 'test.js' is still imported, but not evaluated this time
await validateControlsToCheck(dispatch, cardPropertyControlsInfo, ['test.js'], [])
expect(actionsDispatched).toMatchInlineSnapshot(`Array []`)
}),
it('importing a file, then removing that import, then adding it again will register the controls even if not evaluated', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
// First add the controls
addRegisteredControls('test.js', '/src/card', cardControlsToCheck)
await validateControlsToCheck(dispatch, {}, ['test.js'], ['test.js'])
// As 'test.js' is no longer imported, it removes the controls registered by 'test.js' previously
await validateControlsToCheck(dispatch, cardPropertyControlsInfo, [], [])
// Clear the captured actions because we only care about actions dispatched by the next call
actionsDispatched = []
// 'test.js' is now imported again, but not evaluated this time as it hasn't changed
await validateControlsToCheck(dispatch, {}, ['test.js'], [])
expect(actionsDispatched).toMatchInlineSnapshot(`
Array [
Object {
"action": "UPDATE_PROPERTY_CONTROLS_INFO",
"moduleNamesOrPathsToDelete": Array [],
"propertyControlsInfo": Object {
"/src/card": Object {
"Card": Object {
"properties": Object {
"type": "RIGHT",
"value": Object {
"title": Object {
"type": "RIGHT",
"value": Object {
"control": "string-input",
"label": "Title",
},
},
},
},
"variants": Array [
Object {
"elementToInsert": Object {
"children": Array [],
"name": Object {
"baseVariable": "Card",
"propertyPath": Object {
"propertyElements": Array [],
},
},
"props": Array [
Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"key": "title",
"type": "JSX_ATTRIBUTES_ENTRY",
"value": Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"type": "ATTRIBUTE_VALUE",
"value": "Default",
},
},
],
},
"importsToAdd": Object {
"/src/card": Object {
"importedAs": null,
"importedFromWithin": Array [
Object {
"alias": "Card",
"name": "Card",
},
],
"importedWithName": null,
},
},
"insertMenuLabel": "Card Default",
},
],
},
},
},
},
]
`)
})
it('includes newly added controls', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
addRegisteredControls('test.js', '/src/card', cardControlsToCheck)
addRegisteredControls('test.js', '/src/selector', selectorControlsToCheck)
await validateControlsToCheck(dispatch, cardPropertyControlsInfo, ['test.js'], ['test.js'])
expect(actionsDispatched).toMatchInlineSnapshot(`
Array [
Object {
"action": "UPDATE_PROPERTY_CONTROLS_INFO",
"moduleNamesOrPathsToDelete": Array [],
"propertyControlsInfo": Object {
"/src/selector": Object {
"Selector": Object {
"properties": Object {
"type": "RIGHT",
"value": Object {
"value": Object {
"type": "RIGHT",
"value": Object {
"control": "popuplist",
"label": "Value",
"options": Array [
"True",
"False",
"FileNotFound",
],
},
},
},
},
"variants": Array [
Object {
"elementToInsert": Object {
"children": Array [],
"name": Object {
"baseVariable": "Selector",
"propertyPath": Object {
"propertyElements": Array [],
},
},
"props": Array [
Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"key": "value",
"type": "JSX_ATTRIBUTES_ENTRY",
"value": Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"type": "ATTRIBUTE_VALUE",
"value": "'FileNotFound'",
},
},
],
},
"importsToAdd": Object {
"/src/selector": Object {
"importedAs": null,
"importedFromWithin": Array [
Object {
"alias": "Selector",
"name": "Selector",
},
],
"importedWithName": null,
},
},
"insertMenuLabel": "True False Selector",
},
],
},
},
},
},
]
`)
})
it('includes modified controls', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
addRegisteredControls('test.js', '/src/card', modifiedCardControlsToCheck)
addRegisteredControls('test.js', '/src/selector', selectorControlsToCheck)
await validateControlsToCheck(
dispatch,
{
...cardPropertyControlsInfo,
...selectorPropertyControlsInfo,
},
['test.js'],
['test.js'],
)
expect(actionsDispatched).toMatchInlineSnapshot(`
Array [
Object {
"action": "UPDATE_PROPERTY_CONTROLS_INFO",
"moduleNamesOrPathsToDelete": Array [],
"propertyControlsInfo": Object {
"/src/card": Object {
"Card": Object {
"properties": Object {
"type": "RIGHT",
"value": Object {
"border": Object {
"type": "RIGHT",
"value": Object {
"control": "string-input",
"label": "Border",
},
},
"title": Object {
"type": "RIGHT",
"value": Object {
"control": "string-input",
"label": "Title",
},
},
},
},
"variants": Array [
Object {
"elementToInsert": Object {
"children": Array [],
"name": Object {
"baseVariable": "Card",
"propertyPath": Object {
"propertyElements": Array [],
},
},
"props": Array [
Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"key": "title",
"type": "JSX_ATTRIBUTES_ENTRY",
"value": Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"type": "ATTRIBUTE_VALUE",
"value": "Default",
},
},
Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"key": "border",
"type": "JSX_ATTRIBUTES_ENTRY",
"value": Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"type": "ATTRIBUTE_VALUE",
"value": "shiny",
},
},
],
},
"importsToAdd": Object {
"/src/card": Object {
"importedAs": null,
"importedFromWithin": Array [
Object {
"alias": "Card",
"name": "Card",
},
],
"importedWithName": null,
},
},
"insertMenuLabel": "Card Default",
},
],
},
},
},
},
]
`)
})
it('merges multiple calls for the same module', async () => {
let actionsDispatched: Array<EditorAction> = []
const dispatch: EditorDispatch = (
actions: ReadonlyArray<EditorAction>,
priority?: DispatchPriority,
) => {
actionsDispatched.push(...actions)
}
addRegisteredControls('test.js', '/src/card', cardControlsToCheck)
addRegisteredControls('test.js', '/src/card', otherCardControlsToCheck)
await validateControlsToCheck(dispatch, {}, ['test.js'], ['test.js'])
expect(actionsDispatched).toMatchInlineSnapshot(`
Array [
Object {
"action": "UPDATE_PROPERTY_CONTROLS_INFO",
"moduleNamesOrPathsToDelete": Array [],
"propertyControlsInfo": Object {
"/src/card": Object {
"Card": Object {
"properties": Object {
"type": "RIGHT",
"value": Object {
"title": Object {
"type": "RIGHT",
"value": Object {
"control": "string-input",
"label": "Title",
},
},
},
},
"variants": Array [
Object {
"elementToInsert": Object {
"children": Array [],
"name": Object {
"baseVariable": "Card",
"propertyPath": Object {
"propertyElements": Array [],
},
},
"props": Array [
Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"key": "title",
"type": "JSX_ATTRIBUTES_ENTRY",
"value": Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"type": "ATTRIBUTE_VALUE",
"value": "Default",
},
},
],
},
"importsToAdd": Object {
"/src/card": Object {
"importedAs": null,
"importedFromWithin": Array [
Object {
"alias": "Card",
"name": "Card",
},
],
"importedWithName": null,
},
},
"insertMenuLabel": "Card Default",
},
],
},
"Other Card": Object {
"properties": Object {
"type": "RIGHT",
"value": Object {
"title": Object {
"type": "RIGHT",
"value": Object {
"control": "string-input",
"label": "Title",
},
},
},
},
"variants": Array [
Object {
"elementToInsert": Object {
"children": Array [],
"name": Object {
"baseVariable": "Card",
"propertyPath": Object {
"propertyElements": Array [],
},
},
"props": Array [
Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"key": "title",
"type": "JSX_ATTRIBUTES_ENTRY",
"value": Object {
"comments": Object {
"leadingComments": Array [],
"trailingComments": Array [],
},
"type": "ATTRIBUTE_VALUE",
"value": "Default",
},
},
],
},
"importsToAdd": Object {
"/src/card": Object {
"importedAs": null,
"importedFromWithin": Array [
Object {
"alias": "Card",
"name": "Card",
},
],
"importedWithName": null,
},
},
"insertMenuLabel": "Card Default",
},
],
},
},
},
},
]
`)
})
}) | the_stack |
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import * as React from 'react';
import { Employee } from 'domain/Employee';
import { getRouterProps } from 'util/BookmarkableTestUtils';
import { Button, FileUpload, TextInput } from '@patternfly/react-core';
import { Map } from 'immutable';
import { mockStore } from 'store/mockStore';
import { Contract } from 'domain/Contract';
import DomainObjectView from 'domain/DomainObjectView';
import { mockRedux, mockTranslate } from 'setupTests';
import { employeeOperations, employeeSelectors } from 'store/employee';
import { DataTable, RowEditButtons, RowViewButtons } from 'ui/components/DataTable';
import { alert } from 'store/alert';
import { doNothing } from 'types';
import TypeaheadSelectInput from 'ui/components/TypeaheadSelectInput';
import { Skill } from 'domain/Skill';
import { skillSelectors } from 'store/skill';
import MultiTypeaheadSelectInput from 'ui/components/MultiTypeaheadSelectInput';
import * as ColorPicker from 'ui/components/ColorPicker';
import { ArrowIcon } from '@patternfly/react-icons';
import { EditableEmployeeRow, EmployeeRow, EmployeesPage } from './EmployeesPage';
const noEmployeesNoContractsStore = mockStore({
skillList: {
isLoading: false,
skillMapById: Map(),
},
contractList: {
isLoading: false,
contractMapById: Map(),
},
employeeList: {
isLoading: false,
employeeMapById: Map(),
},
}).store;
const contract1: Contract = {
id: 0,
tenantId: 0,
name: 'Contract',
maximumMinutesPerDay: null,
maximumMinutesPerWeek: null,
maximumMinutesPerMonth: null,
maximumMinutesPerYear: null,
};
const contract2: Contract = {
id: 1,
tenantId: 0,
name: 'Contract 2',
maximumMinutesPerDay: 5,
maximumMinutesPerWeek: null,
maximumMinutesPerMonth: null,
maximumMinutesPerYear: null,
};
const skill1: Skill = {
id: 0,
tenantId: 0,
name: 'Skill 1',
};
const noEmployeesOneContractsStore = mockStore({
skillList: {
isLoading: false,
skillMapById: Map(),
},
contractList: {
isLoading: false,
contractMapById: Map<number, Contract>()
.set(0, contract1)
.set(1, contract2),
},
employeeList: {
isLoading: false,
employeeMapById: Map(),
},
}).store;
const twoEmployeesOneContractsStore = mockStore({
skillList: {
isLoading: false,
skillMapById: Map<number, Skill>()
.set(0, skill1),
},
contractList: {
isLoading: false,
contractMapById: Map<number, Contract>()
.set(0, contract1),
},
employeeList: {
isLoading: false,
employeeMapById: Map<number, DomainObjectView<Employee>>()
.set(1, {
tenantId: 0,
id: 1,
name: 'Employee 1',
contract: contract1.id as number,
shortId: 'E1',
color: '#FF0000',
skillProficiencySet: [],
}).set(2, {
tenantId: 0,
id: 2,
name: 'Employee 2',
contract: contract1.id as number,
shortId: 'E2',
color: '#00FF00',
skillProficiencySet: [],
}),
},
}).store;
describe('Employees page', () => {
const addEmployee = (employee: Employee) => ['add', employee];
const updateEmployee = (employee: Employee) => ['update', employee];
const removeEmployee = (employee: Employee) => ['remove', employee];
const uploadEmployeeList = (file: File) => ['upload', file];
const showErrorMessage = (key: string, params: any) => ['showErrorMessage', key, params];
beforeEach(() => {
jest.clearAllMocks();
jest.spyOn(employeeOperations, 'addEmployee').mockImplementation(employee => addEmployee(employee) as any);
jest.spyOn(employeeOperations, 'updateEmployee').mockImplementation(employee => updateEmployee(employee) as any);
jest.spyOn(employeeOperations, 'removeEmployee').mockImplementation(employee => removeEmployee(employee) as any);
jest.spyOn(employeeOperations, 'uploadEmployeeList').mockImplementation(file => uploadEmployeeList(file) as any);
jest.spyOn(alert, 'showErrorMessage').mockImplementation((key, params) => showErrorMessage(key, params) as any);
jest.spyOn(twoEmployeesOneContractsStore, 'dispatch').mockImplementation(doNothing);
jest.spyOn(noEmployeesNoContractsStore, 'dispatch').mockImplementation(doNothing);
});
it('should render correctly with no employees', () => {
mockRedux(noEmployeesOneContractsStore);
const employeesPage = shallow(<EmployeesPage {...getRouterProps('/0/employee', {})} />);
expect(toJson(employeesPage)).toMatchSnapshot();
});
it('should render correctly with a few employees', () => {
mockRedux(twoEmployeesOneContractsStore);
const employeesPage = shallow(<EmployeesPage {...getRouterProps('/0/employee', {})} />);
expect(toJson(employeesPage)).toMatchSnapshot();
});
it('should render the viewer correctly', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const viewer = shallow(<EmployeeRow {...employee} />);
expect(toJson(viewer)).toMatchSnapshot();
});
it('clicking on the edit button should show editor', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const viewer = shallow(<EmployeeRow {...employee} />);
viewer.find(RowViewButtons).simulate('edit');
expect(viewer).toMatchSnapshot();
viewer.find(EditableEmployeeRow).simulate('close');
expect(viewer).toMatchSnapshot();
});
it('clicking on the arrow should take you to the Availability Page', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
const routerProps = getRouterProps('/0/employees', {});
const viewer = shallow(<EmployeeRow {...employee} />);
viewer.find(Button).filterWhere(wrapper => wrapper.contains(<ArrowIcon />)).simulate('click');
expect(routerProps.history.push)
.toBeCalledWith(`/${employee.tenantId}/availability?employee=${encodeURIComponent(employee.name)}`);
});
it('should render the editor correctly', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const editor = shallow(<EditableEmployeeRow employee={employee} isNew={false} onClose={jest.fn()} />);
expect(toJson(editor)).toMatchSnapshot();
});
it('no name should be invalid', () => {
const employee = {
...employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2),
name: '',
};
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const editor = shallow(<EditableEmployeeRow employee={employee} isNew={false} onClose={jest.fn()} />);
expect(editor.find(RowEditButtons).prop('isValid')).toBe(false);
});
it('duplicate name should be invalid', () => {
const employee = {
...employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2),
name: 'Employee 1',
id: 3,
};
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const editor = shallow(<EditableEmployeeRow employee={employee} isNew={false} onClose={jest.fn()} />);
expect(editor.find(RowEditButtons).prop('isValid')).toBe(false);
});
it('saving new employee should call add employee', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const editor = shallow(<EditableEmployeeRow employee={employee} isNew onClose={jest.fn()} />);
const name = 'New Employee Name';
const contract = contract2;
const skillProficiencySet = skillSelectors.getSkillList(twoEmployeesOneContractsStore.getState());
const shortId = 'NEN';
const color = '#FF00FF';
editor.find(`[columnName="${mockTranslate('name')}"]`).find(TextInput).simulate('change', name);
editor.find(`[columnName="${mockTranslate('contract')}"]`)
.find(TypeaheadSelectInput).simulate('change', contract);
editor.find(`[columnName="${mockTranslate('skillProficiencies')}"]`)
.find(MultiTypeaheadSelectInput).simulate('change', skillProficiencySet);
editor.find(`[columnName="${mockTranslate('shortId')}"]`)
.find(TextInput).simulate('change', shortId);
editor.find(`[columnName="${mockTranslate('color')}"]`)
.find(ColorPicker.ColorPicker).simulate('changeColor', color);
const newEmployee = {
...employee,
name,
contract,
skillProficiencySet,
shortId,
color,
};
editor.find(RowEditButtons).prop('onSave')();
expect(employeeOperations.addEmployee).toBeCalledWith(newEmployee);
expect(twoEmployeesOneContractsStore.dispatch).toBeCalledWith(addEmployee(newEmployee));
});
it('saving updated employee should call update employee', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const editor = shallow(<EditableEmployeeRow employee={employee} isNew={false} onClose={jest.fn()} />);
editor.find(RowEditButtons).prop('onSave')();
expect(employeeOperations.updateEmployee).toBeCalledWith(employee);
expect(twoEmployeesOneContractsStore.dispatch).toBeCalledWith(updateEmployee(employee));
});
it('clicking on the edit button in the viewer should show the editor', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
const viewer = shallow(<EmployeeRow {...employee} />);
// Clicking the edit button should show the editor
viewer.find(RowViewButtons).prop('onEdit')();
expect(viewer).toMatchSnapshot();
// Clicking the close button should show the viwer
viewer.find(EditableEmployeeRow).prop('onClose')();
expect(viewer).toMatchSnapshot();
});
it('deleting should call delete employee', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
getRouterProps('/0/employees', {});
const viewer = shallow(<EmployeeRow {...employee} />);
viewer.find(RowViewButtons).prop('onDelete')();
expect(employeeOperations.removeEmployee).toBeCalledWith(employee);
expect(twoEmployeesOneContractsStore.dispatch).toBeCalledWith(removeEmployee(employee));
});
it('should upload the file on Excel input', () => {
mockRedux(noEmployeesNoContractsStore);
const employeesPage = shallow(<EmployeesPage {...getRouterProps('/0/employee', {})} />);
const file = new File([], 'hello.xlsx');
employeesPage.find(FileUpload).simulate('change', file);
expect(noEmployeesNoContractsStore.dispatch).toBeCalledWith(uploadEmployeeList(file));
});
it('should show an error on non-excel input', () => {
mockRedux(noEmployeesNoContractsStore);
const employeesPage = shallow(<EmployeesPage {...getRouterProps('/0/employee', {})} />);
employeesPage.find(FileUpload).simulate('change', '');
expect(employeeOperations.uploadEmployeeList).not.toBeCalled();
expect(noEmployeesNoContractsStore.dispatch)
.toBeCalledWith(showErrorMessage('badFileType', { fileTypes: 'Excel (.xlsx)' }));
});
it('DataTable rowWrapper should be EmployeeRow', () => {
const employee = employeeSelectors.getEmployeeById(twoEmployeesOneContractsStore.getState(), 2);
mockRedux(twoEmployeesOneContractsStore);
const employeePage = shallow(<EmployeesPage {...getRouterProps('/0/employee', {})} />);
const rowWrapper = shallow(employeePage.find(DataTable).prop('rowWrapper')(employee));
expect(rowWrapper).toMatchSnapshot();
});
it('DataTable newRowWrapper should be EditableEmployeeRow', () => {
mockRedux(twoEmployeesOneContractsStore);
const employeePage = shallow(<EmployeesPage {...getRouterProps('/0/employee', {})} />);
const removeRow = jest.fn();
jest.spyOn(ColorPicker, 'getRandomColor').mockImplementation(() => '#040404'); // chosen by fair dice roll
const newRowWrapper = shallow((employeePage.find(DataTable).prop('newRowWrapper') as any)(removeRow));
expect(newRowWrapper).toMatchSnapshot();
newRowWrapper.find(RowEditButtons).prop('onClose')();
expect(removeRow).toBeCalled();
});
}); | the_stack |
import { assert } from 'chai';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
const testFilename = path.join(__dirname, '..', 'test.ts');
function getDiagnostics(code: string) {
fs.writeFileSync(testFilename, code);
const options: ts.CompilerOptions = {
module: ts.ModuleKind.CommonJS,
sourceMap: false,
target: ts.ScriptTarget.ES2017,
experimentalDecorators: true,
strict: true,
strictPropertyInitialization: false,
noUnusedLocals: true,
emitDecoratorMetadata: true,
skipLibCheck: true,
outDir: 'build',
noUnusedParameters: true,
inlineSourceMap: true,
inlineSources: true,
noImplicitReturns: true,
noImplicitThis: true,
declaration: true,
};
const program = ts.createProgram([testFilename], options);
const emitResult = program.emit();
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
return allDiagnostics;
}
describe('compile time typed-knex string column parameters', function() {
this.timeout(1000000);
afterEach(() => {
try {
fs.unlinkSync(testFilename);
// tslint:disable-next-line: no-empty
} catch (_e) { }
});
it('should return type with properties from the selectColumn method', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.select('id')
.getFirst();
console.log(result.id);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should error on calling property not used in selectColumn method', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.select('id')
.getFirst();
console.log(result.name);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should return type with properties from the select method', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.select('id')
.getFirst();
console.log(result.id);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should error on calling property not used in select method', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.select('id')
.getFirst();
console.log(result.name);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should allow to call whereIn with type of property', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const query = typedKnex
.query(User)
.whereIn('name', ['user1', 'user2']);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should error on calling whereIn with different type', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const query = typedKnex
.query(User)
.whereIn('name', [1]);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should allow to call whereBetween with type of property', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const query = typedKnex
.query(User)
.whereBetween('numericValue', [1,10]);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should error on calling whereBetween with different type', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const query = typedKnex
.query(User)
.whereBetween('numericValue', ['','']);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should error on calling whereBetween with array of more than 2', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const query = typedKnex
.query(User)
.whereBetween('numericValue', [1,2,3]);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should allow property of parent query in where exists', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User, UserSetting } from './testEntities';
(async () => {
const query = typedKnex
.query(User)
.whereExists(UserSetting, (subQuery) => {
subQuery.whereColumns('user.id', '=', 'someValue');
});
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should not allow unknown property of parent query in where exists', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User, UserSetting } from './testEntities';
(async () => {
const query = typedKnex
.query(User)
.whereExists(UserSetting, (subQuery) => {
subQuery.whereColumns('user.id', '=', 'unknown');
});
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should return type with properties from the min method', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.min('numericValue', 'minNumericValue')
.getFirst();
console.log(result.minNumericValue);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should error on calling property not used in min method', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.min('numericValue', 'minNumericValue')
.getFirst();
console.log(result.id);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should return all Model properties after clearSelect', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.select('id')
.clearSelect()
.getFirst();
console.log(result.id);
console.log(result.name);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
// it('should return correct type from findByColumn', done => {
// file = project.createSourceFile(
// 'test/test4.ts',
// `
// import { knex} from 'knex';
// import { TypedKnex } from '../src/typedKnex';
// import { User } from './testEntities';
// (async () => {
// const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
// const item = await typedKnex
// .query(User)
// .findByColumn('numericValue', 1, 'name');
// if (item !== undefined) {
// console.log(item.name);
// }
// })();
// `
// );
// assert.equal(allDiagnostics.length, 0);
// done();
// });
it('should return correct type from findByPrimaryKey', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'name');
if (item !== undefined) {
console.log(item.name);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey not accept objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'category');
if (item !== undefined) {
console.log(item.category);
}
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey not accept optional objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'optionalCategory');
if (item !== undefined) {
console.log(item.optionalCategory);
}
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey not accept nullable objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'nullableCategory');
if (item !== undefined) {
console.log(item.nullableCategory);
}
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey accept Date objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'birthDate');
if (item !== undefined) {
console.log(item.birthDate);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey accept unknown objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'extraData');
if (item !== undefined) {
console.log(item.extraData);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey accept nullable Date objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'deathDate');
if (item !== undefined) {
console.log(item.deathDate);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey accept nullable string objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'someNullableValue');
if (item !== undefined) {
console.log(item.someNullableValue);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should findByPrimaryKey accept optional string objects in select', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(User)
.findByPrimaryKey("id", 'someOptionalValue');
if (item !== undefined) {
console.log(item.someOptionalValue);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should return correct type from leftOuterJoinTableOnFunction', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User, UserSetting } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(UserSetting)
.leftOuterJoinTableOnFunction('otherUser', User, join => {
join.on('id', '=', 'user2Id');
})
.select('otherUser.name', 'user2.numericValue')
.getFirst();
if (item !== undefined) {
console.log(item.user2.numericValue);
console.log(item.otherUser.name);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should not return type from leftOuterJoinTableOnFunction with not selected from joined table', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User, UserSetting } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(UserSetting)
.leftOuterJoinTableOnFunction('otherUser', User, join => {
join.on('id', '=', 'user2Id');
})
.select('otherUser.name', 'user2.numericValue')
.getFirst();
if (item !== undefined) {
console.log(item.otherUser.id);
}
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should not return type from leftOuterJoinTableOnFunction with not selected from main table', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User, UserSetting } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(UserSetting)
.leftOuterJoinTableOnFunction('otherUser', User, join => {
join.on('id', '=', 'user2Id');
})
.select('otherUser.name', 'user2.numericValue')
.getFirst();
if (item !== undefined) {
console.log(item.id);
}
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should return any when keepFlat() is used', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User, UserSetting } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(UserSetting)
.leftOuterJoinTableOnFunction('otherUser', User, join => {
join.on('id', '=', 'user2Id');
})
.select('otherUser.name', 'user2.numericValue')
.keepFlat()
.getSingle();
console.log(item.doesNotExist);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should accept string column in orderBy', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.orderBy('id')
.getMany();
console.log(result.length);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should accept Date column in orderBy', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.orderBy('birthDate')
.getMany();
console.log(result.length);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should accept nullable Date column in orderBy', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.orderBy('deathDate')
.getMany();
console.log(result.length);
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
it('should not accept foreign key column in orderBy', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const result = await typedKnex
.query(User)
.orderBy(c=>c.category)
.getMany();
console.log(result.length);
})();
`);
assert.notEqual(allDiagnostics.length, 0);
done();
});
it('should return correct type from nested left outer join', (done) => {
const allDiagnostics = getDiagnostics(`
import { knex} from 'knex';
import { TypedKnex } from '../src/typedKnex';
import { User, UserSetting } from './testEntities';
(async () => {
const typedKnex = new TypedKnex(knex({ client: 'postgresql' }));
const item = await typedKnex
.query(UserSetting)
.leftOuterJoin('otherUser', User, 'status', '=', 'otherValue')
.leftOuterJoin('otherUser.otherOtherUser', User, 'status', '=', 'otherUser.status')
.select('otherUser.otherOtherUser.name')
.getFirst();
if (item !== undefined) {
console.log(item.otherUser.otherOtherUser.name);
}
})();
`);
assert.equal(allDiagnostics.length, 0);
done();
});
}); | the_stack |
import {createCategory as createCategoryRedux, moveChannelsToCategory} from 'mattermost-redux/actions/channel_categories';
import {General} from 'mattermost-redux/constants';
import {CategoryTypes} from 'mattermost-redux/constants/channel_categories';
import {getCategory, makeGetChannelIdsForCategory} from 'mattermost-redux/selectors/entities/channel_categories';
import {getCurrentChannelId} from 'mattermost-redux/selectors/entities/channels';
import {DispatchFunc, GetStateFunc} from 'mattermost-redux/types/actions';
import {insertMultipleWithoutDuplicates} from 'mattermost-redux/utils/array_utils';
import {getCategoriesForCurrentTeam, getChannelsInCategoryOrder, getDisplayedChannels} from 'selectors/views/channel_sidebar';
import {DraggingState, GlobalState} from 'types/store';
import {ActionTypes} from 'utils/constants';
export function setUnreadFilterEnabled(enabled: boolean) {
return {
type: ActionTypes.SET_UNREAD_FILTER_ENABLED,
enabled,
};
}
export function setDraggingState(data: DraggingState) {
return {
type: ActionTypes.SIDEBAR_DRAGGING_SET_STATE,
data,
};
}
export function stopDragging() {
return {type: ActionTypes.SIDEBAR_DRAGGING_STOP};
}
export function createCategory(teamId: string, displayName: string, channelIds?: string[]) {
return async (dispatch: DispatchFunc, getState: GetStateFunc) => {
if (channelIds) {
const state = getState() as GlobalState;
const multiSelectedChannelIds = state.views.channelSidebar.multiSelectedChannelIds;
channelIds.forEach((channelId) => {
if (multiSelectedChannelIds.indexOf(channelId) >= 0) {
dispatch(multiSelectChannelAdd(channelId));
}
});
}
const result: any = await dispatch(createCategoryRedux(teamId, displayName, channelIds));
return dispatch({
type: ActionTypes.ADD_NEW_CATEGORY_ID,
data: result.data.id,
});
};
}
// addChannelsInSidebar moves channels to a given category without specifying the order in the sidebar, so the channels
// will always go to the first position in the category
export function addChannelsInSidebar(categoryId: string, channelId: string) {
return moveChannelsInSidebar(categoryId, 0, channelId, false);
}
// moveChannelsInSidebar moves channels to a given category in the sidebar, but it accounts for when the target index
// may have changed due to archived channels not being shown in the sidebar.
export function moveChannelsInSidebar(categoryId: string, targetIndex: number, draggableChannelId: string, setManualSorting = true) {
return (dispatch: DispatchFunc, getState: GetStateFunc) => {
const state = getState() as GlobalState;
const multiSelectedChannelIds = state.views.channelSidebar.multiSelectedChannelIds;
let channelIds = [];
// Multi channel case
if (multiSelectedChannelIds.length && multiSelectedChannelIds.indexOf(draggableChannelId) !== -1) {
const categories = getCategoriesForCurrentTeam(state);
const displayedChannels = getDisplayedChannels(state);
let channelsToMove = [draggableChannelId];
// Filter out channels that can't go in the category specified
const targetCategory = categories.find((category) => category.id === categoryId);
channelsToMove = multiSelectedChannelIds.filter((channelId) => {
const selectedChannel = displayedChannels.find((channel) => channelId === channel.id);
const isDMGM = selectedChannel?.type === General.DM_CHANNEL || selectedChannel?.type === General.GM_CHANNEL;
return targetCategory?.type === CategoryTypes.CUSTOM || targetCategory?.type === CategoryTypes.FAVORITES || (isDMGM && targetCategory?.type === CategoryTypes.DIRECT_MESSAGES) || (!isDMGM && targetCategory?.type !== CategoryTypes.DIRECT_MESSAGES);
});
// Reorder such that the channels move in the order that they appear in the sidebar
const displayedChannelIds = displayedChannels.map((channel) => channel.id);
channelsToMove.sort((a, b) => displayedChannelIds.indexOf(a) - displayedChannelIds.indexOf(b));
// Remove selection from channels that were moved
channelsToMove.forEach((channelId) => dispatch(multiSelectChannelAdd(channelId)));
channelIds = channelsToMove;
} else {
channelIds = [draggableChannelId];
}
const newIndex = adjustTargetIndexForMove(state, categoryId, channelIds, targetIndex, draggableChannelId);
return dispatch(moveChannelsToCategory(categoryId, channelIds, newIndex, setManualSorting));
};
}
export function adjustTargetIndexForMove(state: GlobalState, categoryId: string, channelIds: string[], targetIndex: number, draggableChannelId: string) {
if (targetIndex === 0) {
// The channel is being placed first, so there's nothing above that could affect the index
return 0;
}
const category = getCategory(state, categoryId);
const filteredChannelIds = makeGetChannelIdsForCategory()(state, category);
// When dragging multiple channels, we don't actually remove all of them from the list as react-beautiful-dnd doesn't support that
// Account for channels removed above the insert point, except the one currently being dragged which is already accounted for by react-beautiful-dnd
const removedChannelsAboveInsert = filteredChannelIds.filter((channel, index) => channel !== draggableChannelId && channelIds.indexOf(channel) !== -1 && index <= targetIndex);
const shiftedIndex = targetIndex - removedChannelsAboveInsert.length;
if (category.channel_ids.length === filteredChannelIds.length) {
// There are no archived channels in the category, so the shiftedIndex will be correct
return shiftedIndex;
}
const updatedChannelIds = insertMultipleWithoutDuplicates(filteredChannelIds, channelIds, shiftedIndex);
// After "moving" the channel in the sidebar, find what channel comes above it
const previousChannelId = updatedChannelIds[updatedChannelIds.indexOf(channelIds[0]) - 1];
// We want the channel to still be below that channel, so place the new index below it
let newIndex = category.channel_ids.indexOf(previousChannelId) + 1;
// If the channel is moving downwards, then the target index will need to be reduced by one to account for
// the channel being removed. For example, if we're moving channelA from [channelA, channelB, channelC] to
// [channelB, channelA, channelC], newIndex would currently be 2 (which comes after channelB), but we need
// it to be 1 (which comes after channelB once channelA is removed).
const sourceIndex = category.channel_ids.indexOf(channelIds[0]);
if (sourceIndex !== -1 && sourceIndex < newIndex) {
newIndex -= 1;
}
return Math.max(newIndex - removedChannelsAboveInsert.length, 0);
}
export function clearChannelSelection() {
return (dispatch: DispatchFunc, getState: () => GlobalState) => {
const state = getState();
if (state.views.channelSidebar.multiSelectedChannelIds.length === 0) {
// No selection to clear
return Promise.resolve({data: true});
}
return dispatch({
type: ActionTypes.MULTISELECT_CHANNEL_CLEAR,
});
};
}
export function multiSelectChannelAdd(channelId: string) {
return (dispatch: DispatchFunc, getState: GetStateFunc) => {
const state = getState() as GlobalState;
const multiSelectedChannelIds = state.views.channelSidebar.multiSelectedChannelIds;
// Nothing already selected, so we include the active channel
if (!multiSelectedChannelIds.length) {
const currentChannel = getCurrentChannelId(state);
dispatch({
type: ActionTypes.MULTISELECT_CHANNEL,
data: currentChannel,
});
}
return dispatch({
type: ActionTypes.MULTISELECT_CHANNEL_ADD,
data: channelId,
});
};
}
// Much of this logic was pulled from the react-beautiful-dnd sample multiselect implementation
// Found here: https://github.com/atlassian/react-beautiful-dnd/tree/master/stories/src/multi-drag
export function multiSelectChannelTo(channelId: string) {
return (dispatch: DispatchFunc, getState: GetStateFunc) => {
const state = getState() as GlobalState;
const multiSelectedChannelIds = state.views.channelSidebar.multiSelectedChannelIds;
let lastSelected = state.views.channelSidebar.lastSelectedChannel;
// Nothing already selected, so start with the active channel
if (!multiSelectedChannelIds.length) {
const currentChannel = getCurrentChannelId(state);
dispatch({
type: ActionTypes.MULTISELECT_CHANNEL,
data: currentChannel,
});
lastSelected = currentChannel;
}
const allChannelsIdsInOrder = getChannelsInCategoryOrder(state).map((channel) => channel.id);
const indexOfNew: number = allChannelsIdsInOrder.indexOf(channelId);
const indexOfLast: number = allChannelsIdsInOrder.indexOf(lastSelected);
// multi selecting in the same column
// need to select everything between the last index and the current index inclusive
// nothing to do here
if (indexOfNew === indexOfLast) {
return null;
}
const start: number = Math.min(indexOfLast, indexOfNew);
const end: number = Math.max(indexOfLast, indexOfNew);
const inBetween = allChannelsIdsInOrder.slice(start, end + 1);
// everything inbetween needs to have it's selection toggled.
// with the exception of the start and end values which will always be selected
return dispatch({
type: ActionTypes.MULTISELECT_CHANNEL_TO,
data: inBetween,
});
};
} | the_stack |
// This component can only be used in the context of an exploration.
/**
* NOTE: These are some hacky behavior in the component class. Apologies in
* advance if you were stuck on one of these for a long time.
*
* 1. Whenever changing a property of the data property of this component
* class, please make sure the object is reassigned. Angular's change detection
* uses the `===` operator which would only return false when the object
* changes. You can use the spread operator to achieve the desired result.
* Eg: this.data = {..this.data};
*
* 2. Angular treats SVG+XMl as dangerous by default. To show this image in the
* view, we run our own security (for our own safety) and circumvent the angular
* security. When we circumvent Angular's security checks, it attaches some
* additional information to inform the Angular's view engine to not run
* security checks on the image data. This can only be done the in html file
* using property binding (i.e. [src]). If we use this in the ts file, by doing
* `const img = new Image; img.src = circumventedValue;`, Angular will raise
* errors.
* In addition to this, our custom functions will also fail for this data. To
* overcome this, during the migration of this component, a new property called
* imgData was introduced. This contains the not circumvented value for svgs or
* just the normal image data for other file formats. While updating
* `this.data.metadata.uploadedImageData`, make sure that you also update
* imgData. Failing to do so could lead to unpredictable behavior.
*/
import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { SafeResourceUrl } from '@angular/platform-browser';
import { downgradeComponent } from '@angular/upgrade/static';
import { AppConstants } from 'app.constants';
import { UrlInterpolationService } from 'domain/utilities/url-interpolation.service';
import { ImagePreloaderService } from 'pages/exploration-player-page/services/image-preloader.service';
import { AlertsService } from 'services/alerts.service';
import { AssetsBackendApiService } from 'services/assets-backend-api.service';
import { ContextService } from 'services/context.service';
import { CsrfTokenService } from 'services/csrf-token.service';
import { ImageLocalStorageService } from 'services/image-local-storage.service';
import { ImageUploadHelperService } from 'services/image-upload-helper.service';
import { SvgSanitizerService } from 'services/svg-sanitizer.service';
import 'third-party-imports/gif-frames.import';
const gifshot = require('gifshot');
interface FilepathData {
mode: number;
metadata: {
uploadedFile?: File;
uploadedImageData?: string | SafeResourceUrl;
originalWidth?: number;
originalHeight?: number;
savedImageFilename?: string;
savedImageUrl?: string;
};
crop: boolean;
}
interface Dimensions {
height: number;
width: number;
}
// Reference: https://github.com/yahoo/gifshot#creategifoptions-callback.
interface GifshotCallbackObject {
image: string;
cameraStream: MediaStream;
error: boolean;
errorCode: string;
errorMsg: string;
savedRenderingContexts: ImageData;
}
@Component({
selector: 'image-editor',
templateUrl: './image-editor.component.html',
styleUrls: []
})
export class ImageEditorComponent implements OnInit, OnChanges {
@Input() modalId;
@Input() value;
@Output() valueChanged = new EventEmitter();
@Output() validityChange = new EventEmitter<Record<'empty', boolean>>();
MODE_EMPTY = 1;
MODE_UPLOADED = 2;
MODE_SAVED = 3;
// We only use PNG format since that is what canvas can export to in
// all browsers.
OUTPUT_IMAGE_FORMAT = {
png: 'png',
gif: 'gif'
};
MIME_TYPE_GIF = 'data:image/gif';
CROP_AREA_BORDER_IN_PX = 3;
OUTPUT_IMAGE_MAX_WIDTH_PX = 490;
CROP_BORDER_MARGIN_PX = 10;
CROP_AREA_MIN_WIDTH_PX = 40;
CROP_AREA_MIN_HEIGHT_PX = 40;
// Categorize mouse positions with respect to the crop area.
MOUSE_TOP_LEFT = 1;
MOUSE_TOP = 2;
MOUSE_TOP_RIGHT = 3;
MOUSE_RIGHT = 4;
MOUSE_BOTTOM_RIGHT = 5;
MOUSE_BOTTOM = 6;
MOUSE_BOTTOM_LEFT = 7;
MOUSE_LEFT = 8;
MOUSE_INSIDE = 9;
// Define the cursors for the crop area.
CROP_CURSORS: Record<string, string> = {};
imageContainerStyle = {};
allowedImageFormats = AppConstants.ALLOWED_IMAGE_FORMATS;
HUNDRED_KB_IN_BYTES: number = 100 * 1024;
imageResizeRatio: number;
cropArea: { x1: number; y1: number; x2: number; y2: number };
mousePositionWithinCropArea: null | number;
mouseLastKnownCoordinates: { x: number; y: number };
lastMouseDownEventCoordinates: { x: number; y: number };
userIsDraggingCropArea: boolean = false;
cropAreaResizeDirection: null | number;
userIsResizingCropArea: boolean = false;
invalidTagsAndAttributes: { tags: string[]; attrs: string[] };
processedImageIsTooLarge: boolean;
entityId: string;
entityType: string;
// Check the note before imports and after fileoverview.
private imgData;
// Check the note before imports and after fileoverview.
private _data: FilepathData;
// Check the note before imports and after fileoverview.
get data(): FilepathData {
return this._data;
}
set data(value: FilepathData) {
this._data = value;
this.validate(this._data);
}
cropAreaXWhenLastDown: number;
cropAreaYWhenLastDown: number;
constructor(
private alertsService: AlertsService,
private assetsBackendApiService: AssetsBackendApiService,
private contextService: ContextService,
private csrfTokenService: CsrfTokenService,
private imageLocalStorageService: ImageLocalStorageService,
private imagePreloaderService: ImagePreloaderService,
private imageUploadHelperService: ImageUploadHelperService,
private svgSanitizerService: SvgSanitizerService,
private urlInterpolationService: UrlInterpolationService
) {}
ngOnInit(): void {
this.validityChange.emit({empty: false});
this.CROP_CURSORS[this.MOUSE_TOP_LEFT] = 'nwse-resize';
this.CROP_CURSORS[this.MOUSE_TOP] = 'ns-resize';
this.CROP_CURSORS[this.MOUSE_TOP_RIGHT] = 'nesw-resize';
this.CROP_CURSORS[this.MOUSE_RIGHT] = 'ew-resize';
this.CROP_CURSORS[this.MOUSE_BOTTOM_RIGHT] = 'nwse-resize';
this.CROP_CURSORS[this.MOUSE_BOTTOM] = 'ns-resize';
this.CROP_CURSORS[this.MOUSE_BOTTOM_LEFT] = 'nesw-resize';
this.CROP_CURSORS[this.MOUSE_LEFT] = 'ew-resize';
this.CROP_CURSORS[this.MOUSE_INSIDE] = 'move';
/** Scope variables and functions (visibles to the view) */
// This variable holds information about the image upload flow.
// It's always guaranteed to have the 'mode' and 'metadata'
// properties.
//
// See below a description of each mode.
//
// MODE_EMPTY:
// The user has not uploaded an image yet.
// In this mode, data.metadata will be an empty object:
// {}
//
// MODE_UPLOADED:
// The user has uploaded an image but it is not yet saved.
// All the crop and resizing happens at this stage.
// In this mode, data.metadata will contain the following info:
// {
// uploadedFile: <a File object>,
// uploadedImageData: <binary data corresponding to the image>,
// originalWidth: <original width of the uploaded image>,
// originalHeight: <original height of the uploaded image>
// }
//
// MODE_SAVED:
// The user has saved the final image for use in Oppia.
// At this stage, the user can click on the trash to start over.
// In this mode, data.metadata will contain the following info:
// {
// savedImageFilename: <File name of the resource for the image>
// savedImageUrl: <Trusted resource Url for the image>
// }.
this.data = { mode: this.MODE_EMPTY, metadata: {}, crop: true };
// Resizing properties.
this.imageResizeRatio = 1;
// Cropping properties.
this.cropArea = { x1: 0, y1: 0, x2: 0, y2: 0 };
this.mousePositionWithinCropArea = null;
this.mouseLastKnownCoordinates = { x: 0, y: 0 };
this.lastMouseDownEventCoordinates = { x: 0, y: 0 };
this.userIsDraggingCropArea = false;
this.userIsResizingCropArea = false;
this.cropAreaResizeDirection = null;
this.invalidTagsAndAttributes = {
tags: [],
attrs: []
};
this.processedImageIsTooLarge = false;
this.entityId = this.contextService.getEntityId();
this.entityType = this.contextService.getEntityType();
window.addEventListener('mouseup', (e) => {
e.preventDefault();
this.userIsDraggingCropArea = false;
this.userIsResizingCropArea = false;
}, false);
if (this.value) {
this.resetComponent(this.value);
}
}
/** Internal functions (not visible in the view) */
private resetComponent(newValue) {
// Reset the component each time the value changes
// (e.g. if this is part of an editable list).
if (newValue) {
this.setSavedImageFilename(newValue, false);
const dimensions = (
this.imagePreloaderService.getDimensionsOfImage(newValue));
this.imageContainerStyle = {
height: dimensions.height + 'px',
width: dimensions.width + 'px'
};
this.validityChange.emit({ empty: true });
}
}
/**
* Resamples an image to the specified dimension.
*
* @param imageDataURI A DOMString containing the input image data URI.
* @param width The desired output width.
* @param height The desired output height.
* @return A DOMString containing the output image data URI.
*/
private getResampledImageData(imageDataURI, width, height) {
// Create an Image object with the original data.
const img = new Image();
img.src = imageDataURI;
// Create a Canvas and draw the image on it, resampled.
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL('image/' + this.OUTPUT_IMAGE_FORMAT.png, 1);
}
/**
* Crops an image to the specified rectangular region.
*
* @param imageDataURI A DOMString containing the input image data URI.
* @param x The x coorinate of the top-left corner of the crop region.
* @param y The y coorinate of the top-left corner of the crop region.
* @param width The width of the crop region.
* @param height The height of the crop region.
* @return A DOMString containing the output image data URI.
*/
private getCroppedImageData(imageDataURI, x, y, width, height) {
// Put the original image in a canvas.
const img = new Image();
img.src = imageDataURI;
const canvas = document.createElement('canvas');
canvas.width = x + width;
canvas.height = y + height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// Get image data for a cropped selection.
const data = ctx.getImageData(x, y, width, height);
// Draw on a separate canvas and return the dataURL.
const cropCanvas = document.createElement('canvas');
cropCanvas.width = width;
cropCanvas.height = height;
const cropCtx = cropCanvas.getContext('2d');
cropCtx.putImageData(data, 0, 0);
return cropCanvas.toDataURL('image/' + this.OUTPUT_IMAGE_FORMAT.png, 1);
}
private async getCroppedGIFDataAsync(
x: number, y: number, width: number, height: number,
imageDataURI: string): Promise<string> {
return new Promise((resolve, reject) => {
// Put the original image in a canvas.
let img = new Image();
img.src = imageDataURI;
img.addEventListener('load', () => {
// If the image loads,
// fulfill the promise with the cropped dataURL.
const canvas = document.createElement('canvas');
canvas.width = x + width;
canvas.height = y + height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// Get image data for a cropped selection.
const data = ctx.getImageData(x, y, width, height);
// Draw on a separate canvas and return the dataURL.
const cropCanvas = document.createElement('canvas');
cropCanvas.width = width;
cropCanvas.height = height;
const cropCtx = cropCanvas.getContext('2d');
cropCtx.putImageData(data, 0, 0);
resolve(cropCanvas.toDataURL('image/png'));
}, false);
img.addEventListener('error', () => {
reject(new Error('Image could not be loaded.'));
}, false);
});
}
private getEventCoorindatesRelativeToImageContainer(e) {
// Even though the event listeners are added to the image container,
// the events seem to be reported with 'target' set to the deepest
// element where the event occurred. In other words, if the event
// occurred outside of the crop area, then the (x, y) reported will be
// the one with respect to the image container, but if the event
// occurs inside the crop area, then the (x, y) reported will be the
// one with respect to the crop area itself. So this function does
// normalization on the (x, y) values so that they are always reported
// with respect to the image container (makes calculations easier).
let x = e.offsetX;
let y = e.offsetY;
const containerClass = 'filepath-editor-image-crop-container';
let node = e.target;
while (node !== null && !node.classList.contains(containerClass)) {
x += node.offsetLeft;
y += node.offsetTop;
node = node.offsetParent;
}
return { x: x, y: y };
}
private clamp(value, min, max) {
return Math.min(Math.max(min, value), max);
}
private handleMouseMoveWhileDraggingCropArea(x, y) {
const xDown = this.lastMouseDownEventCoordinates.x;
const yDown = this.lastMouseDownEventCoordinates.y;
const x1WhenDown = this.cropAreaXWhenLastDown;
const y1WhenDown = this.cropAreaYWhenLastDown;
// Calculate new position of the crop area.
let x1 = x1WhenDown + (x - xDown);
let y1 = y1WhenDown + (y - yDown);
// Correct for boundaries.
const dimensions = this.calculateTargetImageDimensions();
const cropWidth = this.cropArea.x2 - this.cropArea.x1;
const cropHeight = this.cropArea.y2 - this.cropArea.y1;
x1 = this.clamp(x1, 0, dimensions.width - cropWidth);
y1 = this.clamp(y1, 0, dimensions.height - cropHeight);
// Update crop area coordinates.
this.cropArea.x1 = x1;
this.cropArea.y1 = y1;
this.cropArea.x2 = x1 + cropWidth;
this.cropArea.y2 = y1 + cropHeight;
}
private handleMouseMoveWhileResizingCropArea(x, y) {
const dimensions = this.calculateTargetImageDimensions();
const direction = this.cropAreaResizeDirection;
const adjustResizeLeft = (x) => {
// Update crop area x1 value, correcting for boundaries.
this.cropArea.x1 = this.clamp(
x, 0, this.cropArea.x2 - this.CROP_AREA_MIN_WIDTH_PX);
};
const adjustResizeRight = (x) => {
// Update crop area x2 value, correcting for boundaries.
this.cropArea.x2 = this.clamp(
x,
this.CROP_AREA_MIN_WIDTH_PX + this.cropArea.x1,
dimensions.width);
};
const adjustResizeTop = (y) => {
// Update crop area y1 value, correcting for boundaries.
this.cropArea.y1 = this.clamp(
y, 0, this.cropArea.y2 - this.CROP_AREA_MIN_HEIGHT_PX);
};
const adjustResizeBottom = (y) => {
// Update crop area y2 value, correcting for boundaries.
this.cropArea.y2 = this.clamp(
y,
this.CROP_AREA_MIN_HEIGHT_PX + this.cropArea.y1,
dimensions.height);
};
switch (direction) {
case this.MOUSE_TOP_LEFT:
adjustResizeTop(y);
adjustResizeLeft(x);
break;
case this.MOUSE_TOP:
adjustResizeTop(y);
break;
case this.MOUSE_TOP_RIGHT:
adjustResizeTop(y);
adjustResizeRight(x);
break;
case this.MOUSE_RIGHT:
adjustResizeRight(x);
break;
case this.MOUSE_BOTTOM_RIGHT:
adjustResizeBottom(y);
adjustResizeRight(x);
break;
case this.MOUSE_BOTTOM:
adjustResizeBottom(y);
break;
case this.MOUSE_BOTTOM_LEFT:
adjustResizeBottom(y);
adjustResizeLeft(x);
break;
case this.MOUSE_LEFT:
adjustResizeLeft(x);
break;
}
}
private updatePositionWithinCropArea(x, y) {
const margin = this.CROP_BORDER_MARGIN_PX;
const cx1 = this.cropArea.x1;
const cy1 = this.cropArea.y1;
const cx2 = this.cropArea.x2;
const cy2 = this.cropArea.y2;
const xOnLeftBorder = x > cx1 - margin && x < cx1 + margin;
const xOnRightBorder = x > cx2 - margin && x < cx2 + margin;
const yOnTopBorder = y > cy1 - margin && y < cy1 + margin;
const yOnBottomBorder = y > cy2 - margin && y < cy2 + margin;
const xInside = x > cx1 && x < cx2;
const yInside = y > cy1 && y < cy2;
// It is important to check the pointer position for corners first,
// since the conditions overlap. In other words, the pointer can be
// at the top border and at the top-right corner at the same time, in
// which case we want to recognize the corner.
if (xOnLeftBorder && yOnTopBorder) {
// Upper left corner.
this.mousePositionWithinCropArea = this.MOUSE_TOP_LEFT;
} else if (xOnRightBorder && yOnTopBorder) {
// Upper right corner.
this.mousePositionWithinCropArea = this.MOUSE_TOP_RIGHT;
} else if (xOnLeftBorder && yOnBottomBorder) {
// Lower left corner.
this.mousePositionWithinCropArea = this.MOUSE_BOTTOM_LEFT;
} else if (xOnRightBorder && yOnBottomBorder) {
// Lower right corner.
this.mousePositionWithinCropArea = this.MOUSE_BOTTOM_RIGHT;
} else if (yOnTopBorder) {
// Top border.
this.mousePositionWithinCropArea = this.MOUSE_TOP;
} else if (xOnLeftBorder) {
// Left border.
this.mousePositionWithinCropArea = this.MOUSE_LEFT;
} else if (xOnRightBorder) {
// Right border.
this.mousePositionWithinCropArea = this.MOUSE_RIGHT;
} else if (yOnBottomBorder) {
// Bottom border.
this.mousePositionWithinCropArea = this.MOUSE_BOTTOM;
} else if (xInside && yInside) {
// Inside the crop area.
this.mousePositionWithinCropArea = this.MOUSE_INSIDE;
} else {
this.mousePositionWithinCropArea = null;
}
}
private getTrustedResourceUrlForImageFileName(imageFileName) {
if (
this.contextService.getImageSaveDestination() ===
AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE &&
this.imageLocalStorageService.isInStorage(imageFileName)) {
const imageUrl = this.imageLocalStorageService.getRawImageData(
imageFileName);
if (imageFileName.endsWith('.svg')) {
return this.svgSanitizerService.getTrustedSvgResourceUrl(imageUrl);
}
return imageUrl;
}
const encodedFilepath = window.encodeURIComponent(imageFileName);
return this.assetsBackendApiService.getImageUrlForPreview(
this.contextService.getEntityType(),
this.contextService.getEntityId(),
encodedFilepath);
}
resetFilePathEditor(): void {
if (
this.data.metadata.savedImageFilename && (
this.contextService.getImageSaveDestination() ===
AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE) &&
this.imageLocalStorageService.isInStorage(
this.data.metadata.savedImageFilename)
) {
this.imageLocalStorageService.deleteImage(
this.data.metadata.savedImageFilename);
}
this.data = {
mode: this.MODE_EMPTY,
metadata: {},
crop: true
};
this.imageResizeRatio = 1;
this.invalidTagsAndAttributes = {
tags: [],
attrs: []
};
this.validityChange.emit({empty: false});
}
validate(data: FilepathData): boolean {
const isValid = data.mode === this.MODE_SAVED &&
data.metadata.savedImageFilename &&
data.metadata.savedImageFilename.length > 0;
return isValid;
}
isUserCropping(): boolean {
const dimensions = this.calculateTargetImageDimensions();
const cropWidth = this.cropArea.x2 - this.cropArea.x1;
const cropHeight = this.cropArea.y2 - this.cropArea.y1;
return cropWidth < dimensions.width || cropHeight < dimensions.height;
}
onMouseMoveOnImageArea(e: MouseEvent): void {
e.preventDefault();
const coords = this.getEventCoorindatesRelativeToImageContainer(e);
if (this.userIsDraggingCropArea) {
this.handleMouseMoveWhileDraggingCropArea(coords.x, coords.y);
} else if (this.userIsResizingCropArea) {
this.handleMouseMoveWhileResizingCropArea(coords.x, coords.y);
} else {
this.updatePositionWithinCropArea(coords.x, coords.y);
}
this.mouseLastKnownCoordinates = { x: coords.x, y: coords.y };
}
onMouseDownOnCropArea(e: MouseEvent): void {
e.preventDefault();
const coords = this.getEventCoorindatesRelativeToImageContainer(e);
const position = this.mousePositionWithinCropArea;
if (position === this.MOUSE_INSIDE) {
this.lastMouseDownEventCoordinates = { x: coords.x, y: coords.y };
this.cropAreaXWhenLastDown = this.cropArea.x1;
this.cropAreaYWhenLastDown = this.cropArea.y1;
this.userIsDraggingCropArea = true;
} else if (position !== null) {
this.lastMouseDownEventCoordinates = { x: coords.x, y: coords.y };
this.userIsResizingCropArea = true;
this.cropAreaResizeDirection = position;
}
}
onMouseUpOnCropArea(e: MouseEvent): void {
e.preventDefault();
this.userIsDraggingCropArea = false;
this.userIsResizingCropArea = false;
}
getMainContainerDynamicStyles(): string {
const width = this.OUTPUT_IMAGE_MAX_WIDTH_PX;
return 'width: ' + width + 'px';
}
getImageContainerDynamicStyles(): string {
if (this.data.mode === this.MODE_EMPTY) {
return 'border: 1px dotted #888';
} else {
return 'border: none';
}
}
getToolbarDynamicStyles(): string {
if (this.isUserCropping()) {
return 'visibility: hidden';
} else {
return 'visibility: visible';
}
}
getCropButtonBarDynamicStyles(): string {
return 'left: ' + this.cropArea.x2 + 'px;' +
'top: ' + this.cropArea.y1 + 'px;';
}
getCropAreaDynamicStyles(): string {
const cropWidth = this.cropArea.x2 - this.cropArea.x1;
const cropHeight = this.cropArea.y2 - this.cropArea.y1;
const position = this.mousePositionWithinCropArea;
// Position, size, cursor and background.
const styles = {
left: this.cropArea.x1 + 'px',
top: this.cropArea.y1 + 'px',
width: cropWidth + 'px',
height: cropHeight + 'px',
cursor: this.CROP_CURSORS[position],
background: null
};
if (!styles.cursor) {
styles.cursor = 'default';
}
// Translucent background layer.
if (this.isUserCropping()) {
const data = 'url(' + (
// Check point 2 in the note before imports and after fileoverview.
this.imgData || this.data.metadata.uploadedImageData) + ')';
styles.background = data + ' no-repeat';
// Add crop area border.
const x = this.cropArea.x1 + this.CROP_AREA_BORDER_IN_PX;
const y = this.cropArea.y1 + this.CROP_AREA_BORDER_IN_PX;
styles['background-position'] = '-' + x + 'px -' + y + 'px';
const dimensions = this.calculateTargetImageDimensions();
styles['background-size'] = dimensions.width + 'px ' +
dimensions.height + 'px';
}
return Object.keys(styles).map(
key => {
return key + ': ' + styles[key];
}).join('; ');
}
getUploadedImageDynamicStyles(): string {
const dimensions = this.calculateTargetImageDimensions();
const w = dimensions.width;
const h = dimensions.height;
return 'width: ' + w + 'px; height: ' + h + 'px;';
}
confirmCropImage(): void {
// Find coordinates of the cropped area within original image scale.
const dimensions = this.calculateTargetImageDimensions();
const r = this.data.metadata.originalWidth / dimensions.width;
const x1 = this.cropArea.x1 * r;
const y1 = this.cropArea.y1 * r;
const width = (this.cropArea.x2 - this.cropArea.x1) * r;
const height = (this.cropArea.y2 - this.cropArea.y1) * r;
// Check point 2 in the note before imports and after fileoverview.
const imageDataURI = this.imgData || (
this.data.metadata.uploadedImageData as string);
const mimeType = imageDataURI.split(';')[0];
let newImageFile;
if (mimeType === this.MIME_TYPE_GIF) {
let successCb = obj => {
this.validateProcessedFilesize(obj.image);
newImageFile = (
this.imageUploadHelperService.convertImageDataToImageFile(
obj.image));
this.updateDimensions(newImageFile, obj.image, width, height);
document.body.style.cursor = 'default';
};
let processFrameCb = this.getCroppedGIFDataAsync.bind(
null, x1, y1, width, height);
this.processGIFImage(
imageDataURI, width, height, processFrameCb, successCb);
} else if (mimeType === 'data:image/svg+xml') {
// Check point 2 in the note before imports and after fileoverview.
const imageData = this.imgData || (
this.data.metadata.uploadedImageData as string);
newImageFile = (
this.imageUploadHelperService.convertImageDataToImageFile(
this.data.metadata.uploadedImageData as string));
this.updateDimensions(newImageFile, imageData, width, height);
} else {
// Generate new image data and file.
const newImageData = this.getCroppedImageData(
// Check point 2 in the note before imports and after fileoverview.
this.imgData || this.data.metadata.uploadedImageData,
x1, y1, width, height);
this.validateProcessedFilesize(newImageData);
newImageFile = (
this.imageUploadHelperService.convertImageDataToImageFile(
newImageData));
this.updateDimensions(newImageFile, newImageData, width, height);
}
}
updateDimensions(
newImageFile: File,
newImageData: string,
width: number,
height: number): void {
// Update image data.
this.data.metadata.uploadedFile = newImageFile;
this.data.metadata.uploadedImageData = newImageData;
this.imgData = newImageData;
this.data.metadata.originalWidth = width;
this.data.metadata.originalHeight = height;
// Check point 1 in the note before imports and after fileoverview.
this.data = {...this.data};
// Re-calculate the dimensions of the base image and reset the
// coordinates of the crop area to the boundaries of the image.
const dimensions = this.calculateTargetImageDimensions();
this.cropArea = {
x1: 0,
y1: 0,
x2: dimensions.width,
y2: dimensions.height
};
}
cancelCropImage(): void {
const dimensions = this.calculateTargetImageDimensions();
this.cropArea.x1 = 0;
this.cropArea.y1 = 0;
this.cropArea.x2 = dimensions.width;
this.cropArea.y2 = dimensions.height;
}
getImageSizeHelp(): string | null {
const imageWidth = this.data.metadata.originalWidth;
if (this.imageResizeRatio === 1 &&
imageWidth > this.OUTPUT_IMAGE_MAX_WIDTH_PX) {
return (
'This image has been automatically downsized to ensure ' +
'that it will fit in the card.'
);
}
return null;
}
isCropAllowed(): boolean {
return this.data.crop;
}
isNoImageUploaded(): boolean {
return this.data.mode === this.MODE_EMPTY;
}
isImageUploaded(): boolean {
return this.data.mode === this.MODE_UPLOADED;
}
isImageSaved(): boolean {
return this.data.mode === this.MODE_SAVED;
}
getCurrentResizePercent(): number {
return Math.round(100 * this.imageResizeRatio);
}
decreaseResizePercent(amount: number): void {
// Do not allow to decrease size below 10%.
this.imageResizeRatio = Math.max(
0.1, this.imageResizeRatio - amount / 100);
this.updateValidationWithLatestDimensions();
}
increaseResizePercent(amount: number): void {
// Do not allow to increase size above 100% (only downsize allowed).
this.imageResizeRatio = Math.min(
1, this.imageResizeRatio + amount / 100);
this.updateValidationWithLatestDimensions();
}
private updateValidationWithLatestDimensions(): void {
const dimensions = this.calculateTargetImageDimensions();
const imageDataURI = (
this.imgData || this.data.metadata.uploadedImageData as string);
const mimeType = (imageDataURI as string).split(';')[0];
if (mimeType === this.MIME_TYPE_GIF) {
let successCb = obj => {
this.validateProcessedFilesize(obj.image);
document.body.style.cursor = 'default';
};
this.processGIFImage(
imageDataURI, dimensions.width, dimensions.height,
null, successCb);
} else {
const resampledImageData = this.getResampledImageData(
imageDataURI, dimensions.width, dimensions.height);
this.validateProcessedFilesize(resampledImageData);
}
}
calculateTargetImageDimensions(): Dimensions {
let width = this.data.metadata.originalWidth;
let height = this.data.metadata.originalHeight;
if (width > this.OUTPUT_IMAGE_MAX_WIDTH_PX) {
const aspectRatio = width / height;
width = this.OUTPUT_IMAGE_MAX_WIDTH_PX;
height = width / aspectRatio;
}
return {
width: Math.round(width * this.imageResizeRatio),
height: Math.round(height * this.imageResizeRatio)
};
}
setUploadedFile(file: File): void {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
// Check point 2 in the note before imports and after fileoverview.
this.imgData = reader.result as string;
let imageData: string | SafeResourceUrl = reader.result as string;
if (file.name.endsWith('.svg')) {
imageData = this.svgSanitizerService.getTrustedSvgResourceUrl(
imageData as string);
}
this.data = {
mode: this.MODE_UPLOADED,
metadata: {
uploadedFile: file,
uploadedImageData: imageData,
originalWidth: img.naturalWidth || 300,
originalHeight: img.naturalHeight || 150
},
crop: file.type !== 'image/svg+xml'
};
const dimensions = this.calculateTargetImageDimensions();
this.cropArea = {
x1: 0,
y1: 0,
x2: dimensions.width,
y2: dimensions.height
};
this.updateValidationWithLatestDimensions();
};
img.src = (reader.result) as string;
};
reader.readAsDataURL(file);
}
setSavedImageFilename(filename: string, updateParent: boolean): void {
this.data = {
mode: this.MODE_SAVED,
metadata: {
savedImageFilename: filename,
// Check point 2 in the note before imports and after fileoverview.
savedImageUrl: this.getTrustedResourceUrlForImageFileName(
filename) as string
},
crop: true
};
if (updateParent) {
this.alertsService.clearWarnings();
this.value = filename;
this.valueChanged.emit(filename);
this.validityChange.emit({ empty: true });
this.resetComponent(filename);
}
}
onFileChanged(file: File): void {
this.setUploadedFile(file);
}
discardUploadedFile(): void {
this.resetFilePathEditor();
this.processedImageIsTooLarge = false;
}
validateProcessedFilesize(resampledImageData: string): void {
const mimeType = resampledImageData.split(';')[0];
const imageSize = atob(
resampledImageData.replace(`${mimeType};base64,`, '')).length;
// The processed image can sometimes be larger than 100 KB. This is
// because the output of HTMLCanvasElement.toDataURL() operation in
// getResampledImageData() is browser specific and can vary in size.
// See https://stackoverflow.com/a/9777037.
this.processedImageIsTooLarge = imageSize > this.HUNDRED_KB_IN_BYTES;
}
saveUploadedFile(): void {
this.alertsService.clearWarnings();
this.processedImageIsTooLarge = false;
if (!this.data.metadata.uploadedFile) {
this.alertsService.addWarning('No image file detected.');
return;
}
const dimensions = this.calculateTargetImageDimensions();
// Check mime type from imageDataURI.
// Check point 2 in the note before imports and after fileoverview.
const imageDataURI = this.imgData || (
this.data.metadata.uploadedImageData as string);
const mimeType = imageDataURI.split(';')[0];
let resampledFile;
if (mimeType === 'data:image/gif') {
let successCb = obj => {
if (!obj.error) {
this.validateProcessedFilesize(obj.image);
if (this.processedImageIsTooLarge) {
document.body.style.cursor = 'default';
return;
}
resampledFile = (
this.imageUploadHelperService.convertImageDataToImageFile(
obj.image));
if (resampledFile === null) {
this.alertsService.addWarning('Could not get resampled file.');
document.body.style.cursor = 'default';
return;
}
this.saveImage(dimensions, resampledFile, 'gif');
document.body.style.cursor = 'default';
}
};
let gifWidth = dimensions.width;
let gifHeight = dimensions.height;
this.processGIFImage(imageDataURI, gifWidth, gifHeight, null, successCb);
} else if (mimeType === 'data:image/svg+xml') {
this.invalidTagsAndAttributes = (
this.svgSanitizerService.getInvalidSvgTagsAndAttrsFromDataUri(
imageDataURI));
const tags = this.invalidTagsAndAttributes.tags;
const attrs = this.invalidTagsAndAttributes.attrs;
if (tags.length === 0 && attrs.length === 0) {
resampledFile = (
this.imageUploadHelperService.convertImageDataToImageFile(
imageDataURI));
this.saveImage(dimensions, resampledFile, 'svg');
this.data.crop = false;
}
} else {
const resampledImageData = this.getResampledImageData(
imageDataURI, dimensions.width, dimensions.height);
this.validateProcessedFilesize(resampledImageData);
if (this.processedImageIsTooLarge) {
return;
}
resampledFile = (
this.imageUploadHelperService.convertImageDataToImageFile(
resampledImageData));
if (resampledFile === null) {
this.alertsService.addWarning('Could not get resampled file.');
return;
}
this.saveImage(dimensions, resampledFile, 'png');
}
}
private processGIFImage(
imageDataURI: string, width: number, height: number,
processFrameCallback: (dataUrl: string) => void,
successCallback: (gifshotCallbackObject: GifshotCallbackObject) => void
): void {
// Looping through individual GIF frames can take a while
// especially if there are a lot. Changing the cursor will let the
// user know that something is happening.
document.body.style.cursor = 'wait';
window.GifFrames({
url: imageDataURI,
frames: 'all',
outputType: 'canvas',
}).then(async function(frameData) {
let frames = [];
for (let i = 0; i < frameData.length; i += 1) {
let sourceCanvas = frameData[i].getImage();
// Some GIFs may be optimised such that frames are stacked and
// only incremental changes are present in individual frames.
// For such GIFs, no additional operation needs to be done to
// handle transparent content. These GIFs have 0 or 1 Disposal
// method value.
// See https://www.w3.org/Graphics/GIF/spec-gif89a.txt
if (frameData[i].frameInfo.disposal > 1) {
// Frames that have transparent content may not render
// properly in the gifshot output. As a workaround, add a
// white background to individual frames before creating a
// GIF.
let ctx = sourceCanvas.getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
ctx.globalCompositeOperation = 'source-over';
}
let dataURL = sourceCanvas.toDataURL('image/png');
let updatedFrame = (
processFrameCallback ?
await processFrameCallback(dataURL) : dataURL);
frames.push(updatedFrame);
}
gifshot.createGIF({
gifWidth: width,
gifHeight: height,
images: frames
}, successCallback);
});
}
saveImageToLocalStorage(
dimensions: Dimensions,
resampledFile: Blob,
imageType: string): void {
const filename = this.imageUploadHelperService.generateImageFilename(
dimensions.height, dimensions.width, imageType);
const reader = new FileReader();
reader.onload = () => {
const imageData = reader.result as string;
// Check point 2 in the note before imports and after fileoverview.
this.imgData = imageData;
this.imageLocalStorageService.saveImage(filename, imageData);
this.setSavedImageFilename(filename, true);
const dimensions = (
this.imagePreloaderService.getDimensionsOfImage(filename));
this.imageContainerStyle = {
height: dimensions.height + 'px',
width: dimensions.width + 'px'
};
};
reader.readAsDataURL(resampledFile);
}
saveImage(
dimensions: Dimensions,
resampledFile: Blob,
imageType: string): void {
if (
this.contextService.getImageSaveDestination() ===
AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE
) {
this.saveImageToLocalStorage(dimensions, resampledFile, imageType);
} else {
this.postImageToServer(dimensions, resampledFile, imageType);
}
}
postImageToServer(
dimensions: Dimensions,
resampledFile: Blob,
imageType: string = 'png'): void {
let form = new FormData();
form.append('image', resampledFile);
form.append('payload', JSON.stringify({
filename: this.imageUploadHelperService.generateImageFilename(
dimensions.height, dimensions.width, imageType)
}));
const imageUploadUrlTemplate = (
'/createhandler/imageupload/<entity_type>/<entity_id>');
this.csrfTokenService.getTokenAsync().then((token) => {
form.append('csrf_token', token);
$.ajax({
url: this.urlInterpolationService.interpolateUrl(
imageUploadUrlTemplate, {
entity_type: this.entityType,
entity_id: this.entityId
}
),
data: form,
processData: false,
contentType: false,
type: 'POST',
dataFilter: data => {
// Remove the XSSI prefix.
const transformedData = data.substring(5);
return JSON.parse(transformedData);
},
dataType: 'text'
}).done((data) => {
// Pre-load image before marking the image as saved.
const img = new Image();
img.onload = () => {
this.setSavedImageFilename(data.filename, true);
let dimensions = (
this.imagePreloaderService.getDimensionsOfImage(data.filename));
this.imageContainerStyle = {
height: dimensions.height + 'px',
width: dimensions.width + 'px'
};
};
// Check point 2 in the note before imports and after fileoverview.
img.src = this.getTrustedResourceUrlForImageFileName(
data.filename) as string;
}).fail((data) => {
// Remove the XSSI prefix.
var transformedData = data.responseText.substring(5);
var parsedResponse = JSON.parse(transformedData);
this.alertsService.addWarning(
parsedResponse.error || 'Error communicating with server.');
});
});
}
ngOnChanges(changes: SimpleChanges): void {
if (
changes.value &&
changes.value.currentValue !== changes.value.previousValue
) {
const newValue = changes.value.currentValue;
this.resetComponent(newValue);
}
}
}
angular.module('oppia').directive(
'imageEditor', downgradeComponent({
component: ImageEditorComponent
}) as angular.IDirectiveFactory); | the_stack |
import { Nes } from "./nes";
//for debugging
//don't rely on this for functionality, always use getFlag()
export class DEBUGVIEWERFL {
C: number = 0;
Z: number = 0;
I: number = 0;
D: number = 0;
B: number = 0;
U: number = 0;
V: number = 0;
N: number = 0;
}
export class Instruction {
op: Function;
add: Function;
id: number = 0;
cyc: number = 0; //number of cycles required to execute instruction
opcode_name?: string = '';
addressmode_name?: string = '';
}
export class CPU {
FLAG_C = 0; // Carry Bit
FLAG_Z = 1; // Zero
FLAG_I = 2; // Disable Interrupts
FLAG_D = 3; // Decimal Mode (unused in this implementation)
FLAG_B = 4; // Break
FLAG_U = 5; // Unused
FLAG_V = 6; // Overflow
FLAG_N = 7; // Negative
nes: Nes;
//Registers
A: number = 0; // Accumulator Register
X: number = 0; // X Register
Y: number = 0; // Y Register
STACK: number = 0; // Stack Pointer ($0100-$01FF) , Starts at 0xFD and counts down
PC: number = 0x8000; // Program Counter (16 bit), hardcoded to start at 0x8000?
STATUS: number = 0; // Status Register
RESET_ADDRESS: number = 0xFFFC;
IRQ_ADDRESS: number = 0xFFFE;
NMI_ADDRESS: number = 0xFFFA;
//variables
address: number = 0; // address to get data based on addressing mode
cycles: number = 0; // number of cpu cycles left for the current operation
all_instructions: Instruction[] = [];
current_instruction: Instruction;
nmi_requested = false;
irq_requested = false;
debug_viewer_fl: DEBUGVIEWERFL = new DEBUGVIEWERFL();
debug_hex_values = {
A: "",
X: "",
Y: "",
P: "",
SP: "",
PC: ""
}
// last_instruction:string = '';
// last_address:number = 0;
// last_read:number = 0;
next_op: string = '';
next_addressmode: string = '';
// BITWISE OPERATORS CHEAT SHEET
// AND &
// OR |
// NOT ~
// XOR ^
// Left shift <<
// Right shift >>
//opcodes data sheets
//https://www.masswerk.at/6502/6502_instruction_set.html#BRK
//http://www.oxyron.de/html/opcodes02.html
//http://archive.6502.org/datasheets/rockwell_r650x_r651x.pdf
//best one with long explanations of opcodes - http://obelisk.me.uk/6502/reference.html#ROL
//build a matrix so it will be easier to eyeball if i made a typo
//based on the function, addressing mode, and number of cycles
constructor(nes: Nes) {
this.nes = nes;
this.init_instructions();
}
loggerCounter = 0;
logger:string = '';
startLogging = false;
allCycles = 0;
clock() {
// this.allcyclecount++;
//EXPENSIVE
//UNCOMMENT THIS IF DOING NESTESTLOGMODE
// if (this.nes.PAUSED || this.nes.nestestlogmode) {
// }
// else
// {
if (this.cycles > 0) {
this.cycles--;
return;
}
// }
//read in the opcode from the program counter
let opcode = this.read(this.PC);
//increment the program counter
this.PC++;
this.current_instruction = this.all_instructions[opcode];
// if (this.current_instruction.opcode_name=="TAX"){
// let debug=1;
// }
//set number of cycles based on instruction
this.cycles = this.current_instruction.cyc;
//run address mode
this.current_instruction.add();
//FOR DEBUGGING
// if (this.loggerCounter<100000 && this.startLogging){
// this.logger += this.loggerCounter + ") PC: " + this.PC.toString(16) +
// " OP: " + opcode.toString(16) + " " +
// this.current_instruction.opcode_name + " " +
// this.current_instruction.addressmode_name + " " +
// " Address: " + this.address.toString(16) + "\r\n";
// if (this.nmi_requested){
// this.logger += "NMI\r\n";
// }
// if (this.irq_requested){
// this.logger += "IRQ\r\n";
// }
// this.loggerCounter++;
// }
// this.allCycles++;
// if (this.PC==43038){
// let debug=1;
// }
// if (this.nes.smb3StartHack && this.PC==43038){
// this.nes.memory.ram[16]=150;
// this.nes.smb3hackCounter++;
// console.log('SMB3 Hack: ' + this.nes.smb3hackCounter);
// }
//execute instruction
this.current_instruction.op();
//TODO - move this to before the op?
//handle NMI
if (this.nmi_requested) {
this.nmi();
this.nmi_requested = false;
}
//handle IRQ
if (this.irq_requested) {
this.irq();
this.irq_requested = false;
}
//decrement the cpu cycles counter;
this.cycles--;
}
//OPCODE MATRIX
init_instructions() {
this.all_instructions = [
//ROW 0
{ id: 0x00, op: this.BRK, add: this.IMP, cyc: 7 },
{ id: 0x01, op: this.ORA, add: this.IZX, cyc: 6 },
{ id: 0x02, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x03, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x04, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x05, op: this.ORA, add: this.ZP0, cyc: 3 },
{ id: 0x06, op: this.ASL, add: this.ZP0, cyc: 5 },
{ id: 0x07, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x08, op: this.PHP, add: this.IMP, cyc: 3 },
{ id: 0x09, op: this.ORA, add: this.IMM, cyc: 2 },
{ id: 0x0a, op: this.ASL, add: this.IMP, cyc: 2 },
{ id: 0x0b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x0c, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x0d, op: this.ORA, add: this.ABS, cyc: 4 },
{ id: 0x0e, op: this.ASL, add: this.ABS, cyc: 6 },
{ id: 0x0f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 1
{ id: 0x10, op: this.BPL, add: this.REL, cyc: 2 },
{ id: 0x11, op: this.ORA, add: this.IZY, cyc: 5 },
{ id: 0x12, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x13, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x14, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x15, op: this.ORA, add: this.ZPX, cyc: 4 },
{ id: 0x16, op: this.ASL, add: this.ZPX, cyc: 6 },
{ id: 0x17, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x18, op: this.CLC, add: this.IMP, cyc: 2 },
{ id: 0x19, op: this.ORA, add: this.ABY, cyc: 4 },
{ id: 0x1a, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x1b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x1c, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x1d, op: this.ORA, add: this.ABX, cyc: 4 },
{ id: 0x1e, op: this.ASL, add: this.ABX, cyc: 7 },
{ id: 0x1f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 2
{ id: 0x20, op: this.JSR, add: this.ABS, cyc: 6 },
{ id: 0x21, op: this.AND, add: this.IZX, cyc: 6 },
{ id: 0x22, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x23, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x24, op: this.BIT, add: this.ZP0, cyc: 3 },
{ id: 0x25, op: this.AND, add: this.ZP0, cyc: 3 },
{ id: 0x26, op: this.ROL, add: this.ZP0, cyc: 5 },
{ id: 0x27, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x28, op: this.PLP, add: this.IMP, cyc: 4 },
{ id: 0x29, op: this.AND, add: this.IMM, cyc: 2 },
{ id: 0x2a, op: this.ROL, add: this.IMP, cyc: 2 },
{ id: 0x2b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x2c, op: this.BIT, add: this.ABS, cyc: 4 },
{ id: 0x2d, op: this.AND, add: this.ABS, cyc: 4 },
{ id: 0x2e, op: this.ROL, add: this.ABS, cyc: 6 },
{ id: 0x2f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 3
{ id: 0x30, op: this.BMI, add: this.REL, cyc: 2 },
{ id: 0x31, op: this.AND, add: this.IZY, cyc: 5 },
{ id: 0x32, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x33, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x34, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x35, op: this.AND, add: this.ZPX, cyc: 4 },
{ id: 0x36, op: this.ROL, add: this.ZPX, cyc: 6 },
{ id: 0x37, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x38, op: this.SEC, add: this.IMP, cyc: 2 },
{ id: 0x39, op: this.AND, add: this.ABY, cyc: 4 },
{ id: 0x3a, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x3b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x3c, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x3d, op: this.AND, add: this.ABX, cyc: 4 },
{ id: 0x3e, op: this.ROL, add: this.ABX, cyc: 7 },
{ id: 0x3f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 4
{ id: 0x40, op: this.RTI, add: this.IMP, cyc: 6 },
{ id: 0x41, op: this.EOR, add: this.IZX, cyc: 6 },
{ id: 0x42, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x43, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x44, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x45, op: this.EOR, add: this.ZP0, cyc: 3 },
{ id: 0x46, op: this.LSR, add: this.ZP0, cyc: 5 },
{ id: 0x47, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x48, op: this.PHA, add: this.IMP, cyc: 3 },
{ id: 0x49, op: this.EOR, add: this.IMM, cyc: 2 },
{ id: 0x4a, op: this.LSR, add: this.IMP, cyc: 2 },
{ id: 0x4b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x4c, op: this.JMP, add: this.ABS, cyc: 3 },
{ id: 0x4d, op: this.EOR, add: this.ABS, cyc: 4 },
{ id: 0x4e, op: this.LSR, add: this.ABS, cyc: 6 },
{ id: 0x4f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 5
{ id: 0x50, op: this.BVC, add: this.REL, cyc: 2 },
{ id: 0x51, op: this.EOR, add: this.IZY, cyc: 5 },
{ id: 0x52, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x53, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x54, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x55, op: this.EOR, add: this.ZPX, cyc: 4 },
{ id: 0x56, op: this.LSR, add: this.ZPX, cyc: 6 },
{ id: 0x57, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x58, op: this.CLI, add: this.IMP, cyc: 2 },
{ id: 0x59, op: this.EOR, add: this.ABY, cyc: 4 },
{ id: 0x5a, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x5b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x5c, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x5d, op: this.EOR, add: this.ABX, cyc: 4 },
{ id: 0x5e, op: this.LSR, add: this.ABX, cyc: 7 },
{ id: 0x5f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 6
{ id: 0x60, op: this.RTS, add: this.IMP, cyc: 6 },
{ id: 0x61, op: this.ADC, add: this.IZX, cyc: 6 },
{ id: 0x62, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x63, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x64, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x65, op: this.ADC, add: this.ZP0, cyc: 3 },
{ id: 0x66, op: this.ROR, add: this.ZP0, cyc: 5 },
{ id: 0x67, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x68, op: this.PLA, add: this.IMP, cyc: 4 },
{ id: 0x69, op: this.ADC, add: this.IMM, cyc: 2 },
{ id: 0x6a, op: this.ROR, add: this.IMP, cyc: 2 },
{ id: 0x6b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x6c, op: this.JMP, add: this.IND, cyc: 5 },
{ id: 0x6d, op: this.ADC, add: this.ABS, cyc: 4 },
{ id: 0x6e, op: this.ROR, add: this.ABS, cyc: 6 },
{ id: 0x6f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 7
{ id: 0x70, op: this.BVS, add: this.REL, cyc: 2 },
{ id: 0x71, op: this.ADC, add: this.IZY, cyc: 5 },
{ id: 0x72, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x73, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x74, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x75, op: this.ADC, add: this.ZPX, cyc: 4 },
{ id: 0x76, op: this.ROR, add: this.ZPX, cyc: 6 },
{ id: 0x77, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x78, op: this.SEI, add: this.IMP, cyc: 2 },
{ id: 0x79, op: this.ADC, add: this.ABY, cyc: 4 },
{ id: 0x7a, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x7b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x7c, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x7d, op: this.ADC, add: this.ABX, cyc: 4 },
{ id: 0x7e, op: this.ROR, add: this.ABX, cyc: 7 },
{ id: 0x7f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 8
{ id: 0x80, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x81, op: this.STA, add: this.IZX, cyc: 6 },
{ id: 0x82, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x83, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x84, op: this.STY, add: this.ZP0, cyc: 3 },
{ id: 0x85, op: this.STA, add: this.ZP0, cyc: 3 },
{ id: 0x86, op: this.STX, add: this.ZP0, cyc: 3 },
{ id: 0x87, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x88, op: this.DEY, add: this.IMP, cyc: 2 },
{ id: 0x89, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x8a, op: this.TXA, add: this.IMP, cyc: 2 },
{ id: 0x8b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x8c, op: this.STY, add: this.ABS, cyc: 4 },
{ id: 0x8d, op: this.STA, add: this.ABS, cyc: 4 },
{ id: 0x8e, op: this.STX, add: this.ABS, cyc: 4 },
{ id: 0x8f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW 9
{ id: 0x90, op: this.BCC, add: this.REL, cyc: 2 },
{ id: 0x91, op: this.STA, add: this.IZY, cyc: 6 },
{ id: 0x92, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x93, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x94, op: this.STY, add: this.ZPX, cyc: 4 },
{ id: 0x95, op: this.STA, add: this.ZPX, cyc: 4 },
{ id: 0x96, op: this.STX, add: this.ZPY, cyc: 4 },
{ id: 0x97, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x98, op: this.TYA, add: this.IMP, cyc: 2 },
{ id: 0x99, op: this.STA, add: this.ABY, cyc: 5 },
{ id: 0x9a, op: this.TXS, add: this.IMP, cyc: 2 },
{ id: 0x9b, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x9c, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x9d, op: this.STA, add: this.ABX, cyc: 5 },
{ id: 0x9e, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0x9f, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW A
{ id: 0xa0, op: this.LDY, add: this.IMM, cyc: 2 },
{ id: 0xa1, op: this.LDA, add: this.IZX, cyc: 6 },
{ id: 0xa2, op: this.LDX, add: this.IMM, cyc: 2 },
{ id: 0xa3, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xa4, op: this.LDY, add: this.ZP0, cyc: 3 },
{ id: 0xa5, op: this.LDA, add: this.ZP0, cyc: 3 },
{ id: 0xa6, op: this.LDX, add: this.ZP0, cyc: 3 },
{ id: 0xa7, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xa8, op: this.TAY, add: this.IMP, cyc: 2 },
{ id: 0xa9, op: this.LDA, add: this.IMM, cyc: 2 },
{ id: 0xaa, op: this.TAX, add: this.IMP, cyc: 2 },
{ id: 0xab, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xac, op: this.LDY, add: this.ABS, cyc: 4 },
{ id: 0xad, op: this.LDA, add: this.ABS, cyc: 4 },
{ id: 0xae, op: this.LDX, add: this.ABS, cyc: 4 },
{ id: 0xaf, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW B
{ id: 0xb0, op: this.BCS, add: this.REL, cyc: 2 },
{ id: 0xb1, op: this.LDA, add: this.IZY, cyc: 5 },
{ id: 0xb2, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xb3, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xb4, op: this.LDY, add: this.ZPX, cyc: 4 },
{ id: 0xb5, op: this.LDA, add: this.ZPX, cyc: 4 },
{ id: 0xb6, op: this.LDX, add: this.ZPY, cyc: 4 },
{ id: 0xb7, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xb8, op: this.CLV, add: this.IMP, cyc: 2 },
{ id: 0xb9, op: this.LDA, add: this.ABY, cyc: 4 },
{ id: 0xba, op: this.TSX, add: this.IMP, cyc: 2 },
{ id: 0xbb, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xbc, op: this.LDY, add: this.ABX, cyc: 4 },
{ id: 0xbd, op: this.LDA, add: this.ABX, cyc: 4 },
{ id: 0xbe, op: this.LDX, add: this.ABY, cyc: 4 },
{ id: 0xbf, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW C
{ id: 0xc0, op: this.CPY, add: this.IMM, cyc: 2 },
{ id: 0xc1, op: this.CMP, add: this.IZX, cyc: 6 },
{ id: 0xc2, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xc3, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xc4, op: this.CPY, add: this.ZP0, cyc: 3 },
{ id: 0xc5, op: this.CMP, add: this.ZP0, cyc: 3 },
{ id: 0xc6, op: this.DEC, add: this.ZP0, cyc: 5 },
{ id: 0xc7, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xc8, op: this.INY, add: this.IMP, cyc: 2 },
{ id: 0xc9, op: this.CMP, add: this.IMM, cyc: 2 },
{ id: 0xca, op: this.DEX, add: this.IMP, cyc: 2 },
{ id: 0xcb, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xcc, op: this.CPY, add: this.ABS, cyc: 4 },
{ id: 0xcd, op: this.CMP, add: this.ABS, cyc: 4 },
{ id: 0xce, op: this.DEC, add: this.ABS, cyc: 6 },
{ id: 0xcf, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW D
{ id: 0xd0, op: this.BNE, add: this.REL, cyc: 2 },
{ id: 0xd1, op: this.CMP, add: this.IZY, cyc: 5 },
{ id: 0xd2, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xd3, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xd4, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xd5, op: this.CMP, add: this.ZPX, cyc: 4 },
{ id: 0xd6, op: this.DEC, add: this.ZPX, cyc: 6 },
{ id: 0xd7, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xd8, op: this.CLD, add: this.IMP, cyc: 2 },
{ id: 0xd9, op: this.CMP, add: this.ABY, cyc: 4 },
{ id: 0xda, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xdb, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xdc, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xdd, op: this.CMP, add: this.ABX, cyc: 4 },
{ id: 0xde, op: this.DEC, add: this.ABX, cyc: 7 },
{ id: 0xdf, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW E
{ id: 0xe0, op: this.CPX, add: this.IMM, cyc: 2 },
{ id: 0xe1, op: this.SBC, add: this.IZX, cyc: 6 },
{ id: 0xe2, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xe3, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xe4, op: this.CPX, add: this.ZP0, cyc: 3 },
{ id: 0xe5, op: this.SBC, add: this.ZP0, cyc: 3 },
{ id: 0xe6, op: this.INC, add: this.ZP0, cyc: 5 },
{ id: 0xe7, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xe8, op: this.INX, add: this.IMP, cyc: 2 },
{ id: 0xe9, op: this.SBC, add: this.IMM, cyc: 2 },
{ id: 0xea, op: this.NOP, add: this.IMP, cyc: 2 },
{ id: 0xeb, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xec, op: this.CPX, add: this.ABS, cyc: 4 },
{ id: 0xed, op: this.SBC, add: this.ABS, cyc: 4 },
{ id: 0xee, op: this.INC, add: this.ABS, cyc: 6 },
{ id: 0xef, op: this.XXX, add: this.XXX, cyc: 0 },
//ROW F
{ id: 0xf0, op: this.BEQ, add: this.REL, cyc: 2 },
{ id: 0xf1, op: this.SBC, add: this.IZY, cyc: 5 },
{ id: 0xf2, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xf3, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xf4, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xf5, op: this.SBC, add: this.ZPX, cyc: 4 },
{ id: 0xf6, op: this.INC, add: this.ZPX, cyc: 6 },
{ id: 0xf7, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xf8, op: this.SED, add: this.IMP, cyc: 2 },
{ id: 0xf9, op: this.SBC, add: this.ABY, cyc: 4 },
{ id: 0xfa, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xfb, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xfc, op: this.XXX, add: this.XXX, cyc: 0 },
{ id: 0xfd, op: this.SBC, add: this.ABX, cyc: 4 },
{ id: 0xfe, op: this.INC, add: this.ABX, cyc: 7 },
{ id: 0xff, op: this.XXX, add: this.XXX, cyc: 0 },
];
//otherwise the function pointers aren't bound to this class
this.all_instructions.forEach(instruction => {
instruction.add = instruction.add.bind(this);
instruction.op = instruction.op.bind(this);
instruction.opcode_name = instruction.op.name.substr(6);
instruction.addressmode_name = instruction.add.name.substr(6);
});
}
getNextInstructionForDebug() {
if (this.nes.DEBUGMODE) //EXPENSIVE
{
let next_opcode = this.read(this.PC);
let next_instruction: Instruction = this.getInstruction(next_opcode);
try {
this.next_op = next_instruction.op.name.substr(6);
this.next_addressmode = next_instruction.add.name.substr(6);
} catch (error) { }
}
}
//cpu reset function sets the cpu to a known state
reset() {
this.A = 0;
this.X = 0;
this.Y = 0;
this.STACK = 0xFD;
this.STATUS = 0x24;
this.updateFlagDebugViewer();
//my own variables
this.address = 0;
//set the program counter to this hard coded address
var lo = this.read(this.RESET_ADDRESS);
var hi = this.read(this.RESET_ADDRESS + 1);
this.PC = (hi << 8) | lo;
this.cycles = 8;
if (this.nes.DEBUGMODE)
this.getNextInstructionForDebug();
}
//interrupt only if disable interrupt flag is clear
//TODO currently not being used but will be used in APU and MMC3 Mapper later on
irq() {
if (this.getFlag(this.FLAG_I) == 0) {
//write the program counter to the stack
//lo and hi byte one at a time
this.writeProgramCounterToStack();
//write the status to stack
this.writeStatusToStack();
//set some flags
this.setFlag(this.FLAG_B, 0);
this.setFlag(this.FLAG_U, 1);
this.setFlag(this.FLAG_I, 1);
//set the program counter to this hard coded address
var lo = this.read(this.IRQ_ADDRESS);
var hi = this.read(this.IRQ_ADDRESS + 1);
this.PC = (hi << 8) | lo;
this.cycles = 7;
}
}
//public interface for requesting nmi
public nmiRequest() {
this.nmi_requested = true;
}
//public interface for requesting irq
public irqRequest() {
this.irq_requested = true;
}
//same as IRQ but non maskable interrupt cannot be stopped
//also the nmi_address is different
private nmi() {
//write the program counter to the stack
//lo and hi byte one at a time
this.writeProgramCounterToStack();
//write the status to stack
this.writeStatusToStack();
//set some flags
this.setFlag(this.FLAG_B, 0);
this.setFlag(this.FLAG_U, 1);
this.setFlag(this.FLAG_I, 1);
//set the program counter to this hard coded address
var lo = this.read(this.NMI_ADDRESS);
var hi = this.read(this.NMI_ADDRESS + 1);
this.PC = (hi << 8) | lo;
this.cycles = 8;
}
// HELPER FUNCTIONS
read(address: number) {
// this.last_read = data;
return this.nes.memory.read(address);
}
write(address: number, value: number) {
this.nes.memory.write(address, value);
}
//mask a number to 8 bits
//since javascript only has floating point numbers
mask255(data: number): number {
return data & 0xFF;
}
compare(data: number, comparer: number) {
if (comparer >= data)
this.setFlag(this.FLAG_C, 1);
else
this.setFlag(this.FLAG_C, 0);
if (comparer == data)
this.setFlag(this.FLAG_Z, 1);
else
this.setFlag(this.FLAG_Z, 0);
if ((comparer - data) & 0x80)
this.setFlag(this.FLAG_N, 1);
else
this.setFlag(this.FLAG_N, 0);
}
//write the program counter to the stack
writeProgramCounterToStack() {
this.write(0x0100 + this.STACK, (this.PC >> 8) & 0x00FF);
this.STACK--;
this.write(0x0100 + this.STACK, this.PC & 0x00FF);
this.STACK--;
}
writeStatusToStack() {
this.write(0x0100 + this.STACK, this.STATUS);
this.STACK--;
}
getFlag(flag: number): number {
if (this.STATUS & (1 << flag))
return 1;
else
return 0;
}
//value should be 0 or 1
setFlag(flag: number, value: number) {
this.STATUS = this.setBit(this.STATUS, flag, value);
// this.updateFlagDebugViewer();
}
//call this manually whenever status gets updated
updateFlagDebugViewer() {
if (this.nes.DEBUGMODE) //EXPENSIVE
{
this.debug_viewer_fl.B = this.getFlag(this.FLAG_B);
this.debug_viewer_fl.C = this.getFlag(this.FLAG_C);
this.debug_viewer_fl.D = this.getFlag(this.FLAG_D);
this.debug_viewer_fl.I = this.getFlag(this.FLAG_I);
this.debug_viewer_fl.N = this.getFlag(this.FLAG_N);
this.debug_viewer_fl.U = this.getFlag(this.FLAG_U);
this.debug_viewer_fl.V = this.getFlag(this.FLAG_V);
this.debug_viewer_fl.Z = this.getFlag(this.FLAG_Z);
}
}
updateHexDebugValues() {
if (this.nes.DEBUGMODE) //EXPENSIVE
{
this.debug_hex_values.A = this.A.toString(16);
this.debug_hex_values.X = this.X.toString(16);
this.debug_hex_values.Y = this.Y.toString(16);
this.debug_hex_values.P = this.STATUS.toString(16);
this.debug_hex_values.SP = this.STACK.toString(16);
this.debug_hex_values.PC = this.PC.toString(16);
}
}
getBit(byte: number, bit: number): number {
return (byte >> bit) & 1;
}
setBit(byte: number, bit: number, value: number): number {
if (value > 0)
return byte | (1 << bit);
else
return byte & ~(1 << bit);
}
toggleBit(byte: number, bit: number): number {
return byte ^ (1 << bit);
}
getInstruction(opcode: number): Instruction {
//EXPENSIVE
// let instruction = this.all_instructions.find((ins) => {
// return ins.id == opcode;
// })
// if (instruction)
// return instruction;
// else
// return this.not_implemented;
return this.all_instructions[opcode];
}
getData(): number {
return this.read(this.address);
}
setFlagsZandN(value: number) {
let maskedValue = this.mask255(value);
//set the zero flag if the value is zero
if (maskedValue == 0)
this.setFlag(this.FLAG_Z, 1);
else
this.setFlag(this.FLAG_Z, 0);
//set the negative flag if the most significant bit is 1
this.setFlag(this.FLAG_N, this.getBit(maskedValue, 7));
// if (value & 0x80)
// this.setFlag(FLAG.N, 1);
// else
// this.setFlag(FLAG.N, 0);
}
branch(do_branch: boolean) {
if (do_branch) {
this.cycles++;
//move forward or backward for branching
//based on what was determined in the
//relative addressing mode
this.address = this.PC + this.address;
//add a cycle if we cross a page boundary
if ((this.address & 0xFF00) != (this.PC & 0xFF00))
this.cycles++;
this.PC = this.address;
}
}
// ADDRESSING MODES
//TODO - my timing will be off unless i implement
//all of the potential cycle adds based on page boundaries
//and other scenarios. will probably affect my audio later
//implied
IMP() {
//do nothing
}
//immediate
IMM() {
//get the data from the next literal byte in the program
this.address = this.PC;
this.PC++;
}
//zero page addressing
ZP0() {
//get the byte from the zero page
this.address = this.read(this.PC) & 0x00FF;
this.PC++;
}
//zero page with X register offset
ZPX() {
this.address = (this.read(this.PC) + this.X) & 0x00FF;
// this.address += this.X;
// this.address = this.address & 0x00FF;
this.PC++;
}
ZPY() {
this.address = (this.read(this.PC) + this.Y) & 0x00FF;
// this.address += this.Y;
// this.address = this.address & 0x00FF;
this.PC++;
}
//absolute addressing
//read the low and high byte of the 2 byte address
ABS() {
// var lo = this.read(this.PC);
// var hi = this.read(this.PC + 1);
// this.address = (this.nes.memory.read(this.PC + 1) << 8) | this.nes.memory.read(this.PC);
this.address = (this.read(this.PC + 1) << 8) | this.read(this.PC);
this.PC += 2;
}
//absolute with x register offset
ABX() {
var lo = this.read(this.PC);
var hi = this.read(this.PC + 1);
this.PC += 2;
this.address = (hi << 8) | lo;
this.address += this.X;
//just in case its larger than 16 bit max
this.address = this.address & 0xffff;
//if we have crossed the page boundary
//then add 1 cycle
if (lo + this.X > 255)
this.cycles += 1;
}
//absolute with y register offset
ABY() {
var lo = this.read(this.PC);
var hi = this.read(this.PC + 1);
this.PC += 2;
this.address = (hi << 8) | lo;
this.address += this.Y;
//just in case its larger than 16 bit max
this.address = this.address & 0xffff;
//if we have crossed the page boundary
//then add 1 cycle
if (lo + this.Y > 255)
this.cycles += 1;
}
//indirect addressing
//6502 version of pointers
IND() {
var lo = this.read(this.PC);
var hi = this.read(this.PC + 1);
this.PC += 2;
var pointer = (hi << 8) | lo;
//simulate page boundary hardware bug (only if low byte is 255)
//low byte at pointer and high byte at pointer+1
if (lo == 255)
this.address = (this.read(pointer & 0xFF00) << 8) | this.read(pointer);
else
this.address = (this.read(pointer + 1) << 8) | this.read(pointer);
}
//zero page indirect addressing with X offset
IZX() {
var num = this.read(this.PC);
this.PC++;
var lo_address = (num + this.X) & 0x00ff;
var hi_address = (num + this.X + 1) & 0x00ff;
var lo = this.read(lo_address);
var hi = this.read(hi_address);
this.address = (hi << 8) | lo;
}
//zero page indirect addressing with Y
//behaves differently than IZX in that it adds
//Y to the final address rather than using
//as an offset when reading the address
IZY() {
var num = this.read(this.PC);
this.PC++;
var lo_address = num & 0x00ff;
var hi_address = (num + 1) & 0x00ff;
var lo = this.read(lo_address);
var hi = this.read(hi_address);
//add a cycle if it crosses a page boundary
if (lo + this.Y > 255)
this.cycles += 1;
this.address = (((hi << 8) | lo) + this.Y) & 0xffff;
}
//relative addressing
//can only jump back -128 or forward 127
//used in branching
REL() {
this.address = this.read(this.PC);
//weirdly this is a signed number so if it's 128 or
//above it's actually considered a negative number
//so we subtract 256 from it to get the correct value
//example: 251 is actually -5 for branching purposes
if (this.address >= 128)
this.address -= 256;
this.PC++;
}
// OPCODES
//add M to A with carry
ADC() {
var data = this.getData();
var temp = this.A + data + this.getFlag(this.FLAG_C);
this.setFlagsZandN(temp);
//set the carry bit
this.setFlag(this.FLAG_C, temp > 255 ? 1 : 0);
//set the overflow flag based on a formula
//just trust that it works
if (((this.A ^ data) & 0x80) == 0 && ((this.A ^ temp) & 0x80) != 0)
this.setFlag(this.FLAG_V, 1);
else
this.setFlag(this.FLAG_V, 0);
//load the value back into the accumulator
//make sure it's 8-bit
this.A = this.mask255(temp);
}
//do an AND operation between accumulator and the data
AND() {
this.A = this.A & this.getData();
this.setFlagsZandN(this.A);
}
//arithmetic shift left
ASL() {
var data: number;
//if addressing mode is implied then
//we are acting upon the accumulator
//other write it back to the same address
if (this.current_instruction.addressmode_name == "IMP") {
data = this.A << 1;
this.A = this.mask255(data);
}
else {
data = this.getData() << 1;
this.write(this.address, this.mask255(data));
}
if (data > 255)
this.setFlag(this.FLAG_C, 1);
else
this.setFlag(this.FLAG_C, 0);
this.setFlagsZandN(data);
}
//branch on carry clear
BCC() {
this.branch(this.getFlag(this.FLAG_C) == 0);
}
//branch if carry bit is set
BCS() {
this.branch(this.getFlag(this.FLAG_C) == 1);
}
//branch if zero
BEQ() {
this.branch(this.getFlag(this.FLAG_Z) == 1);
}
//test bits in M with A
//set flag z with accumulator & data
BIT() {
var data = this.getData();
var temp = this.A & data;
if (this.mask255(temp) == 0)
this.setFlag(this.FLAG_Z, 1);
else
this.setFlag(this.FLAG_Z, 0);
this.setFlag(this.FLAG_N, data & (1 << 7));
this.setFlag(this.FLAG_V, data & (1 << 6));
}
//branch if result is negative
BMI() {
this.branch(this.getFlag(this.FLAG_N) == 1);
}
//branch on result not zero
BNE() {
this.branch(this.getFlag(this.FLAG_Z) == 0);
}
//branch if result is positive
BPL() {
this.branch(this.getFlag(this.FLAG_N) == 0);
}
//break operation - perform an interrupt from the program
BRK() {
this.PC++;
this.writeProgramCounterToStack();
this.writeStatusToStack();
this.setFlag(this.FLAG_B, 1); //SHOULD THIS GO AFTER WRITE??
//set the program counter to this hard coded address
var lo = this.read(this.IRQ_ADDRESS);
var hi = this.read(this.IRQ_ADDRESS + 1);
this.PC = (hi << 8) | lo;
}
//branch if overflow clear
BVC() {
this.branch(this.getFlag(this.FLAG_V) == 0);
}
//branch if oveflow set
BVS() {
this.branch(this.getFlag(this.FLAG_V) == 1);
}
//clear carry flag
CLC() {
this.setFlag(this.FLAG_C, 0);
}
//clear decimal flag
CLD() {
this.setFlag(this.FLAG_D, 0);
}
//clear interrupt flag
CLI() {
this.setFlag(this.FLAG_I, 0);
}
//clear overflow flag
CLV() {
this.setFlag(this.FLAG_V, 0);
}
//compare data to the accumulator
CMP() {
var data = this.getData();
this.compare(data, this.A);
}
//compare data to X Register
CPX() {
var data = this.getData();
this.compare(data, this.X);
}
//compare data to Y Register
CPY() {
var data = this.getData();
this.compare(data, this.Y);
}
//decrement value at memory location
DEC() {
var data = this.getData();
data--;
this.setFlagsZandN(data);
data = this.mask255(data);
this.write(this.address, data);
}
//decrement X Register
DEX() {
this.X = this.mask255(this.X - 1);
this.setFlagsZandN(this.X);
}
//decrement Y Register
DEY() {
this.Y = this.mask255(this.Y - 1);
this.setFlagsZandN(this.Y);
}
//bitwise logic XOR
EOR() {
var data = this.getData();
this.A = this.mask255(this.A ^ data);
this.setFlagsZandN(this.A);
}
//increment value at memory location
INC() {
var data = this.getData();
data++;
this.setFlagsZandN(data);
data = this.mask255(data);
this.write(this.address, data);
}
//incremement X Register
INX() {
this.X++;
this.setFlagsZandN(this.X);
this.X = this.mask255(this.X);
}
//incremement Y Register
INY() {
this.Y++;
this.setFlagsZandN(this.Y);
this.Y = this.mask255(this.Y);
}
//jump to location
JMP() {
this.PC = this.address;
}
//jump to subroutine
JSR() {
this.PC--;
this.writeProgramCounterToStack();
this.PC = this.address;
}
//load the accumulator
LDA() {
this.A = this.getData();
// this.A = 120;
this.setFlagsZandN(this.A);
}
//load the X register
LDX() {
this.X = this.getData();
this.setFlagsZandN(this.X);
}
//load the Y register
LDY() {
this.Y = this.getData();
this.setFlagsZandN(this.Y);
}
//logical shift right
//set the carry bit to the old bit 0
LSR() {
var data: number;
//if addressing mode is implied then
//we are acting upon the accumulator
//other write it back to the same address
if (this.current_instruction.addressmode_name == "IMP") {
data = this.A;
this.setFlag(this.FLAG_C, this.A & 1)
data = data >> 1;
this.A = this.mask255(data);
}
else {
data = this.getData();
this.setFlag(this.FLAG_C, data & 1);
data = data >> 1;
this.write(this.address, this.mask255(data));
}
this.setFlagsZandN(data);
}
//no operation
NOP() {
}
//bitwise OR on accumulator
ORA() {
var data = this.getData();
this.A = this.mask255(this.A | data);
this.setFlagsZandN(this.A);
}
//push the accumulator onto the stack
//on the 6502 the stack pointer decreases
//as you push things onto it
PHA() {
this.write(0x0100 + this.STACK, this.A);
this.STACK--; //decrease the stack pointer;
}
//push status register to stack
//set break flag before push
PHP() {
// this.setFlag(this.FLAG_B, 1);
this.write(0x0100 + this.STACK, this.STATUS);
this.STACK--; //decrease the stack pointer;
}
//pop the stack and load it into the accumulator
//0x0100 is a hard coded address from which the stack pointer starts
PLA() {
this.STACK++; //increase the stack pointer;
this.A = this.read(0x0100 + this.STACK);
this.setFlagsZandN(this.A);
}
//pop status register off stack
PLP() {
this.STACK++; //increase the stack pointer;
this.STATUS = this.read(0x0100 + this.STACK);
this.setFlag(this.FLAG_U, 1);
this.setFlag(this.FLAG_B, 0); //??
}
//rotate left - shift all bits left by 1
//Move each of the bits in either A or M
//one place to the left. Bit 0 is filled
//with the current value of the carry flag
//whilst the old bit 7 becomes the new carry flag value.
ROL() {
var data: number;
if (this.current_instruction.addressmode_name == "IMP") {
data = this.A << 1 | this.getFlag(this.FLAG_C);
this.A = this.mask255(data);
}
else {
data = this.getData() << 1 | this.getFlag(this.FLAG_C);
this.write(this.address, this.mask255(data));
}
this.setFlag(this.FLAG_C, this.getBit(data, 8));
this.setFlagsZandN(data);
}
//rotate right - shift all bits right by 1
//Move each of the bits in either A or M one place to the right.
//Bit 7 is filled with the current value of the carry flag
//whilst the old bit 0 becomes the new carry flag value.
ROR() {
var data: number;
if (this.current_instruction.addressmode_name == "IMP") {
data = this.A >> 1 | (this.getFlag(this.FLAG_C) << 7);
this.setFlag(this.FLAG_C, this.getBit(this.A, 0));
this.A = this.mask255(data);
}
else {
var fetched_data = this.getData();
data = fetched_data >> 1 | (this.getFlag(this.FLAG_C) << 7);
this.setFlag(this.FLAG_C, this.getBit(fetched_data, 0));
this.write(this.address, this.mask255(data));
}
this.setFlagsZandN(data);
}
//restore the state of the program
//to before when the interrupt happened
//by restoring the status and the program counter
RTI() {
//restore status
this.STACK++; //increase the stack pointer;
this.STATUS = this.read(0x0100 + this.STACK);
this.setFlag(this.FLAG_U, 1);
this.updateFlagDebugViewer();
//restore program counter
this.STACK++;
var lo = this.read(0x0100 + this.STACK);
this.STACK++;
var hi = this.read(0x0100 + this.STACK);
this.PC = (hi << 8) | lo;
}
//return from subroutine
//The RTS instruction is used at the end of a subroutine
//to return to the calling routine. It pulls the
//program counter (minus one) from the stack.
RTS() {
//restore program counter
this.STACK++;
var lo = this.read(0x0100 + this.STACK);
this.STACK++;
var hi = this.read(0x0100 + this.STACK);
this.PC = (hi << 8) | lo;
this.PC++;
}
//subtract with carry
//so weirdly if the carry bit is not set it will be one less than you expect
//so 10 - 5 = 4 unless you set the carry bit
//https://stackoverflow.com/questions/48971814/i-dont-understand-whats-going-on-with-sbc
SBC() {
var data = this.getData();
var temp = this.A - data - (1 - this.getFlag(this.FLAG_C));
this.setFlagsZandN(temp);
//set the carry bit
this.setFlag(this.FLAG_C, temp < 0 ? 0 : 1);
//set the overflow flag based on a formula
//just trust that it works
if (((this.A ^ data) & 0x80) != 0 && ((this.A ^ temp) & 0x80) != 0)
this.setFlag(this.FLAG_V, 1);
else
this.setFlag(this.FLAG_V, 0);
//load the value back into the accumulator
//make sure it's 8-bit
this.A = temp & 0xFF;
}
//set the carry flag to 1
SEC() {
this.setFlag(this.FLAG_C, 1);
}
//set the decimal flag to 1
SED() {
this.setFlag(this.FLAG_D, 1);
}
//set the interrupt flag to 1
SEI() {
this.setFlag(this.FLAG_I, 1);
}
//store A register
STA() {
this.write(this.address, this.A);
}
//store X Register
STX() {
this.write(this.address, this.X);
}
//store Y register
STY() {
this.write(this.address, this.Y);
}
//transfer accumulator to X
//Copies the current contents of the accumulator into the
//X register and sets the zero and negative flags as appropriate.
TAX() {
this.X = this.A;
this.setFlagsZandN(this.X);
}
//transfer accumulator to Y
TAY() {
this.Y = this.A;
this.setFlagsZandN(this.Y);
}
//transfer stack pointer to X
TSX() {
this.X = this.STACK;
this.setFlagsZandN(this.X);
}
//transfer X to accumulator
TXA() {
this.A = this.X;
this.setFlagsZandN(this.A);
}
//transfer X to Stack Pointer
//don't look at flags z and n
TXS() {
this.STACK = this.X;
}
//transfer Y to accumulator
TYA() {
this.A = this.Y
this.setFlagsZandN(this.A);
}
XXX() {
//illegal opcode
}
} | the_stack |
* @title: 3D Physics rigid body constraints
* @subTitle: How to create physical constraints for physics rigid bodies.
* @description:
* This sample shows how to create each of the physics constraints (point to point, hinge, slider, cone twist,
* 6 degrees of freedom).
* Each object in the scene can be manipulated with the mouse to see how the constraints work.
*/
/*{{ javascript("jslib/camera.js") }}*/
/*{{ javascript("jslib/floor.js") }}*/
/*{{ javascript("jslib/mouseforces.js") }}*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/services/turbulenzservices.js") }}*/
/*{{ javascript("jslib/services/turbulenzbridge.js") }}*/
/*{{ javascript("jslib/services/gamesession.js") }}*/
/*{{ javascript("jslib/services/mappingtable.js") }}*/
/*{{ javascript("scripts/debugphysics.js") }}*/
/*{{ javascript("scripts/htmlcontrols.js") }}*/
/*global TurbulenzEngine: true */
/*global TurbulenzServices: false */
/*global RequestHandler: false */
/*global DebugConstraint: false */
/*global Camera: false */
/*global CameraController: false */
/*global Floor: false */
/*global MouseForces: false */
/*global HTMLControls: false */
TurbulenzEngine.onload = function onloadFn()
{
var errorCallback = function errorCallback(msg)
{
window.alert(msg);
};
var graphicsDeviceParameters = { };
var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters);
if (!graphicsDevice.shadingLanguageVersion)
{
errorCallback("No shading language support detected.\nPlease check your graphics drivers are up to date.");
graphicsDevice = null;
return;
}
var mathDeviceParameters = {};
var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters);
var inputDeviceParameters = { };
var inputDevice = TurbulenzEngine.createInputDevice(inputDeviceParameters);
var assetsToLoad = 4;
// Setup camera & controller
var camera = Camera.create(mathDevice);
var worldUp = mathDevice.v3BuildYAxis();
camera.lookAt(mathDevice.v3Build(-4.9, 5.3, -14.2), worldUp, mathDevice.v3Build(13.4, 5.7, 6.5));
camera.updateViewMatrix();
var cameraController = CameraController.create(graphicsDevice, inputDevice, camera);
var floor = Floor.create(graphicsDevice, mathDevice);
var requestHandlerParameters = {};
var requestHandler = RequestHandler.create(requestHandlerParameters);
var shader3d = null;
var technique3d = null;
var shader2d = null;
var technique2d = null;
var shaderDebug = null;
var techniqueDebug = null;
var debugConstraint = null;
var debugMode = true;
var shader3dLoaded = function shader3dLoadedFn(shaderText)
{
if (shaderText)
{
var shaderParameters = JSON.parse(shaderText);
shader3d = graphicsDevice.createShader(shaderParameters);
if (shader3d)
{
technique3d = shader3d.getTechnique("desatureTextureConstantColor3D");
assetsToLoad -= 1;
}
}
};
var techniqueParameters3d = graphicsDevice.createTechniqueParameters({
diffuse : null,
constantColor : mathDevice.v4Build(0, 0, 0, 1)
});
var shader2dLoaded = function shader2dLoadedFn(shaderText)
{
if (shaderText)
{
var shaderParameters = JSON.parse(shaderText);
shader2d = graphicsDevice.createShader(shaderParameters);
if (shader2d)
{
technique2d = shader2d.getTechnique("constantColor2D");
assetsToLoad -= 1;
}
}
};
var shaderDebugLoaded = function shaderDebugLoadedFn(shaderText)
{
if (shaderText)
{
var shaderParameters = JSON.parse(shaderText);
shaderDebug = graphicsDevice.createShader(shaderParameters);
if (shaderDebug)
{
techniqueDebug = shaderDebug.getTechnique("debug_lines");
assetsToLoad -= 1;
}
}
debugConstraint = DebugConstraint.create(graphicsDevice, techniqueDebug, mathDevice, camera);
};
var techniqueParameters2d = graphicsDevice.createTechniqueParameters({
clipSpace : null,
constantColor : mathDevice.v4Build(0, 0, 0, 1)
});
var linePrim = graphicsDevice.PRIMITIVE_LINES;
var cursorFormat = [graphicsDevice.VERTEXFORMAT_FLOAT3];
var cursorSemantic = graphicsDevice.createSemantics([graphicsDevice.SEMANTIC_POSITION]);
var semantics = graphicsDevice.createSemantics([graphicsDevice.SEMANTIC_POSITION, graphicsDevice.SEMANTIC_TEXCOORD]);
var primitive = graphicsDevice.PRIMITIVE_TRIANGLES;
// Create the dimensions of a cube and a door shape for rendering and physics purposes
var cubeExtents = mathDevice.v3Build(0.5, 0.5, 0.5);
var doorExtents = mathDevice.v3Build(0.5, 1.5, 0.05);
/*jshint white: false*/
function buildCuboidVertexBufferParams(extents)
{
var extents0 = extents[0];
var extents1 = extents[1];
var extents2 = extents[2];
return {
numVertices: 24,
attributes: ['FLOAT3', 'SHORT2N'],
dynamic: false,
data: [
-extents0, -extents1, extents2, 0, 0,
extents0, -extents1, extents2, 1, 0,
extents0, extents1, extents2, 1, 1,
-extents0, extents1, extents2, 0, 1,
-extents0, extents1, extents2, 0, 0,
extents0, extents1, extents2, 1, 0,
extents0, extents1, -extents2, 1, 1,
-extents0, extents1, -extents2, 0, 1,
-extents0, extents1, -extents2, 1, 1,
extents0, extents1, -extents2, 0, 1,
extents0, -extents1, -extents2, 0, 0,
-extents0, -extents1, -extents2, 1, 0,
-extents0, -extents1, -extents2, 0, 0,
extents0, -extents1, -extents2, 1, 0,
extents0, -extents1, extents2, 1, 1,
-extents0, -extents1, extents2, 0, 1,
extents0, -extents1, extents2, 0, 0,
extents0, -extents1, -extents2, 1, 0,
extents0, extents1, -extents2, 1, 1,
extents0, extents1, extents2, 0, 1,
-extents0, -extents1, -extents2, 0, 0,
-extents0, -extents1, extents2, 1, 0,
-extents0, extents1, extents2, 1, 1,
-extents0, extents1, -extents2, 0, 1
]
};
}
var indexbufferParameters =
{
numIndices: 36,
format: 'USHORT',
dynamic: false,
data: [
2, 0, 1,
3, 0, 2,
6, 4, 5,
7, 4, 6,
10, 8, 9,
11, 8, 10,
14, 12, 13,
15, 12, 14,
18, 16, 17,
19, 16, 18,
22, 20, 21,
23, 20, 22
]
};
/*jshint white: true*/
var cubeVertexbuffer = graphicsDevice.createVertexBuffer(buildCuboidVertexBufferParams(cubeExtents));
var doorVertexbuffer = graphicsDevice.createVertexBuffer(buildCuboidVertexBufferParams(doorExtents));
var indexbuffer = graphicsDevice.createIndexBuffer(indexbufferParameters);
var numIndices = indexbufferParameters.numIndices;
var clearColor = mathDevice.v4Build(0.95, 0.95, 1.0, 1.0);
// Cache mathDevice functions
var m43MulM44 = mathDevice.m43MulM44;
var isVisibleBoxOrigin = mathDevice.isVisibleBoxOrigin;
var v4Build = mathDevice.v4Build;
//
// Physics
//
var physicsDeviceParameters = { };
var physicsDevice = TurbulenzEngine.createPhysicsDevice(physicsDeviceParameters);
var dynamicsWorldParameters = { };
var dynamicsWorld = physicsDevice.createDynamicsWorld(dynamicsWorldParameters);
// Specify the generic settings for the collision objects
var collisionMargin = 0.005;
var mass = 1.0;
var pi = Math.PI;
// Floor is represented by a plane shape
var floorShape = physicsDevice.createPlaneShape({
normal : mathDevice.v3Build(0, 1, 0),
distance : 0,
margin : 0.001
});
var floorObject = physicsDevice.createCollisionObject({
shape : floorShape,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, -2.0, 0.0
),
friction : 0.5,
restitution : 0.3,
group: physicsDevice.FILTER_STATIC,
mask: physicsDevice.FILTER_ALL
});
// Adds the floor collision object to the physicsDevice
dynamicsWorld.addCollisionObject(floorObject);
// Set up some rigid body shapes to match the rendering shapes
var cubeShape = physicsDevice.createBoxShape({
halfExtents : cubeExtents,
margin : collisionMargin
});
var doorShape = physicsDevice.createBoxShape({
halfExtents : doorExtents,
margin : collisionMargin
});
// Do not use inertia for fixed objects (objects with mass = 0.0)
var inertia = cubeShape.inertia;
var rigidBodies = [];
// SLIDER CONSTRAINT
// Moveable Body
var sliderMovingBody = physicsDevice.createRigidBody({
shape : cubeShape,
mass : mass,
inertia : inertia,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
-2.0, 8.0, 0.0
)
});
rigidBodies[rigidBodies.length] = {
body : sliderMovingBody,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.54, 0.54, 0.82, 1),
constraintName : "Slider"
};
dynamicsWorld.addRigidBody(sliderMovingBody);
// Fixed Body
var sliderFixedBody = physicsDevice.createRigidBody({
shape : cubeShape,
mass : 0.0,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
2.0, 4.0, 0.0
)
});
rigidBodies[rigidBodies.length] = {
body : sliderFixedBody,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.54, 0.54, 0.82, 1),
constraintName : "Slider"
};
dynamicsWorld.addRigidBody(sliderFixedBody);
// A slider constraint only slides along the x-axis of the frame.
// Therefore rotate the frame of reference so that the x-axis is equal to the direction vector between the objects
var dir = mathDevice.v3Normalize(mathDevice.v3Sub(mathDevice.m43Pos(sliderFixedBody.transform),
mathDevice.m43Pos(sliderMovingBody.transform)), dir);
var xaxis = mathDevice.v3BuildXAxis();
var angle = Math.acos(mathDevice.v3Dot(dir, xaxis));
var axis = mathDevice.v3Normalize(mathDevice.v3Cross(xaxis, dir));
var frameInA = mathDevice.m43FromAxisRotation(axis, angle);
var sliderConstraint = physicsDevice.createSliderConstraint({
bodyA : sliderMovingBody,
bodyB : sliderFixedBody,
transformA : frameInA,
transformB : frameInA,
linearLowerLimit : 1.2,
linearUpperLimit : 8,
angularLowerLimit : 0,
angularUpperLimit : 0
});
dynamicsWorld.addConstraint(sliderConstraint);
// HINGE CONSTRAINT - fixed to world
// Rotated to roughly 160 degrees around the Y-axis - causes door to swing
var yaxis = mathDevice.v3BuildYAxis();
var transform = mathDevice.m43FromAxisRotation(yaxis, pi * (5 / 4));
mathDevice.m43SetPos(transform, mathDevice.v3Build(0.0, 5.0, -10.0));
// Door Body
var hingeDoorBody = physicsDevice.createRigidBody({
shape : doorShape,
mass : mass,
inertia : doorShape.inertia,
transform : transform
});
rigidBodies[rigidBodies.length] = {
body : hingeDoorBody,
vertexBuffer : doorVertexbuffer,
color : mathDevice.v4Build(0.89, 0.99, 0.43, 1),
constraintName : "Hinge"
};
dynamicsWorld.addRigidBody(hingeDoorBody);
// Creates a hinge that simulates a door frame
mathDevice.m43FromAxisRotation(xaxis, pi / 2, frameInA);
mathDevice.m43SetPos(frameInA, mathDevice.v3Build(-0.5, 0, 0));
var hingeConstraint = physicsDevice.createHingeConstraint({
bodyA : hingeDoorBody,
transformA : frameInA,
low : 0,
high : pi * (5 / 6) // 150 degrees
});
dynamicsWorld.addConstraint(hingeConstraint);
// POINT2POINT CONSTRAINT
// Moveable body1
var p2pMoveableBody1 = physicsDevice.createRigidBody({
shape : cubeShape,
mass : mass,
inertia : inertia,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 5.5, -20.0
),
linearDamping : 0.8,
angularDamping : 0.8
});
rigidBodies[rigidBodies.length] = {
body : p2pMoveableBody1,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.43, 0.89, 0.89, 1),
constraintName : "Point2Point"
};
dynamicsWorld.addRigidBody(p2pMoveableBody1);
// Moveable body2
var p2pMoveableBody2 = physicsDevice.createRigidBody({
shape : cubeShape,
mass : mass,
inertia : inertia,
transform : [
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 3.0, -20.0
],
linearDamping : 0.8,
angularDamping : 0.8
});
rigidBodies[rigidBodies.length] = {
body : p2pMoveableBody2,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.43, 0.89, 0.89, 1),
constraintName : "Point2Point"
};
dynamicsWorld.addRigidBody(p2pMoveableBody2);
// Fixed Body
var p2pFixedBody = physicsDevice.createRigidBody({
shape : cubeShape,
mass : 0.0,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 6.0, -20.0
)
});
rigidBodies[rigidBodies.length] = {
body : p2pFixedBody,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.43, 0.89, 0.89, 1),
constraintName : "Point2Point"
};
dynamicsWorld.addRigidBody(p2pFixedBody);
var pivotInA = mathDevice.v3Build(0.5, -0.5, -0.5);
// Transform the pivot point of bodyA into the object space of bodyB
// pivotInB = inverse(p2pMoveableBody1.transform) * (p2pFixedBody.transform * pivotInA)
var pivotInB = mathDevice.m43TransformVector(mathDevice.m43InverseOrthonormal(p2pMoveableBody1.transform),
mathDevice.m43TransformVector(p2pFixedBody.transform, pivotInA));
var p2pConstraint1 = physicsDevice.createPoint2PointConstraint({
bodyA : p2pMoveableBody1,
bodyB : p2pFixedBody,
pivotA : pivotInA,
pivotB : pivotInB
});
dynamicsWorld.addConstraint(p2pConstraint1);
pivotInA = mathDevice.v3Build(-0.5, -0.5, 0.5, pivotInA);
// Transform the pivot point of bodyA into the object space of bodyB
// pivotInB = inverse(p2pMoveableBody2.transform) * (p2pMoveableBody1.transform * pivotInA)
pivotInB = mathDevice.m43TransformVector(mathDevice.m43InverseOrthonormal(p2pMoveableBody2.transform),
mathDevice.m43TransformVector(p2pMoveableBody1.transform, pivotInA),
pivotInB);
var p2pConstraint2 = physicsDevice.createPoint2PointConstraint({
bodyA : p2pMoveableBody2,
bodyB : p2pMoveableBody1,
pivotA : pivotInA,
pivotB : pivotInB
});
dynamicsWorld.addConstraint(p2pConstraint2);
// CONETWIST CONSTRAINT
// Moveable Box
var coneTwistMoveableBody = physicsDevice.createRigidBody({
shape : cubeShape,
mass : mass,
inertia : inertia,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
3.0, 7.0, -30.0
),
linearDamping : 0.8,
angularDamping : 0.8
});
rigidBodies[rigidBodies.length] = {
body : coneTwistMoveableBody,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.88, 0.78, 0.78, 1),
constraintName : "ConeTwist"
};
dynamicsWorld.addRigidBody(coneTwistMoveableBody);
// Fixed body
var coneTwistFixedBody = physicsDevice.createRigidBody({
shape : cubeShape,
mass : 0.0,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 6.0, -30.0
)
});
rigidBodies[rigidBodies.length] = {
body : coneTwistFixedBody,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.88, 0.78, 0.78, 1),
constraintName : "ConeTwist"
};
dynamicsWorld.addRigidBody(coneTwistFixedBody);
// Set up the frame of reference for the conetwist constraint
var rotation = mathDevice.quatBuild(pi / 2, 0.0, 0.0, pi / 2);
mathDevice.quatNormalize(rotation, rotation);
var translation = mathDevice.v3Build(-3, 0.0, 0.0);
frameInA = mathDevice.m43FromRT(rotation, translation);
translation = mathDevice.v3Build(0.0, 0.0, 0.0, translation);
var frameInB = mathDevice.m43FromRT(rotation, translation);
var coneTwistConstraint = physicsDevice.createConeTwistConstraint({
bodyA : coneTwistMoveableBody,
bodyB : coneTwistFixedBody,
transformA : frameInA,
transformB : frameInB,
damping : 5.0,
swingSpan1 : (pi / 4) * 0.6,
swingSpan2 : pi / 4,
twistSpan : pi * 0.7
});
dynamicsWorld.addConstraint(coneTwistConstraint);
// 6DOF CONSTRAINT
// Fixed Body
var sixDOFFixedBody = physicsDevice.createRigidBody({
shape : cubeShape,
mass : 0.0,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
0.0, 6.0, -40.0
)
});
rigidBodies[rigidBodies.length] = {
body : sixDOFFixedBody,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.52, 0.88, 0.52, 1),
constraintName : "6DOF"
};
dynamicsWorld.addRigidBody(sixDOFFixedBody);
// Moveable body
var sixDOFMoveableBody = physicsDevice.createRigidBody({
shape : cubeShape,
mass : mass,
intertia : inertia,
transform : mathDevice.m43Build(
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
2.0, 4.0, -40.0
),
linearDamping : 0.6,
angularDamping : 0.6
});
rigidBodies[rigidBodies.length] = {
body : sixDOFMoveableBody,
vertexBuffer : cubeVertexbuffer,
color : mathDevice.v4Build(0.52, 0.88, 0.52, 1),
constraintName : "6DOF"
};
dynamicsWorld.addRigidBody(sixDOFMoveableBody);
var pos = mathDevice.v3Build(0.0, 0.0, 0.0);
frameInA = mathDevice.m43BuildTranslation(pos, frameInA);
pos = mathDevice.v3Build(3.0, 0.0, 0.0, pos);
frameInB = mathDevice.m43BuildTranslation(pos, frameInB);
var sixDOFConstraint = physicsDevice.create6DOFConstraint({
bodyA : sixDOFFixedBody,
bodyB : sixDOFMoveableBody,
transformA : frameInA,
transformB : frameInB,
linearLowerLimit : mathDevice.v3Build(-4.0, -2.0, -2.0),
linearUpperLimit : mathDevice.v3Build(4.0, 2.0, 2.0),
angularLowerLimit : mathDevice.v3Build(-pi / 2, -0.75, -pi / 2),
angularUpperLimit : mathDevice.v3Build(pi / 2, 0.75, pi / 2)
});
dynamicsWorld.addConstraint(sixDOFConstraint);
// Controls
var htmlControls = HTMLControls.create();
htmlControls.addCheckboxControl({
id: "checkbox01",
value: "debugMode",
isSelected: debugMode,
fn: function ()
{
debugMode = !debugMode;
return debugMode;
}
});
htmlControls.register();
var constraintTypeElement = document.getElementById("constrainttype");
//Callback to update the control
var constraintName;
var onKeyUp = function physicsOnkeyupFn(keynum)
{
cameraController.onkeyup(keynum);
};
// Mouse forces
var mouseForces = MouseForces.create(graphicsDevice, inputDevice, mathDevice, physicsDevice);
// Limit the impulse force of selecting objects in the scene
mouseForces.clamp = 1;
var mouseCodes = inputDevice.mouseCodes;
var onMouseDown = function (button)
{
if (mouseCodes.BUTTON_0 === button || mouseCodes.BUTTON_1 === button)
{
mouseForces.onmousedown();
}
};
var onMouseUp = function (button)
{
if (mouseCodes.BUTTON_0 === button || mouseCodes.BUTTON_1 === button)
{
mouseForces.onmouseup();
}
};
// Add event listeners
inputDevice.addEventListener("keyup", onKeyUp);
inputDevice.addEventListener("mousedown", onMouseDown);
inputDevice.addEventListener("mouseup", onMouseUp);
var numObjects = rigidBodies.length;
function desaturate(color, percent)
{
var newcolor = [];
newcolor[0] = color[0] * percent;
newcolor[1] = color[1] * percent;
newcolor[2] = color[2] * percent;
return newcolor;
}
//
// Update
//
var update = function updateFn()
{
inputDevice.update();
if (mouseForces.pickedBody)
{
// If we're dragging a body don't apply the movement to the camera
cameraController.pitch = 0;
cameraController.turn = 0;
cameraController.step = 0;
}
cameraController.update();
var aspectRatio = (graphicsDevice.width / graphicsDevice.height);
if (aspectRatio !== camera.aspectRatio)
{
camera.aspectRatio = aspectRatio;
camera.updateProjectionMatrix();
}
camera.updateViewProjectionMatrix();
if (0 >= assetsToLoad)
{
mouseForces.update(dynamicsWorld, camera, 0.0);
dynamicsWorld.update();
}
var vp = camera.viewProjectionMatrix;
var wvp;
var shape;
var body;
var color;
var vertexbuffer;
if (graphicsDevice.beginFrame())
{
graphicsDevice.clear(clearColor, 1.0, 0);
floor.render(graphicsDevice, camera);
if (0 >= assetsToLoad)
{
graphicsDevice.setTechnique(technique3d);
graphicsDevice.setTechniqueParameters(techniqueParameters3d);
for (var n = 0; n < numObjects; n += 1)
{
body = rigidBodies[n].body;
wvp = m43MulM44.call(mathDevice, body.transform, vp, wvp);
color = rigidBodies[n].color;
shape = body.shape;
vertexbuffer = rigidBodies[n].vertexBuffer;
if (vertexbuffer)
{
graphicsDevice.setStream(vertexbuffer, semantics);
graphicsDevice.setIndexBuffer(indexbuffer);
if (isVisibleBoxOrigin.call(mathDevice, shape.halfExtents, wvp))
{
// Use directly the active technique when just a single property changes
technique3d.worldViewProjection = wvp;
technique3d.constantColor = (body.active) ? color : desaturate(color, 0.5);
graphicsDevice.drawIndexed(primitive, numIndices);
if (mouseForces.pickedBody === body && constraintTypeElement)
{
constraintName = rigidBodies[n].constraintName;
constraintTypeElement.innerHTML = constraintName;
}
}
}
}
if (!mouseForces.pickedBody)
{
graphicsDevice.setTechnique(technique2d);
var screenWidth = graphicsDevice.width;
var screenHeight = graphicsDevice.height;
techniqueParameters2d['clipSpace'] = v4Build.call(mathDevice, 2.0 / screenWidth, -2.0 / screenHeight, -1.0, 1.0);
graphicsDevice.setTechniqueParameters(techniqueParameters2d);
var writer = graphicsDevice.beginDraw(linePrim,
4,
cursorFormat,
cursorSemantic);
if (writer)
{
var halfWidth = screenWidth * 0.5;
var halfHeight = screenHeight * 0.5;
writer([halfWidth - 10, halfHeight]);
writer([halfWidth + 10, halfHeight]);
writer([halfWidth, halfHeight - 10]);
writer([halfWidth, halfHeight + 10]);
graphicsDevice.endDraw(writer);
}
if (constraintTypeElement)
{
constraintTypeElement.innerHTML = "None Selected";
}
}
if (debugConstraint && debugMode)
{
debugConstraint.drawSliderConstraintLimits(sliderConstraint);
debugConstraint.drawHingeConstraintLimits(hingeConstraint);
debugConstraint.drawP2PConstraintLimits(p2pConstraint1);
debugConstraint.drawP2PConstraintLimits(p2pConstraint2);
debugConstraint.drawConeTwistConstraintLimits(coneTwistConstraint);
debugConstraint.draw6DOFConstraintLimits(sixDOFConstraint);
}
}
graphicsDevice.endFrame();
}
};
var intervalID = TurbulenzEngine.setInterval(update, 1000 / 60);
var mappingTableReceived = function mappingTableReceivedFn(mappingTable)
{
var textureParameters =
{
src : mappingTable.getURL("textures/crate.jpg"),
mipmaps : true,
onload : function (texture)
{
techniqueParameters3d['diffuse'] = texture;
assetsToLoad -= 1;
}
};
graphicsDevice.createTexture(textureParameters);
requestHandler.request({
src: mappingTable.getURL("shaders/generic3D.cgfx"),
onload: shader3dLoaded
});
requestHandler.request({
src: mappingTable.getURL("shaders/generic2D.cgfx"),
onload: shader2dLoaded
});
requestHandler.request({
src: mappingTable.getURL("shaders/debug.cgfx"),
onload: shaderDebugLoaded
});
};
var gameSessionCreated = function gameSessionCreatedFn(gameSession)
{
TurbulenzServices.createMappingTable(requestHandler,
gameSession,
mappingTableReceived);
};
var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated);
function destroyScene()
{
TurbulenzEngine.clearInterval(intervalID);
if (gameSession)
{
gameSession.destroy();
gameSession = null;
}
requestHandler = null;
indexbuffer = null;
indexbufferParameters = null;
cubeVertexbuffer = null;
doorVertexbuffer = null;
semantics = null;
technique3d = null;
shader3d = null;
technique2d = null;
shader2d = null;
shaderDebug = null;
debugConstraint = null;
techniqueDebug = null;
techniqueParameters2d = null;
techniqueParameters3d = null;
mouseForces = null;
floor = null;
cameraController = null;
camera = null;
rigidBodies = null;
cubeExtents = null;
doorExtents = null;
doorShape = null;
cubeShape = null;
constraintTypeElement = null;
htmlControls = null;
sliderMovingBody = null;
sliderFixedBody = null;
sliderConstraint = null;
hingeDoorBody = null;
hingeConstraint = null;
coneTwistMoveableBody = null;
coneTwistFixedBody = null;
coneTwistConstraint = null;
sixDOFMoveableBody = null;
sixDOFFixedBody = null;
sixDOFConstraint = null;
p2pFixedBody = null;
p2pMoveableBody1 = null;
p2pMoveableBody2 = null;
p2pConstraint1 = null;
p2pConstraint2 = null;
rotation = null;
transform = null;
frameInA = null;
frameInB = null;
pivotInA = null;
pivotInB = null;
dir = null;
xaxis = null;
yaxis = null;
m43MulM44 = null;
isVisibleBoxOrigin = null;
v4Build = null;
mouseCodes = null;
TurbulenzEngine.flush();
physicsDevice = null;
inputDevice = null;
graphicsDevice = null;
mathDevice = null;
}
TurbulenzEngine.onunload = destroyScene;
}; | the_stack |
import {
setBlockType,
toggleMark,
wrapIn,
chainCommands,
exitCode,
} from "prosemirror-commands";
import {
MarkType,
NodeType,
Node as ProsemirrorNode,
ResolvedPos,
} from "prosemirror-model";
import { EditorState, Transaction, Plugin, Selection } from "prosemirror-state";
import { liftTarget } from "prosemirror-transform";
import { EditorView } from "prosemirror-view";
import {
imageUploaderEnabled,
showImageUploader,
} from "../shared/prosemirror-plugins/image-upload";
import {
createMenuPlugin,
makeMenuIcon,
makeMenuLinkEntry,
makeMenuSpacerEntry,
addIf,
makeMenuDropdown,
dropdownItem,
dropdownSection,
} from "../shared/menu";
import { richTextSchema as schema, tableNodes } from "../shared/schema";
import type { CommonViewOptions } from "../shared/view";
import { LINK_TOOLTIP_KEY } from "./plugins/link-tooltip";
import { undo, redo } from "prosemirror-history";
//TODO
function toggleWrapIn(nodeType: NodeType) {
const nodeCheck = nodeTypeActive(nodeType);
const wrapInCommand = wrapIn(nodeType);
return (state: EditorState, dispatch?: (tr: Transaction) => void) => {
// if the node is not wrapped, go ahead and wrap it
if (!nodeCheck(state)) {
return wrapInCommand(state, dispatch);
}
const { $from, $to } = state.selection;
const range = $from.blockRange($to);
// check if there is a valid target to lift to
const target = range && liftTarget(range);
// if we cannot unwrap, return false
if (target == null) {
return false;
}
if (dispatch) {
dispatch(state.tr.lift(range, target));
}
return true;
};
}
/** Command to set a block type to a paragraph (plain text) */
const setToTextCommand = setBlockType(schema.nodes.paragraph);
function toggleBlockType(
nodeType: NodeType,
attrs?: { [key: string]: unknown }
) {
const nodeCheck = nodeTypeActive(nodeType);
const setBlockTypeCommand = setBlockType(nodeType, attrs);
return (state: EditorState, dispatch: (tr: Transaction) => void) => {
// if the node is not set, go ahead and set it
if (!nodeCheck(state)) {
return setBlockTypeCommand(state, dispatch);
}
return setToTextCommand(state, dispatch);
};
}
export function insertHorizontalRuleCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
if (inTable(state.selection)) {
return false;
}
dispatch &&
dispatch(
state.tr.replaceSelectionWith(schema.nodes.horizontal_rule.create())
);
return true;
}
export function inTable(selection: Selection): boolean {
return tableNodes.includes(selection.$head.parent.type);
}
function inTableHead(selection: Selection): boolean {
return selection.$head.parent.type === schema.nodes.table_header;
}
export const exitBlockCommand = chainCommands(exitCode, (state, dispatch) => {
dispatch(
state.tr
.replaceSelectionWith(schema.nodes.hard_break.create())
.scrollIntoView()
);
return true;
});
export function moveSelectionAfterTableCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return exitTableCommand(state, dispatch, false);
}
export function moveSelectionBeforeTableCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return exitTableCommand(state, dispatch, true);
}
function exitTableCommand(
state: EditorState,
dispatch: (tr: Transaction) => void,
before = false
): boolean {
if (!inTable(state.selection)) {
return false;
}
if (dispatch) {
// our hierarchy is table > table_head | table_body > table_row > table_cell
// and we're relying on that to be always true.
// That's why .after(-3) selects the parent _table_ node from a table_cell node
const type = schema.nodes.paragraph;
const newPosition = before
? state.selection.$head.before(-3) - 1
: state.selection.$head.after(-3) + 1;
const tr = state.tr;
// if the position before/after the table doesn't exist, let's insert a paragraph there
try {
tr.doc.resolve(newPosition);
} catch (e) {
const insertionPosition = before
? newPosition + 1
: newPosition - 1;
tr.insert(insertionPosition, type.create());
}
tr.setSelection(
Selection.near(tr.doc.resolve(Math.max(0, newPosition)), 1)
);
dispatch(tr.scrollIntoView());
}
return true;
}
export function insertTableRowBeforeCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return insertTableRowCommand(true, state, dispatch);
}
export function insertTableRowAfterCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return insertTableRowCommand(false, state, dispatch);
}
function insertTableRowCommand(
before: boolean,
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
if (!inTable(state.selection) || inTableHead(state.selection)) {
return false;
}
if (dispatch) {
const { $head } = state.selection;
const tableRowNode = $head.node(-1);
const newTableCells: ProsemirrorNode[] = [];
tableRowNode.forEach((cell) => {
newTableCells.push(schema.nodes.table_cell.create(cell.attrs));
});
const newTableRow = schema.nodes.table_row.create(null, newTableCells);
const positionToInsert = before ? $head.before(-1) : $head.after(-1);
const tr = state.tr.insert(positionToInsert, newTableRow);
dispatch(tr.scrollIntoView());
}
return true;
}
export function insertTableColumnAfterCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return insertTableColumnCommand(false, state, dispatch);
}
export function insertTableColumnBeforeCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return insertTableColumnCommand(true, state, dispatch);
}
/**
* Insert a new table column in this table
* 1. find the index of the selected table cell in the current table row
* 2. walk through the entire document to traverse all rows in our selected table
* 3. for each table row, find the table cell at the desired index and get its position
* 4. insert a new table_cell or table_header node before/after the found position
*/
function insertTableColumnCommand(
before: boolean,
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
if (!inTable(state.selection)) {
return false;
}
if (dispatch) {
const $head = state.selection.$head;
const selectedTable = $head.node(-3);
const selectedCellIndex = $head.index(-1);
// find and store all positions where we need to insert new cells
const newCells: [NodeType, number][] = [];
const tableOffset = $head.start(-3);
let targetCell: ProsemirrorNode;
// traverse the current table to find the absolute positions of our cells to be inserted
selectedTable.descendants((node: ProsemirrorNode, pos: number) => {
if (!tableNodes.includes(node.type)) {
return false; // don't descend into non-table nodes
}
if (node.type === schema.nodes.table_row) {
targetCell = node.child(selectedCellIndex);
}
if (targetCell && node == targetCell) {
const position = before
? selectedTable.resolve(pos + 1).before()
: selectedTable.resolve(pos + 1).after();
// position is relative to the start of the table, so we need
// to add the table offset (distance to start of document)
newCells.push([node.type, tableOffset + position]);
}
});
// insert new cells from bottom to top (reverse order)
// to avoid inserted cells making our found positions obsolete
let tr = state.tr;
for (const newCell of newCells.reverse()) {
tr = tr.insert(newCell[1], newCell[0].create());
}
dispatch(tr.scrollIntoView());
}
return true;
}
export function removeRowCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
if (!inTable(state.selection) || inTableHead(state.selection)) {
return false;
}
if (dispatch) {
const tr = state.tr;
const $head = state.selection.$head;
// delete entire table if we're deleting the last row in the table body
if ($head.node(-2).childCount === 1) {
return removeTableCommand(state, dispatch);
}
// delete from start to end of this row (node at -1 position from the table cell)
tr.delete($head.start(-1) - 1, $head.end(-1) + 1);
dispatch(tr.scrollIntoView());
}
return true;
}
export function removeColumnCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
if (!inTable(state.selection)) {
return false;
}
if (dispatch) {
const $head = state.selection.$head;
const table = $head.node(-3);
// remove entire table if this is the last remaining column
if ($head.node(-1).childCount === 1) {
return removeTableCommand(state, dispatch);
}
const cellIndex = $head.index(-1);
let targetCell: ProsemirrorNode;
const resolvedPositions: ResolvedPos[] = [];
const tableOffset = $head.start(-3);
table.descendants((node: ProsemirrorNode, pos: number) => {
if (!tableNodes.includes(node.type)) {
return false; // don't descend into non-table nodes
}
if (node.type === schema.nodes.table_row) {
targetCell =
node.childCount >= cellIndex + 1
? node.child(cellIndex)
: null;
}
if (targetCell && node == targetCell) {
resolvedPositions.push(table.resolve(pos + 1));
}
});
let tr = state.tr;
for (const cellPosition of resolvedPositions.reverse()) {
tr = tr.delete(
tableOffset + cellPosition.start() - 1,
tableOffset + cellPosition.end() + 1
);
}
dispatch(tr.scrollIntoView());
}
return true;
}
export function removeTableContentCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
if (!inTable(state.selection)) {
return false;
}
const { $from, $to } = state.selection;
// selection includes entire table
if ($from.start(-3) >= $from.pos - 3 && $from.end(-3) <= $to.pos + 3) {
return removeTableCommand(state, dispatch);
}
// selection includes entire row
if ($from.start(-1) >= $from.pos - 1 && $from.end(-1) <= $to.pos + 1) {
return removeRowCommand(state, dispatch);
}
// selection contains two arbitrary cells?
// prevent delete operation to prevent deleting the cell nodes
// themselves and breaking the table structure
if (!$from.sameParent($to)) {
return true;
}
return false;
}
function moveToCellCommand(
state: EditorState,
dispatch: (tr: Transaction) => void,
direction: number
): boolean {
if (direction !== -1 && direction !== 1) {
return false;
}
if (!inTable(state.selection)) return false;
const $head = state.selection.$head;
for (let level = -1; level > -4; level--) {
const parentIndex = $head.index(level);
const parent = $head.node(level);
if (!parent) continue;
// every time we want to skip the boundaries of a node (a cell, a row, ...)
// we have to consider the node's opening and closing positions, too. For
// each level, this will add an additional offset of 2 that we need to skip
const nodeOffset = 2;
const target = parent.maybeChild(parentIndex + direction);
if (!target) continue;
const newPos =
direction === -1
? $head.start() - nodeOffset * (level * -1)
: $head.end() + nodeOffset * (level * -1);
dispatch(
state.tr
.setSelection(Selection.near(state.tr.doc.resolve(newPos), 1))
.scrollIntoView()
);
return true;
}
// we're at the end of the table and still want to move forward?
// let's move the cursor below the table!
if (direction === 1) {
return moveSelectionAfterTableCommand(state, dispatch);
} else {
return moveSelectionBeforeTableCommand(state, dispatch);
}
}
export function moveToPreviousCellCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return moveToCellCommand(state, dispatch, -1);
}
export function moveToNextCellCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
return moveToCellCommand(state, dispatch, +1);
}
function removeTableCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
const $head = state.selection.$head;
if (dispatch) {
dispatch(state.tr.deleteRange($head.start(-3) - 1, $head.end(-3) + 1));
}
return true;
}
export function insertTableCommand(
state: EditorState,
dispatch: (tr: Transaction) => void
): boolean {
if (!setBlockType(schema.nodes.table)(state)) {
return false;
}
if (!dispatch) return true;
let headerIndex = 1;
let cellIndex = 1;
const cell = () =>
schema.nodes.table_cell.create(
null,
schema.text(`cell ${cellIndex++}`)
);
const header = () =>
schema.nodes.table_header.create(
null,
schema.text(`header ${headerIndex++}`)
);
const row = (...cells: ProsemirrorNode[]) =>
schema.nodes.table_row.create(null, cells);
const head = (row: ProsemirrorNode) =>
schema.nodes.table_head.create(null, row);
const body = (...rows: ProsemirrorNode[]) =>
schema.nodes.table_body.create(null, rows);
const table = (head: ProsemirrorNode, body: ProsemirrorNode) =>
schema.nodes.table.createChecked(null, [head, body]);
const paragraph = () => schema.nodes.paragraph.create(null);
const t = table(
head(row(header(), header())),
body(row(cell(), cell()), row(cell(), cell()))
);
let tr = state.tr.replaceSelectionWith(t);
dispatch(tr.scrollIntoView());
// if there's no selectable node after the inserted table, insert an empty paragraph
// because it makes selecting, navigating much more intuitive
const newState = state.apply(tr);
const nodeAfterTable = newState.doc.nodeAt(newState.tr.selection.to - 1);
if (nodeAfterTable && nodeAfterTable.type === schema.nodes.text) {
tr = newState.tr.insert(newState.tr.selection.to, paragraph());
dispatch(tr.scrollIntoView());
}
return true;
}
export function insertImageCommand(
state: EditorState,
dispatch: (tr: Transaction) => void,
view: EditorView
): boolean {
if (!imageUploaderEnabled(view)) {
return false;
}
if (!dispatch) return true;
showImageUploader(view);
return true;
}
export function insertLinkCommand(
state: EditorState,
dispatch: (tr: Transaction) => void,
view: EditorView
): boolean {
if (state.selection.empty) return false;
if (dispatch) {
const selectedText =
state.selection.content().content.firstChild?.textContent ?? null;
const linkMatch = /^http(s)?:\/\/\S+$/.exec(selectedText);
const linkUrl = linkMatch?.length > 0 ? linkMatch[0] : "";
const isInserting = toggleMark(schema.marks.link, { href: linkUrl })(
state,
dispatch
);
if (isInserting) {
const tr = LINK_TOOLTIP_KEY.setEditMode(true, state, view.state.tr);
view.dispatch(tr);
}
}
return true;
}
/**
* Creates an `active` method that returns true of the current selection is/contained in the current block type
* @param nodeType The type of the node to check for
*/
function nodeTypeActive(nodeType: NodeType) {
return function (state: EditorState) {
const { from, to } = state.selection;
let isNodeType = false;
// check all nodes in the selection for the right type
state.doc.nodesBetween(from, to, (node) => {
isNodeType = node.type.name === nodeType.name;
// stop recursing if the current node is the right type
return !isNodeType;
});
return isNodeType;
};
}
/**
* Creates an `active` method that returns true of the current selection has the passed mark
* @param mark The mark to check for
*/
function markActive(mark: MarkType) {
return function (state: EditorState) {
const { from, $from, to, empty } = state.selection;
if (empty) {
return !!mark.isInSet(state.storedMarks || $from.marks());
} else {
return state.doc.rangeHasMark(from, to, mark);
}
};
}
export const createMenu = (options: CommonViewOptions): Plugin =>
createMenuPlugin(
[
{
key: "toggleHeading",
command: toggleBlockType(schema.nodes.heading, { level: 1 }),
dom: makeMenuIcon("Header", "Heading", "heading-btn"),
active: nodeTypeActive(schema.nodes.heading),
},
{
key: "toggleBold",
command: toggleMark(schema.marks.strong),
dom: makeMenuIcon("Bold", "Bold", "bold-btn"),
active: markActive(schema.marks.strong),
},
{
key: "toggleEmphasis",
command: toggleMark(schema.marks.em),
dom: makeMenuIcon("Italic", "Italic", "italic-btn"),
active: markActive(schema.marks.em),
},
{
key: "toggleCode",
command: toggleMark(schema.marks.code),
dom: makeMenuIcon("Code", "Inline code", "code-btn"),
active: markActive(schema.marks.code),
},
addIf(
{
key: "toggleStrike",
command: toggleMark(schema.marks.strike),
dom: makeMenuIcon(
"Strikethrough",
"Strikethrough",
"strike-btn"
),
active: markActive(schema.marks.strike),
},
options.parserFeatures.extraEmphasis
),
makeMenuSpacerEntry(),
{
key: "toggleLink",
command: insertLinkCommand,
dom: makeMenuIcon("Link", "Link selection", "insert-link-btn"),
},
{
key: "toggleBlockquote",
command: toggleWrapIn(schema.nodes.blockquote),
dom: makeMenuIcon("Quote", "Blockquote", "blockquote-btn"),
active: nodeTypeActive(schema.nodes.blockquote),
},
{
key: "toggleCodeblock",
command: toggleBlockType(schema.nodes.code_block),
dom: makeMenuIcon("Codeblock", "Code block", "code-block-btn"),
active: nodeTypeActive(schema.nodes.code_block),
},
addIf(
{
key: "insertImage",
command: insertImageCommand,
dom: makeMenuIcon("Image", "Image", "insert-image-btn"),
},
!!options.imageUpload?.handler
),
addIf(
{
key: "insertTable",
command: insertTableCommand,
dom: makeMenuIcon("Table", "Table", "insert-table-btn"),
visible: (state: EditorState) => !inTable(state.selection),
},
options.parserFeatures.tables
),
addIf(tableDropdown, options.parserFeatures.tables),
makeMenuSpacerEntry(),
{
key: "toggleOrderedList",
command: toggleWrapIn(schema.nodes.ordered_list),
dom: makeMenuIcon(
"OrderedList",
"Numbered list",
"numbered-list-btn"
),
active: nodeTypeActive(schema.nodes.ordered_list),
},
{
key: "toggleUnorderedList",
command: toggleWrapIn(schema.nodes.bullet_list),
dom: makeMenuIcon(
"UnorderedList",
"Bulleted list",
"bullet-list-btn"
),
active: nodeTypeActive(schema.nodes.bullet_list),
},
{
key: "insertRule",
command: insertHorizontalRuleCommand,
dom: makeMenuIcon(
"HorizontalRule",
"Horizontal rule",
"horizontal-rule-btn"
),
},
makeMenuSpacerEntry(() => false, ["sm:d-inline-block"]),
{
key: "undo",
command: undo,
dom: makeMenuIcon("Undo", "Undo", "undo-btn", [
"sm:d-inline-block",
]),
visible: () => false,
},
{
key: "redo",
command: redo,
dom: makeMenuIcon("Refresh", "Redo", "redo-btn", [
"sm:d-inline-block",
]),
visible: () => false,
},
makeMenuSpacerEntry(),
//TODO eventually this will mimic the "help" dropdown in the prod editor
makeMenuLinkEntry("Help", "Help", options.editorHelpLink),
],
options.menuParentContainer
);
const tableDropdown = makeMenuDropdown(
"Table",
"Edit table",
"table-dropdown",
(state: EditorState) => inTable(state.selection),
dropdownSection("Column", "columnSection"),
dropdownItem("Remove column", removeColumnCommand, "remove-column-btn"),
dropdownItem(
"Insert column before",
insertTableColumnBeforeCommand,
"insert-column-before-btn"
),
dropdownItem(
"Insert column after",
insertTableColumnAfterCommand,
"insert-column-after-btn"
),
dropdownSection("Row", "rowSection"),
dropdownItem("Remove row", removeRowCommand, "remove-row-btn"),
dropdownItem(
"Insert row before",
insertTableRowBeforeCommand,
"insert-row-before-btn"
),
dropdownItem(
"Insert row after",
insertTableRowAfterCommand,
"insert-row-after-btn"
)
); | the_stack |
import { basename, dirname, globToRegExp, join } from "https://deno.land/std@0.144.0/path/mod.ts";
import { JSONC } from "https://deno.land/x/jsonc_parser@v0.0.1/src/jsonc.ts";
import { createGenerator, type UnoGenerator } from "../lib/@unocss/core.ts";
import { findFile } from "../lib/fs.ts";
import log from "../lib/log.ts";
import util from "../lib/util.ts";
import { isCanary, VERSION } from "../version.ts";
import type { AlephConfig, ImportMap, JSXConfig, ModuleLoader } from "./types.ts";
export const regFullVersion = /@\d+\.\d+\.\d+/;
export const builtinModuleExts = ["tsx", "ts", "mts", "jsx", "js", "mjs"];
/** Stores and returns the `fn` output in the `globalThis` object */
export async function globalIt<T>(name: string, fn: () => Promise<T>): Promise<T> {
const cache: T | undefined = Reflect.get(globalThis, name);
if (cache !== undefined) {
return cache;
}
const ret = await fn();
if (ret !== undefined) {
Reflect.set(globalThis, name, ret);
}
return ret;
}
/** Stores and returns the `fn` output in the `globalThis` object synchronously. */
export function globalItSync<T>(name: string, fn: () => T): T {
const cache: T | undefined = Reflect.get(globalThis, name);
if (cache !== undefined) {
return cache;
}
const ret = fn();
if (ret !== undefined) {
Reflect.set(globalThis, name, ret);
}
return ret;
}
/* Get Aleph.js package URI. */
export function getAlephPkgUri(): string {
return globalItSync("__ALEPH_PKG_URI", () => {
const uriFromEnv = Deno.env.get("ALEPH_PKG_URI");
if (uriFromEnv) {
return uriFromEnv;
}
const DEV_PORT = Deno.env.get("ALEPH_DEV_PORT");
if (DEV_PORT) {
return `http://localhost:${DEV_PORT}`;
}
const version = Deno.env.get("ALEPH_VERSION") || VERSION;
return `https://deno.land/x/${isCanary ? "aleph_canary" : "aleph"}@${version}`;
});
}
/** Get the UnoCSS generator, return `null` if the presets are empty. */
export function getUnoGenerator(): UnoGenerator | null {
const config: AlephConfig | undefined = Reflect.get(globalThis, "__ALEPH_CONFIG");
if (config === undefined) {
return null;
}
return globalItSync("__UNO_GENERATOR", () => {
if (config?.unocss?.presets) {
return createGenerator(config.unocss);
}
return null;
});
}
/** Get the deployment ID. */
export function getDeploymentId(): string | undefined {
return Deno.env.get("DENO_DEPLOYMENT_ID");
}
export type CookieOptions = {
expires?: number | Date;
maxAge?: number;
domain?: string;
path?: string;
httpOnly?: boolean;
secure?: boolean;
sameSite?: "lax" | "strict" | "none";
};
export function setCookieHeader(name: string, value: string, options?: CookieOptions): string {
const cookie = [`${name}=${value}`];
if (options) {
if (options.expires) {
cookie.push(`Expires=${new Date(options.expires).toUTCString()}`);
}
if (options.maxAge) {
cookie.push(`Max-Age=${options.maxAge}`);
}
if (options.domain) {
cookie.push(`Domain=${options.domain}`);
}
if (options.path) {
cookie.push(`Path=${options.path}`);
}
if (options.httpOnly) {
cookie.push("HttpOnly");
}
if (options.secure) {
cookie.push("Secure");
}
if (options.sameSite) {
cookie.push(`SameSite=${options.sameSite}`);
}
}
return cookie.join("; ");
}
export function toResponse(v: unknown, headers: Headers): Response {
if (
typeof v === "string" ||
v instanceof ArrayBuffer ||
v instanceof Uint8Array ||
v instanceof ReadableStream
) {
return new Response(v, { headers: headers });
}
if (v instanceof Blob || v instanceof File) {
headers.set("Content-Type", v.type);
headers.set("Content-Length", v.size.toString());
return new Response(v, { headers: headers });
}
if (util.isPlainObject(v) || Array.isArray(v)) {
return Response.json(v, { headers });
}
if (v === null) {
return new Response(null, { headers });
}
throw new Error("Invalid response type: " + typeof v);
}
export function fixResponse(res: Response, addtionHeaders: Headers, fixRedirect: boolean): Response {
if (res.status >= 300 && res.status < 400 && fixRedirect) {
return Response.json({ redirect: { location: res.headers.get("Location"), status: res.status } }, {
status: 501,
headers: addtionHeaders,
});
}
let headers: Headers | null = null;
addtionHeaders.forEach((value, name) => {
if (!headers) {
headers = new Headers(res.headers);
}
headers.set(name, value);
});
if (headers) {
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
}
return res;
}
/**
* fix remote url to local path.
* e.g. `https://esm.sh/react@17.0.2?dev` -> `/-/esm.sh/react@17.0.2?dev`
*/
export function toLocalPath(url: string): string {
if (util.isLikelyHttpURL(url)) {
let { hostname, pathname, port, protocol, search } = new URL(url);
const isHttp = protocol === "http:";
if ((isHttp && port === "80") || (protocol === "https:" && port === "443")) {
port = "";
}
return [
"/-/",
isHttp && "http_",
hostname,
port && "_" + port,
util.trimSuffix(pathname, "/"),
search,
].filter(Boolean).join("");
}
return url;
}
/**
* restore the remote url from local path.
* e.g. `/-/esm.sh/react@17.0.2` -> `https://esm.sh/react@17.0.2`
*/
export function restoreUrl(pathname: string): string {
let [h, ...rest] = pathname.substring(3).split("/");
let protocol = "https";
if (h.startsWith("http_")) {
h = h.substring(5);
protocol = "http";
}
const [host, port] = h.split("_");
return `${protocol}://${host}${port ? ":" + port : ""}/${rest.join("/")}`;
}
/** init loaders in `CLI` mode, or use prebuild loaders */
export async function initModuleLoaders(importMap?: ImportMap): Promise<ModuleLoader[]> {
const loaders: ModuleLoader[] = [];
if (Deno.env.get("ALEPH_CLI")) {
const { imports, __filename } = importMap ?? await loadImportMap();
for (const key in imports) {
if (/^\*\.{?(\w+, ?)*\w+}?$/i.test(key)) {
let src = imports[key];
if (src.endsWith("!loader")) {
src = util.trimSuffix(src, "!loader");
if (src.startsWith("./") || src.startsWith("../")) {
src = "file://" + join(dirname(__filename), src);
}
let { default: loader } = await import(src);
if (typeof loader === "function") {
loader = new loader();
}
if (loader !== null && typeof loader === "object" && typeof loader.load === "function") {
const glob = "/**/" + key;
const reg = globToRegExp(glob);
const Loader = {
meta: { src, glob },
test: (pathname: string) => reg.test(pathname),
load: (specifier: string, content: string, env: Record<string, unknown>) =>
loader.load(specifier, content, env),
};
loaders.push(Loader);
}
}
}
}
}
return loaders;
}
/** Load the JSX config base the given import maps and the existing deno config. */
export async function loadJSXConfig(importMap: ImportMap): Promise<JSXConfig> {
const jsxConfig: JSXConfig = {};
const denoConfigFile = await findFile(["deno.jsonc", "deno.json", "tsconfig.json"]);
if (denoConfigFile) {
try {
const { compilerOptions } = await parseJSONFile(denoConfigFile);
const { jsx, jsxImportSource, jsxFactory } = (compilerOptions || {}) as Record<string, unknown>;
if (
(jsx === undefined || jsx === "react-jsx" || jsx === "react-jsxdev") &&
util.isFilledString(jsxImportSource)
) {
jsxConfig.jsxImportSource = jsxImportSource;
jsxConfig.jsxRuntime = jsxImportSource.includes("preact") ? "preact" : "react";
} else if (jsx === undefined || jsx === "react") {
jsxConfig.jsxRuntime = jsxFactory === "h" ? "preact" : "react";
}
} catch (error) {
log.error(`Failed to parse ${basename(denoConfigFile)}: ${error.message}`);
}
} else if (Deno.env.get("ALEPH_DEV")) {
const jsonFile = join(Deno.env.get("ALEPH_DEV_ROOT")!, "deno.json");
const { compilerOptions } = await parseJSONFile(jsonFile);
const { jsx, jsxImportSource, jsxFactory } = (compilerOptions || {}) as Record<string, unknown>;
if (
(jsx === undefined || jsx === "react-jsx" || jsx === "react-jsxdev") &&
util.isFilledString(jsxImportSource)
) {
jsxConfig.jsxImportSource = jsxImportSource;
jsxConfig.jsxRuntime = jsxImportSource.includes("preact") ? "preact" : "react";
} else if (jsx === undefined || jsx === "react") {
jsxConfig.jsxRuntime = jsxFactory === "h" ? "preact" : "react";
}
}
let fuzzRuntimeUrl: string | null = null;
for (const url of Object.values(importMap.imports)) {
let m = url.match(/^https?:\/\/esm\.sh\/(p?react)@(\d+\.\d+\.\d+(-[a-z\d.]+)*)(\?|$)/);
if (!m) {
m = url.match(/^https?:\/\/esm\.sh\/(p?react)@.+/);
}
if (m) {
const { searchParams } = new URL(url);
if (searchParams.has("pin")) {
jsxConfig.jsxRuntimeCdnVersion = util.trimPrefix(searchParams.get("pin")!, "v");
}
if (!jsxConfig.jsxRuntime) {
jsxConfig.jsxRuntime = m[1] as "react" | "preact";
}
if (m[2]) {
jsxConfig.jsxRuntimeVersion = m[2];
if (jsxConfig.jsxImportSource) {
jsxConfig.jsxImportSource = `https://esm.sh/${jsxConfig.jsxRuntime}@${m[2]}`;
}
} else {
fuzzRuntimeUrl = url;
}
break;
}
}
// get acctual react version from esm.sh
if (fuzzRuntimeUrl) {
log.info(`Checking ${jsxConfig.jsxRuntime} version...`);
const text = await fetch(fuzzRuntimeUrl).then((resp) => resp.text());
const m = text.match(/https?:\/\/cdn\.esm\.sh\/(v\d+)\/p?react@(\d+\.\d+\.\d+(-[a-z\d.]+)*)\//);
if (m) {
jsxConfig.jsxRuntimeCdnVersion = m[1].slice(1);
jsxConfig.jsxRuntimeVersion = m[2];
if (jsxConfig.jsxImportSource) {
jsxConfig.jsxImportSource = `https://esm.sh/${jsxConfig.jsxRuntime}@${m[2]}`;
}
log.info(`${jsxConfig.jsxRuntime}@${jsxConfig.jsxRuntimeVersion} is used`);
}
}
return jsxConfig;
}
/** Load the import maps from the json file. */
export async function loadImportMap(cwd?: string): Promise<ImportMap> {
const importMap: ImportMap = { __filename: "", imports: {}, scopes: {} };
if (Deno.env.get("ALEPH_DEV")) {
const alephPkgUri = Deno.env.get("ALEPH_PKG_URI") || `http://localhost:${Deno.env.get("ALEPH_DEV_PORT")}`;
const importMapFile = join(Deno.env.get("ALEPH_DEV_ROOT")!, "import_map.json");
const { __filename, imports, scopes } = await parseImportMap(importMapFile);
Object.assign(importMap, {
__filename,
imports: {
...imports,
"@unocss/": `${alephPkgUri}/lib/@unocss/`,
"aleph/": `${alephPkgUri}/`,
"aleph/server": `${alephPkgUri}/server/mod.ts`,
"aleph/react": `${alephPkgUri}/framework/react/mod.ts`,
"aleph/vue": `${alephPkgUri}/framework/vue/mod.ts`,
},
scopes,
});
}
const importMapFile = await findFile(
["import_map", "import-map", "importmap", "importMap"].map((v) => `${v}.json`),
cwd,
);
if (importMapFile) {
try {
const { __filename, imports, scopes } = await parseImportMap(importMapFile);
Object.assign(importMap, { __filename });
Object.assign(importMap.imports, imports);
Object.assign(importMap.scopes, scopes);
} catch (e) {
log.error("loadImportMap:", e.message);
}
}
return importMap;
}
export function applyImportMap(specifier: string, importMap: ImportMap): string {
if (specifier in importMap.imports) {
return importMap.imports[specifier];
}
for (const key in importMap.imports) {
if (key.endsWith("/") && specifier.startsWith(key)) {
return importMap.imports[key] + specifier.slice(key.length);
}
}
// todo: support scopes
return specifier;
}
export async function parseJSONFile(jsonFile: string): Promise<Record<string, unknown>> {
const raw = await Deno.readTextFile(jsonFile);
if (jsonFile.endsWith(".jsonc")) {
return JSONC.parse(raw);
}
return JSON.parse(raw);
}
export async function parseImportMap(importMapFile: string): Promise<ImportMap> {
const importMap: ImportMap = { __filename: importMapFile, imports: {}, scopes: {} };
const data = await parseJSONFile(importMapFile);
const imports: Record<string, string> = toStringMap(data.imports);
const scopes: Record<string, Record<string, string>> = {};
if (util.isPlainObject(data.scopes)) {
Object.entries(data.scopes).forEach(([scope, imports]) => {
scopes[scope] = toStringMap(imports);
});
}
Object.assign(importMap, { imports, scopes });
return importMap;
}
function toStringMap(v: unknown): Record<string, string> {
const m: Record<string, string> = {};
if (util.isPlainObject(v)) {
Object.entries(v).forEach(([key, value]) => {
if (key === "") {
return;
}
if (util.isFilledString(value)) {
m[key] = value;
return;
}
if (util.isFilledArray(value)) {
for (const v of value) {
if (util.isFilledString(v)) {
m[key] = v;
return;
}
}
}
});
}
return m;
} | the_stack |
import React, { useEffect, useState, useRef } from 'react'
import { useRouter } from 'next/router'
import Head from 'next/head'
import intersection from 'lodash/intersection'
import NextLink from 'next/link'
import {
Text,
Stack,
Box,
Link,
Breadcrumbs,
AccordionCard,
TopicCard,
FocusableBox,
Navigation,
LinkContext,
Button,
} from '@island.is/island-ui/core'
import { Card, Sticky } from '@island.is/web/components'
import { withMainLayout } from '@island.is/web/layouts/main'
import { Screen } from '@island.is/web/types'
import {
GET_NAMESPACE_QUERY,
GET_ARTICLES_QUERY,
GET_CATEGORIES_QUERY,
GET_LIFE_EVENTS_IN_CATEGORY_QUERY,
} from '@island.is/web/screens/queries'
import { SidebarLayout } from '@island.is/web/screens/Layouts/SidebarLayout'
import { useNamespace } from '@island.is/web/hooks'
import useContentfulId from '@island.is/web/hooks/useContentfulId'
import {
GetLifeEventsInCategoryQuery,
GetNamespaceQuery,
GetArticlesQuery,
QueryGetArticlesArgs,
ContentLanguage,
QueryGetNamespaceArgs,
GetArticleCategoriesQuery,
QueryGetArticleCategoriesArgs,
QueryGetLifeEventsInCategoryArgs,
Image,
ArticleGroup,
} from '../../graphql/schema'
import { CustomNextError } from '@island.is/web/units/errors'
import { LinkType, useLinkResolver } from '@island.is/web/hooks/useLinkResolver'
import { scrollTo } from '@island.is/web/hooks/useScrollSpy'
type Articles = GetArticlesQuery['getArticles']
type LifeEvents = GetLifeEventsInCategoryQuery['getLifeEventsInCategory']
// adds or removes selected category in hash array
export const updateHashArray = (
hashArray: string[],
categoryId: string,
): string[] => {
let tempArr = hashArray ?? []
if (!!categoryId && categoryId.length > 0) {
if (tempArr.includes(categoryId)) {
tempArr = hashArray.filter((x) => x !== categoryId)
} else {
tempArr = tempArr.concat([categoryId])
}
}
return tempArr
}
// gets "active" category that we use to scroll to on inital render
export const getActiveCategory = (hashArr: string[]): string | null => {
if (!!hashArr && hashArr.length > 0) {
const activeCategory = hashArr[hashArr.length - 1].replace('#', '')
return activeCategory.length > 0 ? activeCategory : null
}
return null
}
// creates hash string from array
export const getHashString = (hashArray: string[]): string => {
if (!!hashArray && hashArray.length > 0) {
return hashArray.length > 1 ? hashArray.join(',') : hashArray[0]
}
return ''
}
// creates hash array from string
export const getHashArr = (hashString: string): string[] => {
if (!!hashString && hashString.length > 0) {
hashString = hashString.replace('#', '')
return hashString.length > 0 ? hashString.split(',') : null
}
return null
}
interface CategoryProps {
articles: Articles
categories: GetArticleCategoriesQuery['getArticleCategories']
namespace: GetNamespaceQuery['getNamespace']
lifeEvents: LifeEvents
slug: string
}
const Category: Screen<CategoryProps> = ({
articles,
lifeEvents,
categories,
namespace,
slug,
}) => {
const itemsRef = useRef<Array<HTMLElement | null>>([])
const [hashArray, setHashArray] = useState<string[]>([])
const Router = useRouter()
const n = useNamespace(namespace)
const { linkResolver } = useLinkResolver()
const getCurrentCategory = () => categories.find((x) => x.slug === slug)
// group articles
const { groups, cards, otherArticles } = articles.reduce(
(content, article) => {
// check if this is not the main category for this article
if (article?.category?.title !== getCurrentCategory().title) {
content.otherArticles.push(article)
return content
}
if (article?.group?.slug && !content.groups[article?.group?.slug]) {
// group does not exist create the collection
content.groups[article?.group?.slug] = {
title: article?.group?.title,
description: article?.group?.description,
articles: [article],
groupSlug: article?.group?.slug,
importance: article?.group?.importance,
}
} else if (article?.group?.slug) {
// group should exists push into collection
content.groups[article?.group?.slug].articles.push(article)
} else {
// this article belongs to no group
content.cards.push(article)
}
return content
},
{
groups: {},
cards: [],
otherArticles: [],
},
)
// Get all available subgroups.
const availableSubgroups = articles
.map((article) => article.subgroup)
.filter(
(value, index, all) =>
all.findIndex((t) => JSON.stringify(t) === JSON.stringify(value)) ===
index,
)
.filter((x) => x)
useContentfulId(getCurrentCategory()?.id)
// find current category in categories list
const category = getCurrentCategory()
useEffect(() => {
const urlHash = window.location.hash ?? ''
if (urlHash && urlHash.length > 0) {
const ulrHashArr = getHashArr(urlHash)
const activeCategory = getActiveCategory(ulrHashArr)
setHashArray(ulrHashArr)
if (activeCategory) {
scrollTo(activeCategory, { marginTop: 24 })
}
}
}, [])
const sidebarCategoryLinks = categories.map(
({ __typename: typename, title, slug }) => {
return {
title,
typename,
active: slug === Router.query.slug,
slug: [slug],
}
},
)
const groupArticlesBySubgroup = (articles: Articles, groupSlug?: string) => {
const bySubgroup = articles.reduce((result, item) => {
const key = item?.subgroup?.title ?? 'unknown'
return {
...result,
[key]: [...(result[key] || []), item],
}
}, {})
// add "other" articles as well
const articlesBySubgroup = otherArticles.reduce((result, item) => {
const titles = item.otherSubgroups.map((x) => x.title)
const subgroupsFound = intersection(Object.keys(result), titles)
const key = 'unknown'
// if there is no sub group found then at least show it in the group
if (
!subgroupsFound.length &&
item.otherGroups.find((x) => x.slug === groupSlug)
) {
return {
...result,
[key]: [...(result[key] || []), item],
}
}
return subgroupsFound.reduce((r, k) => {
return {
...r,
[k]: [...r[k], item],
}
}, result)
}, bySubgroup)
return { articlesBySubgroup }
}
const handleAccordionClick = (groupSlug: string) => {
const updatedArr = updateHashArray(hashArray, groupSlug)
setHashArray(updatedArr)
Router.replace({
pathname: linkResolver(category.__typename as LinkType, [slug]).href,
hash: getHashString(updatedArr),
})
}
const sortArticles = (articles: Articles) => {
// Sort articles by importance (which defaults to 0).
// If both articles being compared have the same importance we sort by comparing their titles.
const sortedArticles = articles.sort((a, b) =>
a.importance > b.importance
? -1
: a.importance === b.importance
? a.title.localeCompare(b.title)
: 1,
)
// If it's sorted alphabetically we need to be able to communicate that.
const isSortedAlphabetically =
JSON.stringify(sortedArticles) ===
JSON.stringify(
[...articles].sort((a, b) => a.title.localeCompare(b.title)),
)
return { sortedArticles, isSortedAlphabetically }
}
const sortSubgroups = (articlesBySubgroup: Record<string, Articles>) =>
Object.keys(articlesBySubgroup).sort((a, b) => {
// 'unknown' is a valid subgroup key but we'll sort it to the bottom
if (a === 'unknown') {
return 1
} else if (b === 'unknown') {
return -1
}
// Look up the subgroups being sorted and find+compare their importance.
// If their importance is equal we sort alphabetically.
const foundA = availableSubgroups.find((subgroup) => subgroup.title === a)
const foundB = availableSubgroups.find((subgroup) => subgroup.title === b)
if (foundA && foundB) {
return foundA.importance > foundB.importance
? -1
: foundA.importance === foundB.importance
? foundA.title.localeCompare(foundB.title)
: 1
}
// Fall back to alphabet
return a.localeCompare(b)
})
const sortedGroups = Object.values(
groups,
).sort((a: ArticleGroup, b: ArticleGroup) =>
a.importance > b.importance
? -1
: a.importance === b.importance && a.title.localeCompare(b.title, 'is'),
)
return (
<>
<Head>
<title>{category.title} | Ísland.is</title>
</Head>
<SidebarLayout
isSticky={false}
sidebarContent={
<Sticky>
<Navigation
baseId="desktopNav"
colorScheme="purple"
items={sidebarCategoryLinks}
title={n('sidebarHeader')}
renderLink={(link, { typename, slug }) => {
return (
<Link
href={linkResolver(typename as LinkType, slug).href}
onClick={() => setHashArray([])}
skipTab
pureChildren
>
{link}
</Link>
)
}}
/>
</Sticky>
}
>
<Box
paddingBottom={[2, 2, 4]}
display={['none', 'none', 'block']}
printHidden
>
<Breadcrumbs
items={[
{
title: 'Ísland.is',
href: '/',
},
]}
renderLink={(link) => {
return (
<NextLink {...linkResolver('homepage')} passHref>
{link}
</NextLink>
)
}}
/>
</Box>
<Box
paddingBottom={[2, 2, 4]}
display={['flex', 'flex', 'none']}
justifyContent="spaceBetween"
alignItems="center"
printHidden
>
<Box flexGrow={1} marginRight={6} overflow={'hidden'}>
<LinkContext.Provider
value={{
linkRenderer: (href, children) => (
<Link href={href} skipTab>
{children}
</Link>
),
}}
>
<Text truncate>
<a {...linkResolver('homepage')}>
<Button
as="span"
preTextIcon="arrowBack"
preTextIconType="filled"
size="small"
type="button"
variant="text"
>
Ísland.is
</Button>
</a>
</Text>
</LinkContext.Provider>
</Box>
</Box>
<Box display={['block', 'block', 'none']}>
<Navigation
baseId="mobileNav"
colorScheme="purple"
isMenuDialog
renderLink={(link, { typename, slug }) => {
return (
<Link
href={linkResolver(typename as LinkType, slug).href}
onClick={() => setHashArray([])}
skipTab
pureChildren
>
{link}
</Link>
)
}}
items={sidebarCategoryLinks}
title={n('sidebarHeader')}
activeItemTitle={category.title}
/>
</Box>
<Box paddingBottom={[5, 5, 10]}>
<Text variant="h1" as="h1" paddingTop={[4, 4, 0]} paddingBottom={2}>
{category.title}
</Text>
<Text variant="intro" as="p">
{category.description}
</Text>
</Box>
<Stack space={2}>
{sortedGroups.map(({ groupSlug }, index) => {
const { title, description, articles } = groups[groupSlug]
const { articlesBySubgroup } = groupArticlesBySubgroup(
articles,
groupSlug,
)
const sortedSubgroupKeys = sortSubgroups(articlesBySubgroup)
const expanded = hashArray.includes(groupSlug)
return (
<div
key={index}
id={groupSlug}
ref={(el) => (itemsRef.current[index] = el)}
>
<AccordionCard
id={`accordion-item-${groupSlug}`}
label={title}
labelUse="h2"
labelVariant="h3"
expanded={expanded}
visibleContent={description}
onToggle={() => {
handleAccordionClick(groupSlug)
}}
>
<Box paddingTop={2}>
{sortedSubgroupKeys.map((subgroup, index) => {
const { sortedArticles } = sortArticles(
articlesBySubgroup[subgroup],
)
// Articles with 1 subgroup only have the "other" group and don't get a heading.
const hasSubgroups = sortedSubgroupKeys.length > 1
const noSubgroupNameKeys = [
'unknown',
'undefined',
'null',
]
// Rename unknown group to 'Other'
const subgroupName =
noSubgroupNameKeys.indexOf(subgroup) !== -1 || !subgroup
? n('other')
: subgroup
const heading = hasSubgroups ? subgroupName : ''
return (
<React.Fragment key={subgroup}>
{heading && (
<Text
variant="h5"
as="h3"
paddingBottom={3}
paddingTop={index === 0 ? 0 : 3}
>
{heading}
</Text>
)}
<Stack space={2}>
{sortedArticles.map(
({
__typename: typename,
title,
slug,
processEntry,
}) => {
return (
<FocusableBox key={slug} borderRadius="large">
<TopicCard
href={
linkResolver(
typename.toLowerCase() as LinkType,
[slug],
).href
}
tag={
!!processEntry &&
n('applicationProcess', 'Umsókn')
}
>
{title}
</TopicCard>
</FocusableBox>
)
},
)}
</Stack>
</React.Fragment>
)
})}
</Box>
</AccordionCard>
</div>
)
})}
{lifeEvents.map(
(
{ __typename: typename, title, slug, intro, thumbnail, image },
index,
) => {
return (
<Card
key={index}
link={linkResolver(typename as LinkType, [slug])}
description={intro}
title={title}
image={(thumbnail || image) as Image}
tags={[
{
title: n('categoryTag'),
},
]}
/>
)
},
)}
{cards.map(
({ __typename: typename, title, content, slug }, index) => {
return (
<Card
key={index}
title={title}
description={content}
link={linkResolver(typename as LinkType, [slug])}
/>
)
},
)}
</Stack>
</SidebarLayout>
</>
)
}
Category.getInitialProps = async ({ apolloClient, locale, query }) => {
const slug = query.slug as string
const [
{
data: { getArticles: articles },
},
{
data: { getLifeEventsInCategory: lifeEvents },
},
{
data: { getArticleCategories },
},
namespace,
] = await Promise.all([
apolloClient.query<GetArticlesQuery, QueryGetArticlesArgs>({
query: GET_ARTICLES_QUERY,
variables: {
input: {
lang: locale as ContentLanguage,
category: slug,
size: 150,
},
},
}),
apolloClient.query<
GetLifeEventsInCategoryQuery,
QueryGetLifeEventsInCategoryArgs
>({
query: GET_LIFE_EVENTS_IN_CATEGORY_QUERY,
variables: {
input: {
slug,
lang: locale as ContentLanguage,
},
},
}),
apolloClient.query<
GetArticleCategoriesQuery,
QueryGetArticleCategoriesArgs
>({
query: GET_CATEGORIES_QUERY,
variables: {
input: {
lang: locale as ContentLanguage,
},
},
}),
apolloClient
.query<GetNamespaceQuery, QueryGetNamespaceArgs>({
query: GET_NAMESPACE_QUERY,
variables: {
input: {
namespace: 'Categories',
lang: locale,
},
},
})
.then((res) => JSON.parse(res.data.getNamespace.fields)),
])
const categoryExists = getArticleCategories.some(
(category) => category.slug === slug,
)
// if requested category si not in returned list of categories we assume it does not exist
if (!categoryExists) {
throw new CustomNextError(404, 'Category not found')
}
return {
articles,
lifeEvents,
categories: getArticleCategories,
namespace,
slug,
}
}
export default withMainLayout(Category) | the_stack |
export function script(options?: script.Options): script.Script;
declare namespace script {
interface Options {
/**
* Determines if execution of tests should be delayed until the CLI runs them explicitly.
*
* @default true
*/
schedule?: boolean;
/**
*
*/
cli?: Cli;
}
interface Cli {
/**
* Specifies an assertion library module path to require and make available under Lab.assertions as well as use for enhanced reporting.
*/
readonly assert?: string;
/**
* Forces the process to exist with a non zero exit code on the first test failure.
*
* @default false
*/
readonly bail?: boolean;
/**
* Enables color output.
*
* @default terminal capabilities.
*/
readonly colors?: boolean;
/**
* Sets a timeout value for before, after, beforeEach, afterEach in milliseconds.
*
* @default 0
*/
readonly 'context-timeout'?: number;
/**
* Enable code coverage analysis
*
* @default false
*/
readonly coverage?: boolean;
/**
* Includes all files in coveragePath in report.
*
* @default false
*/
readonly 'coverage-all'?: boolean;
/**
* Set code coverage excludes (an array of path strings).
*/
readonly 'coverage-exclude'?: string[];
/**
* Prevents recursive inclusion of all files in coveragePath in report.
*
* @default false
*/
readonly 'coverage-flat'?: boolean;
/**
* Enables coverage on external modules.
*/
readonly 'coverage-module'?: string[];
/**
* Sets code coverage path.
*/
readonly 'coverage-path'?: string;
/**
* File pattern to use for locating files for coverage.
*/
readonly coveragePattern?: RegExp;
/**
* Minimum plan threshold to apply to all tests that don't define any plan.
*/
readonly 'default-plan-threshold'?: number;
/**
* Skip all tests (dry run).
*
* @default: false
*/
readonly dry?: boolean;
/**
* Value to set NODE_ENV before tests.
*
* @default: 'test'
*/
readonly environment?: string;
/**
* Number of times to retry failing tests (marked explicitly for retry).
*
* @default 5
*/
readonly retries?: number;
/**
* Prevent recursive collection of tests within the provided path.
*
* @default false
*/
readonly flat?: boolean;
/**
* Sets a list of globals to ignore for the leak detection (comma separated).
*/
readonly globals?: string[];
/**
* Only run tests matching the given pattern which is internally compiled to a RegExp.
*/
readonly grep?: string;
/**
* Range of test ids to execute.
*/
readonly id?: number[];
/**
* Sets lab to start with the node.js native debugger.
*
* @default false
*/
readonly inspect?: boolean;
/**
* Sets global variable leaks detection.
*
* @default true
*/
readonly leaks?: boolean;
/**
* Enables code lint.
*
* @default false
*/
readonly lint?: boolean;
/**
* Linter path.
*
* @default 'eslint'
*/
readonly linter?: string;
/**
* Apply any fixes from the linter.
*
* @default false
*/
readonly 'lint-fix'?: boolean;
/**
* Options to pass to linting program. It must be a string that is JSON.parse(able).
*/
readonly 'lint-options'?: string;
/**
* Linter errors threshold in absolute value.
*
* @default 0
*/
readonly 'lint-errors-threshold': number;
/**
* Linter warnings threshold in absolute value.
*
* @default 0
*/
readonly 'lint-warnings-threshold': number;
/**
* File path to write test results. When set to an array, the array size must match the reporter option array.
*
* @default stdout
*/
readonly output?: string | string[];
/**
* File paths to load tests from.
*
* @default ['test']
*/
readonly path?: string[];
/**
* File pattern to use for locating tests (must include file extensions).
*/
readonly pattern?: RegExp;
/**
* Reporter type. One of: 'console', 'html', 'json', 'tap', 'lcov', 'clover', 'junit'.
*
* @default 'console'
*/
readonly reporter?: string | string[];
/**
* Random number seed when shuffle is enabled.
*/
readonly seed?: string;
/**
* Shuffle script execution order.
*
* @default false
*/
readonly shuffle: boolean;
/**
* Silence skipped tests.
*
* @default false
*/
readonly 'silent-skips'?: boolean;
/**
* Enable support for sourcemaps.
*
* @default false
*/
readonly sourcemaps?: boolean;
/**
* Code coverage threshold percentage.
*/
readonly threshold?: number;
/**
* Timeout for each test in milliseconds.
*
* @default 2000
*/
readonly timeout?: number;
/**
* Transformers for non-js file types.
*/
readonly transform?: Transformer[];
/**
* Test types definitions.
*
* @default false
*/
readonly types?: boolean;
/**
* Location of types definitions test file.
*/
readonly 'types-test'?: string;
/**
* Sets output verbosity (0: none, 1: normal, 2: verbose).
*
* @default 1
*/
readonly progress?: number;
}
interface Transformer {
readonly ext: string;
transform(content: string, filename: string): string;
}
interface Script {
after: Setup;
afterEach: Setup;
before: Setup;
beforeEach: Setup;
describe: Experiment;
experiment: Experiment;
suite: Experiment;
it: Test;
test: Test;
}
interface Setup {
(action: Action): void;
(options: TestOptions, action: Action): void;
}
interface Experiment {
(title: string, content: () => void): void;
(title: string, options: Omit<TestOptions, 'plan'>, content: () => void): void;
only(title: string, content: () => void): void;
only(title: string, options: Omit<TestOptions, 'plan'>, content: () => void): void;
skip(title: string, content: () => void): void;
skip(title: string, options: Omit<TestOptions, 'plan'>, content: () => void): void;
}
interface Test {
(title: string, test: Action): void;
(title: string, options: TestOptions, test: Action): void;
only(title: string, test: Action): void;
only(title: string, options: TestOptions, test: Action): void;
skip(title: string, test: Action): void;
skip(title: string, options: TestOptions, test: Action): void;
}
interface Action {
<T>(flags: Flags): Promise<T> | void;
(flags: Flags): void;
}
interface TestOptions {
/**
* Sets the entire experiment content to be skipped during execution.
*
* @default false
*/
readonly skip?: boolean;
/**
* Sets all other experiments to skip.
*
* @default false
*/
readonly only?: boolean;
/**
* Overrides the default test timeout for tests and other timed operations in milliseconds.
*
* @default 2000
*/
readonly timeout?: number;
/**
* The expected number of assertions the test must execute.
*/
readonly plan?: number;
/**
* Set the test to be retried a few times when it fails. Can be set to true to used the default number of retries or an exact number of maximum retries.
*
* @default false
*/
readonly retry?: number | boolean;
}
interface Flags {
/**
* An object that is passed to `before` and `after` functions in addition to tests themselves.
*/
readonly context: Record<string, any>;
/**
* Sets a requirement that a function must be called a certain number of times.
*
* @param func - the function to be called.
* @param count - the number of required invocations.
*
* @returns a wrapped function.
*/
mustCall<T extends (...args: any[]) => any>(func: T, count: number): T;
/**
* Adds notes to the test log.
*
* @param note - a string to be included in the console reporter at the end of the output.
*/
note(note: string): void;
/**
* A property that can be assigned a cleanup function registered at runtime to be executed after the test completes.
*/
onCleanup?: Action;
/**
* A property that can be assigned an override for global exception handling.
*/
onUncaughtException?: ErrorHandler;
/**
* A property that can be assigned an override function for global rejection handling.
*/
onUnhandledRejection?: ErrorHandler;
}
interface ErrorHandler {
(err: Error): void;
}
}
export const types: types.Types;
declare namespace types {
interface Types {
expect: Expect;
}
interface Expect {
/**
* Assert the type of the value expected
*
* @param value - the value being asserted.
*/
type<T>(value: T): void;
/**
* Assert the value to throw an argument error
*
* @param value - the value being asserted.
*/
error<T = any>(value: T): void;
}
} | the_stack |
import chroma from 'chroma-js'
import { v4 as UUID } from 'uuid'
import { PackageType } from '../core/shared/project-file-types'
import { AnyJson, JsonMap } from '../missing-types/json'
import { JsonSchema, PropSchema } from '../missing-types/json-schema'
import { ControlStyles } from '../components/inspector/common/control-status'
import { NormalisedFrame } from 'utopia-api'
import { fastForEach, NO_OP } from '../core/shared/utils'
import {
CanvasRectangle,
RectangleInner,
CoordinateMarker,
Rectangle,
LocalRectangle,
roundTo,
roundToNearestHalf,
roundPointToNearestHalf,
roundPointTo,
normalizeDegrees,
degreesToRadians,
radiansToDegrees,
scalePoint,
scaleVector,
rotateVector,
zeroPoint,
zeroSize,
zeroRectangle,
zeroRectangleAtPoint,
shiftToOrigin,
rectOrigin,
rectSize,
setRectSize,
rectContainsPoint,
circleContainsPoint,
ellipseContainsPoint,
negate,
magnitude,
product,
distance,
vectorFromPoints,
interpolateAt,
offsetPoint,
normalizeRect,
getLocalRectangleInNewParentContext,
getLocalPointInNewParentContext,
getCanvasRectangleWithCanvasOffset,
getCanvasPointWithCanvasOffset,
getCanvasVectorFromWindowVector,
asLocal,
asGlobal,
rectangleDifference,
rectangleIntersection,
pointDifference,
vectorDifference,
offsetRect,
combineRectangles,
stretchRect,
scaleSize,
scaleRect,
getRectCenter,
setRectLeftX,
setRectCenterX,
setRectRightX,
setRectTopY,
setRectCenterY,
setRectBottomY,
setRectWidth,
setRectHeight,
rectFromPointVector,
rectSizeToVector,
transformFrameUsingBoundingBox,
closestPointOnLine,
lineIntersection,
percentToNumber,
numberToPercent,
rectangleToPoints,
boundingRectangle,
boundingRectangleArray,
angleOfPointFromVertical,
pointsEqual,
rectanglesEqual,
proportion,
rect,
point,
sizesEqual,
forceNotNaN,
nanToZero,
safeParseInt,
} from '../core/shared/math-utils'
import {
optionalMap,
optionalFlatMap,
maybeToArray,
arrayToMaybe,
defaultIfNull,
defaultIfNullLazy,
forceNotNull,
} from '../core/shared/optional-utils'
import {
propOrNull,
objectMap,
mapValues,
get,
propOr,
copyObjectWithoutFunctions,
getAllObjectPaths,
modifyKey,
mergeObjects,
objectValues,
isEmptyObject,
objectFlattenKeys,
} from '../core/shared/object-utils'
import {
stripNulls,
filterDuplicates,
flatMapArray,
pluck,
traverseArray,
arrayToObject,
mapArrayToDictionary,
uniq,
dropLast,
last,
removeIndexFromArray,
flattenArray,
addToMapOfArraysUnique,
addUniquely,
addAllUniquely,
findLastIndex,
drop,
insert,
} from '../core/shared/array-utils'
import {
shallowEqual,
oneLevelNestedEquals,
keepReferenceIfShallowEqual,
} from '../core/shared/equality-utils'
import {
SafeFunction,
SafeFunctionCurriedErrorHandler,
processErrorWithSourceMap,
} from '../core/shared/code-exec-utils'
import { memoize } from '../core/shared/memoize'
import { ValueType, OptionsType, OptionTypeBase } from 'react-select'
import { emptySet } from '../core/shared/set-utils'
import * as ObjectPath from 'object-path'
// TODO Remove re-exported functions
export type FilteredFields<Base, T> = {
[K in keyof Base]: Base[K] extends T ? K : never
}[keyof Base]
export type Front = {
type: 'front'
}
export type Back = {
type: 'back'
}
export type Absolute = {
type: 'absolute'
index: number
}
export type After = {
type: 'after'
index: number
}
export type Before = {
type: 'before'
index: number
}
export type IndexPosition = Front | Back | Absolute | After | Before
export type Axis = 'x' | 'y'
export type DiagonalAxis = 'TopLeftToBottomRight' | 'BottomLeftToTopRight'
export interface HSLA {
h: number
s: number
l: number
a: number
}
export type Color = { red: number; green: number; blue: number; alpha: number }
export type ColorProperty = {
enabled: boolean
color: Color
}
export function normalisedFrameToCanvasFrame(frame: NormalisedFrame): CanvasRectangle {
const { left: x, top: y, width, height } = frame
return { x, y, width, height } as CanvasRectangle
}
export type ObtainChildren<T> = (elem: T, parents: Array<T>) => Array<T>
export type GetFrame<T> = (elem: T, parents: Array<T>) => RectangleInner
export type HitTester<T> = {
elem: T
parents: Array<T>
frame: RectangleInner
}
export type Clock = {
// returns the current timestamp
now: () => number
}
export const getChainSegmentEdge = (controlStyles: ControlStyles) => ({
top: `0 1px ${controlStyles.borderColor} inset`,
bottom: `0 -1px ${controlStyles.borderColor} inset`,
left: `1px 0 ${controlStyles.borderColor} inset`,
right: `-1px 0 ${controlStyles.borderColor} inset`,
})
export function generateUUID(): string {
return UUID().replace(/-/g, '_')
}
function isColor(color: any): color is Color {
if (color == null) {
return false
} else {
return (
(color as Color).red !== undefined &&
(color as Color).blue !== undefined &&
(color as Color).green !== undefined &&
(color as Color).alpha !== undefined
)
}
}
function safeColor(color: Color): Color {
return {
red: propOrNull('red', color) == null ? 0 : color.red,
green: propOrNull('green', color) == null ? 0 : color.green,
blue: propOrNull('blue', color) == null ? 0 : color.blue,
alpha: propOrNull('alpha', color) == null ? 1 : color.alpha,
}
}
function colorToRGBA(unsafe: Color): string {
const color = safeColor(unsafe)
return (
'rgba(' +
Math.round(color.red) +
',' +
Math.round(color.green) +
',' +
Math.round(color.blue) +
',' +
color.alpha +
')'
)
}
function colorToHex(unsafe: Color): string {
const color = safeColor(unsafe)
return chroma(color.red, color.green, color.blue).hex().toUpperCase()
}
function colorToRGBAWithoutOpacity(unsafe: Color): string {
const color = safeColor(unsafe)
return (
'rgba(' +
Math.round(color.red) +
',' +
Math.round(color.green) +
',' +
Math.round(color.blue) +
',1)'
)
}
function colorToReactNativeColor(color: Color | null, defaultToBlack: boolean = false): string {
if (color == null || (color.red == null && color.blue == null && color.green == null)) {
return defaultToBlack ? 'rgba(0,0,0,1)' : 'transparent'
}
return colorToRGBA(color)
}
function nullIfTransparent(color: Color | null): Color | null {
if (color == null) {
return null
}
if (color.alpha == 0) {
return null
}
return color
}
const TRANSPARENT_IMAGE_SRC =
'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='
function isJsonStringValid(jsonString: string): boolean {
try {
JSON.parse(jsonString)
} catch (e) {
return false
}
return true
}
function jsonParseOrNull(jsonString: string): any | null {
try {
return JSON.parse(jsonString)
} catch (e) {
return null
}
}
function safeCompare<T>(left: T | null | undefined, right: T, fn: (l: T, r: T) => T): T {
if (left === null || left === undefined) {
return right
} else {
return fn(left, right)
}
}
function removeFirst<T>(array: Array<T>): Array<T> {
return drop(1, array)
}
function resolveRef($ref: string, completeSchema: JsonSchema): JsonSchema {
if ($ref.startsWith('main#/definitions/')) {
// this ONLY works with top level definitions
// TODO make it work with deep refs
const definitionName = $ref.slice(18)
return completeSchema.definitions![definitionName]
} else {
throw new Error(
'using a $ref which does not point to main#/definitions/ is not yet allowed: ' + $ref,
)
}
}
function traverseJsonSchema(
schemaPath: Array<string | number>,
schema: JsonSchema,
completeSchema?: JsonSchema,
): JsonSchema | null {
const schemaToUse = completeSchema ?? schema
if (schemaPath.length === 0) {
return schema
}
if (schema.type === 'array' && schema.items != null) {
return traverseJsonSchema(removeFirst(schemaPath), schema.items, schemaToUse)
}
if (schema.properties != null) {
const prop = schema.properties[schemaPath[0]]
if (prop == null) {
return null
} else {
return traverseJsonSchema(removeFirst(schemaPath), prop, schemaToUse)
}
}
if (schema.$ref != null) {
return traverseJsonSchema(schemaPath, resolveRef(schema.$ref, schemaToUse), schemaToUse)
}
return null
}
function extractDefaultForType(schema: JsonSchema, type: PackageType): AnyJson | undefined {
if (type === 'svg' && schema.defaultSpecialForSvg != null) {
return schema.defaultSpecialForSvg
} else {
return schema.default
}
}
function compileDefaultForSchema(
schema: JsonSchema,
type: PackageType,
debugKey: string | number,
preferLeafDefault: boolean,
completeSchema: JsonSchema,
): AnyJson {
const defaultForNode = extractDefaultForType(schema, type)
if (!preferLeafDefault && defaultForNode !== undefined) {
return defaultForNode
}
if (schema.type === 'array' && schema.items != null) {
/**
* The requested property path points to an array,
* which in our implementation is an object with numbers as keys.
* So an array of one element is of the shape { 0: ... }
*/
return {
0: compileDefaultForSchema(schema.items, type, debugKey, preferLeafDefault, completeSchema),
}
}
if (schema.allOf != null) {
let result: JsonMap = {}
fastForEach(schema.allOf, (elementOfAll) => {
const elementSchema = compileDefaultForSchema(
elementOfAll,
type,
debugKey,
preferLeafDefault,
completeSchema,
)
if (
typeof elementSchema === 'object' &&
elementSchema != null &&
!Array.isArray(elementSchema)
) {
result = {
...result,
...elementSchema,
}
} else {
throw new Error(`Impossible to merge schema element ${elementSchema} into object.`)
}
})
return result
}
if (schema.properties != null) {
let result: { [property: string]: AnyJson } = {}
const properties = schema.properties
fastForEach(Object.keys(properties), (key) => {
const property = properties[key]
result[key] = compileDefaultForSchema(
property,
type,
`${debugKey}.${key}`,
preferLeafDefault,
completeSchema,
)
})
return result
}
if (schema.$ref != null) {
return compileDefaultForSchema(
resolveRef(schema.$ref, completeSchema),
type,
debugKey,
preferLeafDefault,
completeSchema,
)
}
if (preferLeafDefault && defaultForNode !== undefined) {
return defaultForNode
}
// oh no, we don't have a default for this!
throw new Error(`Schema Error: couldn't find default value for type '${debugKey}'`)
}
function compileDefaultForPropSchema(propSchema: PropSchema): any {
return objectMap((schema, key) => {
try {
return compileDefaultForSchema(schema, 'base', key, false, schema)
} catch (e) {
// we couldn't find a default
return null
}
}, propSchema)
}
export function eventTargetIsTextArea(event: KeyboardEvent): boolean {
return /textarea/i.test((event.target as any).tagName)
}
export function eventTargetIsTextAreaOrInput(event: KeyboardEvent) {
return /input|textarea/i.test((event.target as any).tagName)
}
function getBaseAndIndex(name: string, insertSpace: boolean): { base: string; index: number } {
let tokens = name.split(' ')
let lastToken: string = ''
let baseName = name
if (insertSpace) {
lastToken = tokens[tokens.length - 1]
baseName = dropLast(tokens).join(' ')
} else {
const regexMatch = name.match(/\d+$/)
if (regexMatch != null) {
lastToken = regexMatch[0]
baseName = name.slice(0, regexMatch.index)
tokens = [baseName, lastToken]
}
}
const indexToken = parseInt(lastToken)
if (tokens.length == 0 || isNaN(indexToken)) {
return {
base: name,
index: 1,
}
} else {
return {
base: baseName,
index: indexToken,
}
}
}
export function nextName(
candidate: string,
namesTaken: Array<string>,
insertSpace: boolean = true,
): string {
const { base } = getBaseAndIndex(candidate, insertSpace)
const maxIndex = namesTaken
.filter((name) => {
return name.indexOf(base) >= 0
})
.reduce((acc, name) => {
const { index } = getBaseAndIndex(name, insertSpace)
return index > acc ? index : acc
}, 0)
return `${base}${insertSpace ? ' ' : ''}${maxIndex + 1}`
}
// Treats "front" as if everything in the array was in a stack from back to front.
function indexToInsertAt<T>(array: Array<T>, indexPosition: IndexPosition): number {
switch (indexPosition.type) {
case 'front':
return array.length
case 'back':
return 0
case 'absolute':
return indexPosition.index
case 'after':
return Math.min(indexPosition.index + 1, array.length)
case 'before':
return Math.max(indexPosition.index, 0)
}
}
function addToArrayWithFill<T>(
element: T,
array: Array<T>,
atPosition: IndexPosition,
fillValue: () => T,
): Array<T> {
const index = indexToInsertAt(array, atPosition)
let midResult: Array<T> = [...array]
for (let fillIndex = array.length; fillIndex < index; fillIndex++) {
midResult.push(fillValue())
}
return insert(index, element, midResult)
}
function assert(errorMessage: string, predicate: boolean | (() => boolean)): void {
if (typeof predicate === 'function' && predicate()) {
return
}
if (typeof predicate === 'boolean' && predicate) {
return
}
throw new Error(`Assert failed: ${errorMessage}`)
}
export interface Annotations {
_signature: string
_description: string
_properties: { [key: string]: any & Annotations }
}
function withDoc<T>(
value: T,
signature: string,
doc: string,
properties: { [key: string]: any & Annotations } = {},
): T & Annotations {
var annotated: any = value
annotated._signature = signature
annotated._description = doc
annotated._properties = properties
return annotated
}
function shallowClone(value: any): any {
switch (typeof value) {
case 'object':
if (Array.isArray(value)) {
return [...value]
} else {
return { ...value }
}
default:
return value
}
}
function proxyValue(
valueToProxy: any,
recordAssignment: (p: Array<string>, value: any) => any,
): any {
function wrapInProxy(toWrap: any, objPath: Array<string>): any {
if (typeof toWrap == 'object' && toWrap != null) {
let withWrappedChildren: any
switch (typeof toWrap) {
case 'object':
if (Array.isArray(toWrap)) {
withWrappedChildren = toWrap.map((element: any, index: number) =>
wrapInProxy(element, objPath.concat([`${index}`])),
)
} else {
withWrappedChildren = mapValues(
(element: any, key: string) => wrapInProxy(element, objPath.concat([key])),
toWrap,
)
}
break
default:
withWrappedChildren = toWrap
}
return new Proxy(withWrappedChildren, {
set: function (target: any, property: any, value: any, receiver: any): boolean {
if (typeof value === 'symbol') {
target[property] = value
} else {
const innerPath = objPath.concat([property])
const innerValue = wrapInProxy(value, innerPath)
target[property] = innerValue
recordAssignment(innerPath, value)
}
return true
},
})
} else {
return toWrap
}
}
return wrapInProxy(valueToProxy, [])
}
const createSimpleClock = function (): Clock {
return {
now: () => {
return Date.now()
},
}
}
function getRectPointsAlongAxes<C extends CoordinateMarker>(
rectangle: Rectangle<C>,
): { horizontalPoints: Array<number>; verticalPoints: Array<number> } {
return {
horizontalPoints: [
rectangle.x,
rectangle.x + rectangle.width / 2,
rectangle.x + rectangle.width,
],
verticalPoints: [
rectangle.y,
rectangle.y + rectangle.height / 2,
rectangle.y + rectangle.height,
],
}
}
function stepInArray<T>(
eq: (first: T, second: T) => boolean,
step: number,
array: Array<T>,
stepFrom: T,
): T | null {
let workingIndex = 0
let foundIndex: number | null = null
for (const element of array) {
// Check if this is the element we're looking for.
if (eq(element, stepFrom)) {
foundIndex = workingIndex
// Might as well bail out early.
break
}
workingIndex++
}
if (foundIndex === null) {
return null
} else {
let index: number = foundIndex + step
function tryNextStep(): void {
if (index < 0 || index >= array.length) {
index = step >= 0 ? index - array.length : index + array.length
tryNextStep()
}
}
tryNextStep()
return forceNotNull(`No element at index ${index}`, array[index])
}
}
function increaseScale(scale: number): number {
return scale * 2
}
function decreaseScale(scale: number): number {
return scale / 2
}
function createThrottler(
timeout: number,
): (functionToCall: (...args: any[]) => void, ...args: any[]) => void {
let canCallFunction = true
return (functionToCall: (...args: any[]) => void, ...args: any[]) => {
if (canCallFunction) {
// eslint-disable-next-line prefer-spread
functionToCall.apply(null, args)
canCallFunction = false
setTimeout(() => {
canCallFunction = true
}, timeout)
}
}
}
function path<T>(
objPath: Array<string | number>,
obj: Record<string | number, any> | undefined | null,
): T | undefined {
if (obj == null) {
return undefined
} else {
return ObjectPath.get(obj, objPath)
}
}
// eslint-disable-next-line @typescript-eslint/ban-types
function pathOr<T, U = T>(defaultValue: T, objPath: Array<string | number>, obj: {}): T | U {
return ObjectPath.get(obj, objPath, defaultValue)
}
function immutableUpdateField(valueToUpdate: any, field: string | number, valueToSet: any): any {
const fieldParsedAsNumber: number = typeof field === 'number' ? field : parseInt(field)
if (isNaN(fieldParsedAsNumber)) {
// Object field update.
return {
...defaultIfNull({}, valueToUpdate),
[field]: valueToSet,
}
} else {
let result: Array<any> = valueToUpdate == null ? [] : [...valueToUpdate]
result[fieldParsedAsNumber] = valueToSet
return result
}
}
function immutableUpdate(
valueToUpdate: any,
objPath: Array<string | number>,
valueToSet: any,
): any {
switch (objPath.length) {
case 0:
// No path, so we're just replacing the whole value at this point.
return valueToSet
case 1:
// Last part of the path, setting the `valueToSet` where the final part specifies.
return immutableUpdateField(valueToUpdate, objPath[0], valueToSet)
default:
// 2 or more path elements, need to step down path part to recursively invoke this on the remainder.
const [first, ...remainder] = objPath
const fieldParsedAsNumber: number = typeof first === 'number' ? first : parseInt(first)
const isArrayUpdate = typeof first === 'number' || !isNaN(fieldParsedAsNumber)
if (isArrayUpdate) {
// Arrays.
const defaultedArray: Array<any> = defaultIfNull([], valueToUpdate)
let result: Array<any> = [...defaultedArray]
result[fieldParsedAsNumber] = immutableUpdate(
defaultedArray[fieldParsedAsNumber],
remainder,
valueToSet,
)
return result
} else {
// Objects.
const defaultedObject: { [key: string]: any } = defaultIfNull({}, valueToUpdate)
return {
...defaultedObject,
[first]: immutableUpdate(defaultedObject[first], remainder, valueToSet),
}
}
}
}
function isLocalRectangle(rectangle: any): rectangle is LocalRectangle {
if (typeof rectangle === 'object') {
return (
rectangle.x != null &&
typeof rectangle.x === 'number' &&
rectangle.y != null &&
typeof rectangle.y === 'number' &&
rectangle.width != null &&
typeof rectangle.width === 'number' &&
rectangle.height != null &&
typeof rectangle.height === 'number'
)
} else {
return false
}
}
function update<T>(index: number, newValue: T, array: Array<T>): Array<T> {
let result = [...array]
result.splice(index, 1, newValue)
return result
}
function defer<T>(): Promise<T> & {
resolve: (value?: T) => void
reject: (reason?: any) => void
} {
var res, rej
var promise = new Promise<T>((resolve, reject) => {
res = resolve
rej = reject
})
Object.defineProperty(promise, 'resolve', { value: res })
Object.defineProperty(promise, 'reject', { value: rej })
return promise as any
}
function timeLimitPromise<T>(promise: Promise<T>, limitms: number, message: string): Promise<T> {
const timeoutPromise: Promise<any> = new Promise((resolve, reject) => {
const timeoutID = setTimeout(() => {
clearTimeout(timeoutID)
reject(message)
}, limitms)
})
return Promise.race([promise, timeoutPromise])
}
/**
* A type guard for React Select's onChange values, which can either be a value
* or an array of values.
*/
export function isOptionType<T extends OptionTypeBase>(value: ValueType<T>): value is T {
return value != null && !Array.isArray(value)
}
/**
* A type guard for React Select's onChange values, which can either be a value
* or an array of values.
*/
export function isOptionsType<T extends OptionTypeBase>(
value: ValueType<T>,
): value is OptionsType<T> {
return Array.isArray(value)
}
export default {
generateUUID: generateUUID,
assert: assert,
roundTo: roundTo,
roundToNearestHalf: roundToNearestHalf,
roundPointToNearestHalf: roundPointToNearestHalf,
roundPointTo: roundPointTo,
normalizeDegrees: normalizeDegrees,
degreesToRadians: degreesToRadians,
radiansToDegrees: radiansToDegrees,
scalePoint: scalePoint,
scaleVector: scaleVector,
rotateVector: rotateVector,
zeroPoint: zeroPoint,
zeroSize: zeroSize,
zeroRectangle: zeroRectangle,
zeroRectangleAtPoint: zeroRectangleAtPoint,
shiftToOrigin: shiftToOrigin,
rectOrigin: rectOrigin,
rectSize: rectSize,
setRectSize: setRectSize,
rectContainsPoint: rectContainsPoint,
circleContainsPoint: circleContainsPoint,
ellipseContainsPoint: ellipseContainsPoint,
negate: negate,
magnitude: magnitude,
product: product,
distance: distance,
vectorFromPoints: vectorFromPoints,
interpolateAt: interpolateAt,
offsetPoint: offsetPoint,
addVectors: offsetPoint,
normalizeRect: normalizeRect,
getLocalRectangleInNewParentContext: getLocalRectangleInNewParentContext,
getLocalPointInNewParentContext: getLocalPointInNewParentContext,
getCanvasRectangleWithCanvasOffset: getCanvasRectangleWithCanvasOffset,
getCanvasPointWithCanvasOffset: getCanvasPointWithCanvasOffset,
getCanvasVectorFromWindowVector: getCanvasVectorFromWindowVector,
asLocal: asLocal,
asGlobal: asGlobal,
rectangleDifference: rectangleDifference,
rectangleIntersection: rectangleIntersection,
pointDifference: pointDifference,
vectorDifference: vectorDifference,
offsetRect: offsetRect,
combineRectangles: combineRectangles,
stretchRect: stretchRect,
scaleSize: scaleSize,
scaleRect: scaleRect,
getRectCenter: getRectCenter,
setRectLeftX: setRectLeftX,
setRectCenterX: setRectCenterX,
setRectRightX: setRectRightX,
setRectTopY: setRectTopY,
setRectCenterY: setRectCenterY,
setRectBottomY: setRectBottomY,
setRectWidth: setRectWidth,
setRectHeight: setRectHeight,
rectFromPointVector: rectFromPointVector,
rectSizeToVector: rectSizeToVector,
transformFrameUsingBoundingBox: transformFrameUsingBoundingBox,
closestPointOnLine: closestPointOnLine,
lineIntersection: lineIntersection,
isColor: isColor,
safeColor: safeColor,
colorToRGBA: colorToRGBA,
colorToHex: colorToHex,
colorToRGBAWithoutOpacity: colorToRGBAWithoutOpacity,
colorToReactNativeColor: colorToReactNativeColor,
nullIfTransparent: nullIfTransparent,
SafeFunction: SafeFunction,
SafeFunctionCurriedErrorHandler: SafeFunctionCurriedErrorHandler,
TRANSPARENT_IMAGE_SRC: TRANSPARENT_IMAGE_SRC,
get: get,
isJsonStringValid: isJsonStringValid,
safeCompare: safeCompare,
optionalMap: optionalMap,
optionalFlatMap: optionalFlatMap,
stripNulls: stripNulls,
filterDuplicates: filterDuplicates,
propOr: propOr,
propOrNull: propOrNull,
objectMap: objectMap,
removeFirst: removeFirst,
resolveRef: resolveRef,
traverseJsonSchema: traverseJsonSchema,
compileDefaultForSchema: compileDefaultForSchema,
compileDefaultForPropSchema: compileDefaultForPropSchema,
eventTargetIsTextAreaOrInput: eventTargetIsTextAreaOrInput,
copyObjectWithoutFunctions: copyObjectWithoutFunctions,
forceNotNull: forceNotNull,
eventTargetIsTextArea: eventTargetIsTextArea,
nextName: nextName,
indexToInsertAt: indexToInsertAt,
addToArrayWithFill: addToArrayWithFill,
percentToNumber: percentToNumber,
numberToPercent: numberToPercent,
getAllObjectPaths: getAllObjectPaths,
mapValues: mapValues,
withDoc: withDoc,
shallowClone: shallowClone,
proxyValue: proxyValue,
createSimpleClock: createSimpleClock,
memoize: memoize,
shallowEqual: shallowEqual,
oneLevelNestedEquals: oneLevelNestedEquals,
keepReferenceIfShallowEqual: keepReferenceIfShallowEqual,
maybeToArray: maybeToArray,
arrayToMaybe: arrayToMaybe,
getRectPointsAlongAxes: getRectPointsAlongAxes,
rectangleToPoints: rectangleToPoints,
flatMapArray: flatMapArray,
boundingRectangle: boundingRectangle,
boundingRectangleArray: boundingRectangleArray,
pluck: pluck,
traverseArray: traverseArray,
NO_OP: NO_OP,
stepInArray: stepInArray,
arrayToObject: arrayToObject,
angleOfPointFromVertical: angleOfPointFromVertical,
pointsEqual: pointsEqual,
rectanglesEqual: rectanglesEqual,
proportion: proportion,
increaseScale: increaseScale,
decreaseScale: decreaseScale,
createThrottler: createThrottler,
mapArrayToDictionary: mapArrayToDictionary,
modifyKey: modifyKey,
uniq: uniq,
fastForEach: fastForEach,
forceNotNaN: forceNotNaN,
nanToZero: nanToZero,
safeParseInt: safeParseInt,
defaultIfNull: defaultIfNull,
defaultIfNullLazy: defaultIfNullLazy,
emptySet: emptySet,
path: path,
pathOr: pathOr,
mergeObjects: mergeObjects,
objectValues: objectValues,
rect: rect,
point: point,
dropLast: dropLast,
last: last,
immutableUpdate: immutableUpdate,
isEmptyObject: isEmptyObject,
sizesEqual: sizesEqual,
objectFlattenKeys: objectFlattenKeys,
jsonParseOrNull: jsonParseOrNull,
isLocalRectangle: isLocalRectangle,
removeIndexFromArray: removeIndexFromArray,
flattenArray: flattenArray,
update: update,
addToMapOfArraysUnique: addToMapOfArraysUnique,
addUniquely: addUniquely,
addAllUniquely: addAllUniquely,
defer: defer,
processErrorWithSourceMap: processErrorWithSourceMap,
findLastIndex: findLastIndex,
timeLimitPromise: timeLimitPromise,
} | the_stack |
import * as assert from 'assert';
import isolate from '@cycle/isolate';
import xs, {Stream, MemoryStream} from 'xstream';
import fromDiagram from 'xstream/extra/fromDiagram';
import delay from 'xstream/extra/delay';
import concat from 'xstream/extra/concat';
import {setup} from '@cycle/run';
import {
h,
svg,
div,
span,
h2,
h3,
h4,
button,
makeDOMDriver,
DOMSource,
MainDOMSource,
VNode,
thunk,
} from '../../src/index';
function createRenderTarget(id: string | null = null) {
const element = document.createElement('div');
element.className = 'cycletest';
if (id) {
element.id = id;
}
document.body.appendChild(element);
return element;
}
describe('isolateSource', function() {
it('should return source also with isolateSource and isolateSink', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
return {
DOM: xs.of(h('h3.top-most')),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
const dispose = run();
const isolatedDOMSource = sources.DOM.isolateSource(
sources.DOM,
'top-most'
);
// Make assertions
assert.strictEqual(typeof isolatedDOMSource.isolateSource, 'function');
assert.strictEqual(typeof isolatedDOMSource.isolateSink, 'function');
dispose();
done();
});
});
describe('isolateSink', function() {
it('should add an isolate field to the vtree sink', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const vtree$ = xs.of(h3('.top-most'));
return {
DOM: _sources.DOM.isolateSink(vtree$, 'foo'),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
// Make assertions
sinks.DOM.take(1).addListener({
next: (vtree: VNode) => {
assert.strictEqual(vtree.sel, 'h3.top-most');
assert.strictEqual(Array.isArray((vtree.data as any).isolate), true);
assert.deepStrictEqual((vtree.data as any).isolate, [
{type: 'total', scope: 'foo'},
]);
setTimeout(() => {
dispose();
done();
});
},
});
dispose = run();
});
it('should not redundantly repeat the scope className', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const vtree1$ = xs.of(span('.tab1', 'Hi'));
const vtree2$ = xs.of(span('.tab2', 'Hello'));
const first$ = _sources.DOM.isolateSink(vtree1$, '1');
const second$ = _sources.DOM.isolateSink(vtree2$, '2');
const switched$ = concat(
xs.of(1).compose(delay(50)),
xs.of(2).compose(delay(50)),
xs.of(1).compose(delay(50)),
xs.of(2).compose(delay(50)),
xs.of(1).compose(delay(50)),
xs.of(2).compose(delay(50))
)
.map(i => (i === 1 ? first$ : second$))
.flatten();
return {
DOM: switched$,
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
// Make assertions
sinks.DOM.drop(2)
.take(1)
.addListener({
next: (vtree: VNode) => {
assert.strictEqual(vtree.sel, 'span.tab1');
assert.strictEqual(Array.isArray((vtree.data as any).isolate), true);
assert.strictEqual((vtree.data as any).isolate.length, 1);
assert.deepStrictEqual((vtree.data as any).isolate, [
{type: 'total', scope: '1'},
]);
dispose();
done();
},
});
dispose = run();
});
});
describe('isolation', function() {
it('should prevent parent from DOM.selecting() inside the isolation', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const child$ = _sources.DOM.isolateSink(
xs.of(div('.foo', [h4('.bar', 'Wrong')])),
'ISOLATION'
);
const vdom$ = xs
.combine(xs.of(null), child$)
.map(([_, child]) => h3('.top-most', [child, h2('.bar', 'Correct')]));
return {
DOM: vdom$,
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.select('.bar')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 1);
const correctElement = elements[0];
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'H2');
assert.strictEqual(correctElement.textContent, 'Correct');
done();
},
});
run();
});
it('should not occur with scope ":root"', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const child$ = _sources.DOM.isolateSink(
xs.of(div('.foo', [h4('.bar', 'Not wrong')])),
':root'
);
const vdom$ = xs
.combine(xs.of(null), child$)
.map(([_, child]) => h3('.top-most', [child, h2('.bar', 'Correct')]));
return {
DOM: vdom$,
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.select('.bar')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 2);
const notWrongElement = elements[0];
assert.notStrictEqual(notWrongElement, null);
assert.notStrictEqual(typeof notWrongElement, 'undefined');
assert.strictEqual(notWrongElement.tagName, 'H4');
assert.strictEqual(notWrongElement.textContent, 'Not wrong');
const correctElement = elements[1];
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'H2');
assert.strictEqual(correctElement.textContent, 'Correct');
done();
},
});
run();
});
it('should apply only between siblings when given scope ".foo"', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const foo$ = _sources.DOM.isolateSink(
xs.of(div('.container', [h4('.header', 'Correct')])),
'.foo'
);
const bar$ = _sources.DOM.isolateSink(
xs.of(div('.container', [h3('.header', 'Wrong')])),
'.bar'
);
const vdom$ = xs
.combine(foo$, bar$)
.map(([foo, bar]) =>
div('.top-most', [foo, bar, h2('.header', 'Correct')])
);
return {
DOM: vdom$,
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
// Assert parent has total access to its children
sources.DOM.select('.header')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 3);
assert.strictEqual(elements[0].tagName, 'H4');
assert.strictEqual(elements[0].textContent, 'Correct');
assert.strictEqual(elements[1].tagName, 'H3');
assert.strictEqual(elements[1].textContent, 'Wrong');
assert.strictEqual(elements[2].tagName, 'H2');
assert.strictEqual(elements[2].textContent, 'Correct');
// Assert .foo child has no access to .bar child
sources.DOM.isolateSource(sources.DOM, '.foo')
.select('.header')
.elements()
.take(1)
.addListener({
next: (els: Array<Element>) => {
assert.strictEqual(Array.isArray(els), true);
assert.strictEqual(els.length, 1);
assert.strictEqual(els[0].tagName, 'H4');
assert.strictEqual(els[0].textContent, 'Correct');
done();
},
});
},
});
run();
});
it('should apply only between siblings when given scope "#foo"', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const foo$ = _sources.DOM.isolateSink(
xs.of(div('.container', [h4('.header', 'Correct')])),
'#foo'
);
const bar$ = _sources.DOM.isolateSink(
xs.of(div('.container', [h3('.header', 'Wrong')])),
'#bar'
);
const vdom$ = xs
.combine(foo$, bar$)
.map(([foo, bar]) =>
div('.top-most', [foo, bar, h2('.header', 'Correct')])
);
return {
DOM: vdom$,
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
// Assert parent has total access to its children
sources.DOM.select('.header')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 3);
assert.strictEqual(elements[0].tagName, 'H4');
assert.strictEqual(elements[0].textContent, 'Correct');
assert.strictEqual(elements[1].tagName, 'H3');
assert.strictEqual(elements[1].textContent, 'Wrong');
assert.strictEqual(elements[2].tagName, 'H2');
assert.strictEqual(elements[2].textContent, 'Correct');
// Assert .foo child has no access to .bar child
sources.DOM.isolateSource(sources.DOM, '#foo')
.select('.header')
.elements()
.take(1)
.addListener({
next: (els: Array<Element>) => {
assert.strictEqual(Array.isArray(els), true);
assert.strictEqual(els.length, 1);
assert.strictEqual(els[0].tagName, 'H4');
assert.strictEqual(els[0].textContent, 'Correct');
done();
},
});
},
});
run();
});
it('should work with thunks', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const child$ = _sources.DOM.isolateSink(
xs.of<VNode>(thunk('div.foo', () => div('.foo', [h4('.bar', 'Wrong')]), [])),
'ISOLATION'
);
const vdom$ = xs
.combine(xs.of(null), child$)
.map(([_, child]) => h3('.top-most', [child, h2('.bar', 'Correct')]));
return {
DOM: vdom$,
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.select('.bar')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 1);
const correctElement = elements[0];
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'H2');
assert.strictEqual(correctElement.textContent, 'Correct');
done();
},
});
run();
});
it('should allow using elements() in an isolated main() fn', function(done) {
function main(_sources: {DOM: MainDOMSource}) {
const elem$ = _sources.DOM.select(':root').elements();
const vnode$ = elem$.map(elem =>
h('div.bar', 'left=' + (elem[0] as any).offsetLeft)
);
return {
DOM: vnode$,
};
}
const {sinks, sources, run} = setup(isolate(main), {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.select(':root')
.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const barElem = root.querySelector('.bar') as Element;
assert.notStrictEqual(barElem, null);
assert.notStrictEqual(typeof barElem, 'undefined');
assert.strictEqual(barElem.tagName, 'DIV');
assert.strictEqual(barElem.textContent, 'left=8');
done();
},
});
run();
});
it('should allow parent to DOM.select() in its own isolation island', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const {isolateSource, isolateSink} = _sources.DOM;
const islandElement$ = isolateSource(_sources.DOM, 'island')
.select('.bar')
.elements();
const islandVDom$ = isolateSink(
xs.of(div([h3('.bar', 'Correct')])),
'island'
);
const child$ = isolateSink(
islandVDom$.map(islandVDom =>
div('.foo', [islandVDom, h4('.bar', 'Wrong')])
),
'ISOLATION'
);
const vdom$ = child$.map(child => h3('.top-most', [child]));
return {
DOM: vdom$,
island: islandElement$,
};
}
const drivers = {
DOM: makeDOMDriver(createRenderTarget()),
island(sink: Stream<Array<Element>>) {},
};
const {sinks, sources, run} = setup(app, drivers);
sinks.island
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 1);
const correctElement = elements[0];
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'H3');
assert.strictEqual(correctElement.textContent, 'Correct');
done();
},
});
run();
});
it('should isolate DOM.select between parent and (wrapper) child', function(done) {
function Frame(_sources: {DOM: MainDOMSource; content$: Stream<any>}) {
const click$ = _sources.DOM.select('.foo').events('click');
const vdom$ = _sources.content$.map(content =>
h4('.foo.frame', {style: {backgroundColor: 'lightblue'}}, [content])
);
return {
DOM: vdom$,
click$,
};
}
function Monalisa(_sources: {DOM: MainDOMSource}): any {
const {isolateSource, isolateSink} = _sources.DOM;
const islandDOMSource = isolateSource(_sources.DOM, '.island');
const monalisaClick$ = islandDOMSource.select('.foo').events('click');
const islandDOMSink$ = isolateSink(
xs.of(span('.foo.monalisa', 'Monalisa')),
'.island'
);
const click$ = _sources.DOM.select('.foo').events('click');
const frameDOMSource = isolateSource(_sources.DOM, 'myFrame');
const frame = Frame({DOM: frameDOMSource, content$: islandDOMSink$});
const outerVTree$ = isolateSink(frame.DOM, 'myFrame');
return {
DOM: outerVTree$,
frameClick: frame.click$,
monalisaClick: monalisaClick$,
click: click$,
};
}
const {sources, sinks, run} = setup(Monalisa, {
DOM: makeDOMDriver(createRenderTarget()),
frameClick: () => {},
monalisaClick: () => {},
click: () => {},
});
let dispose: any;
const frameClick$ = sinks.frameClick.map((ev: any) => ({
type: ev.type,
tagName: (ev.target as HTMLElement).tagName,
}));
const _monalisaClick$ = sinks.monalisaClick.map((ev: any) => ({
type: ev.type,
tagName: (ev.target as HTMLElement).tagName,
}));
const grandparentClick$ = sinks.click.map((ev: any) => ({
type: ev.type,
tagName: (ev.target as HTMLElement).tagName,
}));
// Stop the propagtion of the second click
sinks.monalisaClick
.drop(1)
.take(1)
.addListener({
next: (ev: Event) => ev.stopPropagation(),
});
let totalClickHandlersCalled = 0;
let frameClicked = false;
frameClick$.addListener({
next: (event: any) => {
assert.strictEqual(frameClicked, false);
assert.strictEqual(event.type, 'click');
assert.strictEqual(event.tagName, 'H4');
frameClicked = true;
totalClickHandlersCalled++;
},
});
// Monalisa should receive two clicks
let monalisaClicked = 0;
_monalisaClick$.addListener({
next: (event: any) => {
assert.strictEqual(monalisaClicked < 2, true);
assert.strictEqual(event.type, 'click');
assert.strictEqual(event.tagName, 'SPAN');
monalisaClicked++;
totalClickHandlersCalled++;
},
});
// The grandparent should receive sibling isolated events
// from the monalisa even though it is passed into the
// total isolated Frame
let grandparentClicked = false;
grandparentClick$.addListener({
next: (event: any) => {
assert.strictEqual(event.type, 'click');
assert.strictEqual(event.tagName, 'SPAN');
assert.strictEqual(grandparentClicked, false);
grandparentClicked = true;
totalClickHandlersCalled++;
assert.doesNotThrow(() => {
setTimeout(() => {
assert.strictEqual(totalClickHandlersCalled, 4);
dispose();
done();
}, 10);
});
},
});
sources.DOM.select(':root')
.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const frameFoo = root.querySelector('.foo.frame') as HTMLElement;
const monalisaFoo = root.querySelector(
'.foo.monalisa'
) as HTMLElement;
assert.notStrictEqual(frameFoo, null);
assert.notStrictEqual(monalisaFoo, null);
assert.notStrictEqual(typeof frameFoo, 'undefined');
assert.notStrictEqual(typeof monalisaFoo, 'undefined');
assert.strictEqual(frameFoo.tagName, 'H4');
assert.strictEqual(monalisaFoo.tagName, 'SPAN');
assert.doesNotThrow(() => {
setTimeout(() => frameFoo.click(), 0);
setTimeout(() => monalisaFoo.click());
setTimeout(() => monalisaFoo.click());
});
},
});
dispose = run();
});
it('should allow a child component to DOM.select() its own root', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const child$ = _sources.DOM.isolateSink(
xs.of(span('.foo', [h4('.bar', 'Wrong')])),
'ISOLATION'
);
return {
DOM: child$.map(child => h3('.top-most', [child])),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
const {isolateSource} = sources.DOM;
let dispose: any;
isolateSource(sources.DOM, 'ISOLATION')
.select('.foo')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 1);
const correctElement = elements[0];
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'SPAN');
setTimeout(() => {
dispose();
done();
});
},
});
dispose = run();
});
it('should allow DOM.selecting svg elements', function(done) {
function App(_sources: {DOM: MainDOMSource}) {
const triangleElement$ = _sources.DOM.select('.triangle').elements();
const svgTriangle = svg({attrs: {width: 150, height: 150}}, [
svg.polygon({
attrs: {
class: 'triangle',
points: '20 0 20 150 150 20',
},
}),
]);
return {
DOM: xs.of(svgTriangle),
triangleElement: triangleElement$,
};
}
function IsolatedApp(_sources: {DOM: MainDOMSource}) {
const {isolateSource, isolateSink} = _sources.DOM;
const isolatedDOMSource = isolateSource(_sources.DOM, 'ISOLATION');
const app = App({DOM: isolatedDOMSource});
const isolateDOMSink = isolateSink(app.DOM, 'ISOLATION');
return {
DOM: isolateDOMSink,
triangleElement: app.triangleElement,
};
}
const drivers = {
DOM: makeDOMDriver(createRenderTarget()),
triangleElement: (sink: any) => {},
};
const {sinks, sources, run} = setup(IsolatedApp, drivers);
// Make assertions
sinks.triangleElement
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(elements.length, 1);
const triangleElement = elements[0];
assert.notStrictEqual(triangleElement, null);
assert.notStrictEqual(typeof triangleElement, 'undefined');
assert.strictEqual(triangleElement.tagName, 'polygon');
done();
},
});
run();
});
it('should allow DOM.select()ing its own root without classname or id', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const child$ = _sources.DOM.isolateSink(
xs.of(span([h4('.bar', 'Wrong')])),
'ISOLATION'
);
return {
DOM: child$.map(child => h3('.top-most', [child])),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
const {isolateSource} = sources.DOM;
isolateSource(sources.DOM, 'ISOLATION')
.select('span')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 1);
const correctElement = elements[0];
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'SPAN');
done();
},
});
run();
});
it('should allow DOM.select()ing all elements with `*`', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
const child$ = _sources.DOM.isolateSink(
xs.of(span([div([h4('.foo', 'hello'), h4('.bar', 'world')])])),
'ISOLATION'
);
return {
DOM: child$.map(child => h3('.top-most', [child])),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
const {isolateSource} = sources.DOM;
isolateSource(sources.DOM, 'ISOLATION')
.select('*')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(Array.isArray(elements), true);
assert.strictEqual(elements.length, 4);
done();
},
});
run();
});
it('should select() isolated element with tag + class', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
return {
DOM: xs.of(
h3('.top-most', [
h2('.bar', 'Wrong'),
div({isolate: [{type: 'total', scope: 'foo'}]}, [
h4('.bar', 'Correct'),
]),
])
),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
const isolatedDOMSource = sources.DOM.isolateSource(sources.DOM, 'foo');
isolatedDOMSource
.select('h4.bar')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(elements.length, 1);
const correctElement = elements[0];
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'H4');
assert.strictEqual(correctElement.textContent, 'Correct');
done();
},
});
run();
});
it('should allow isolatedDOMSource.events() to work without crashing', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
return {
DOM: xs.of(
h3('.top-most', [
div({isolate: [{type: 'total', scope: 'foo'}]}, [
h4('.bar', 'Hello'),
]),
])
),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
const isolatedDOMSource = sources.DOM.isolateSource(sources.DOM, 'foo');
isolatedDOMSource.events('click').addListener({
next: (ev: Event) => {
dispose();
done();
},
});
isolatedDOMSource
.select('div')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(elements.length, 1);
const correctElement = elements[0] as HTMLElement;
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'DIV');
assert.strictEqual(correctElement.textContent, 'Hello');
setTimeout(() => {
correctElement.click();
});
},
});
dispose = run();
});
it('should process bubbling events from inner to outer component', function(done) {
function app(_sources: {DOM: MainDOMSource}) {
return {
DOM: xs.of(
h3('.top-most', [
h2('.bar', 'Wrong'),
div({isolate: [{type: 'sibling', scope: '.foo'}]}, [
h4('.bar', 'Correct'),
]),
])
),
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
const isolatedDOMSource = sources.DOM.isolateSource(sources.DOM, '.foo');
let called = false;
sources.DOM.select('.top-most')
.events('click')
.addListener({
next: (ev: Event) => {
assert.strictEqual(called, true);
dispose();
done();
},
});
isolatedDOMSource
.select('h4.bar')
.events('click')
.addListener({
next: (ev: Event) => {
assert.strictEqual(called, false);
called = true;
},
});
isolatedDOMSource
.select('h4.bar')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(elements.length, 1);
const correctElement = elements[0] as HTMLElement;
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'H4');
assert.strictEqual(correctElement.textContent, 'Correct');
setTimeout(() => {
correctElement.click();
});
},
});
dispose = run();
});
it('should stop bubbling the event if the currentTarget was removed', function(done) {
function main(_sources: {DOM: MainDOMSource}) {
const childExistence$ = _sources.DOM.isolateSource(_sources.DOM, 'foo')
.select('h4.bar')
.events('click')
.map(() => false)
.startWith(true);
return {
DOM: childExistence$.map(exists =>
div([
div('.top-most', {isolate: 'top'}, [
h2('.bar', 'Wrong'),
exists
? div({isolate: [{type: 'total', scope: 'foo'}]}, [
h4('.bar', 'Correct'),
])
: null,
]),
])
),
};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
const topDOMSource = sources.DOM.isolateSource(sources.DOM, 'top');
const fooDOMSource = sources.DOM.isolateSource(sources.DOM, 'foo');
let parentEventHandlerCalled = false;
topDOMSource
.select('.bar')
.events('click')
.addListener({
next: (ev: any) => {
parentEventHandlerCalled = true;
done('this should not be called');
},
});
fooDOMSource
.select('.bar')
.elements()
.drop(1)
.take(1)
.addListener({
next: (elements: Array<Element>) => {
assert.strictEqual(elements.length, 1);
const correctElement = elements[0] as HTMLElement;
assert.notStrictEqual(correctElement, null);
assert.notStrictEqual(typeof correctElement, 'undefined');
assert.strictEqual(correctElement.tagName, 'H4');
assert.strictEqual(correctElement.textContent, 'Correct');
setTimeout(() => {
correctElement.click();
setTimeout(() => {
assert.strictEqual(parentEventHandlerCalled, false);
dispose();
done();
}, 150);
});
},
});
dispose = run();
});
it('should handle a higher-order graph when events() are subscribed', done => {
let errorHappened = false;
let clickDetected = false;
function Child(_sources: {DOM: MainDOMSource}) {
return {
DOM: _sources.DOM.select('.foo')
.events('click')
.debug(() => {
clickDetected = true;
})
.replaceError(() => {
errorHappened = true;
return xs.empty();
})
.mapTo(1)
.startWith(0)
.map(num => div('.container', [h3('.foo', 'Child foo')])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const first = isolate(Child, 'first')(_sources);
const second = isolate(Child, 'second')(_sources);
const oneChild = [first];
const twoChildren = [first, second];
const vnode$ = xs
.periodic(50)
.take(1)
.startWith(-1)
.map(i => (i === -1 ? oneChild : twoChildren))
.map(children =>
xs
.combine(...children.map(child => child.DOM))
.map(childVNodes => div('.parent', childVNodes))
)
.flatten();
return {
DOM: vnode$,
};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.select(':root')
.element()
.drop(2)
.take(1)
.addListener({
next: (root: Element) => {
const parentEl = root.querySelector('.parent') as HTMLElement;
const foo = parentEl.querySelectorAll('.foo')[1] as HTMLElement;
assert.notStrictEqual(parentEl, null);
assert.notStrictEqual(typeof parentEl, 'undefined');
assert.notStrictEqual(foo, null);
assert.notStrictEqual(typeof foo, 'undefined');
assert.strictEqual(parentEl.tagName, 'DIV');
setTimeout(() => {
assert.strictEqual(errorHappened, false);
foo.click();
setTimeout(() => {
assert.strictEqual(clickDetected, true);
dispose();
done();
}, 50);
}, 100);
},
});
dispose = run();
});
it('should handle events when child is removed and re-added', done => {
let clicksCount = 0;
function Child(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.foo')
.events('click')
.addListener({
next: () => {
clicksCount++;
},
});
return {
DOM: xs.of(div('.foo', ['This is foo'])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const child = isolate(Child)(_sources);
// make child.DOM be inserted, removed, and inserted again
const innerDOM$ = xs
.periodic(120)
.take(2)
.map(x => x + 1)
.startWith(0)
.map(x => (x === 1 ? xs.of(div()) : (child.DOM)))
.flatten();
return {
DOM: innerDOM$,
};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.select(':root')
.element()
.drop(1)
.take(3)
.addListener({
next: (root: Element) => {
setTimeout(() => {
const foo = root.querySelector('.foo');
if (!foo) {
return;
}
(foo as any).click();
}, 0);
},
});
setTimeout(() => {
assert.strictEqual(clicksCount, 2);
dispose();
done();
}, 500);
dispose = run();
});
it('should handle events when parent is removed and re-added', done => {
let clicksCount = 0;
function Child(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.foo')
.events('click')
.addListener({
next: () => {
clicksCount++;
},
});
return {
DOM: xs.of(div('.foo', ['This is foo'])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const child = isolate(Child, 'child')(_sources);
// change parent key, causing it to be recreated
const x$ = xs
.periodic(120)
.map(x => x + 1)
.startWith(0)
.take(4);
const innerDOM$ = xs
.combine<number, VNode>(x$, child.DOM)
.map(([x, childVDOM]) =>
div(`.parent${x}`, {key: `key${x}`}, [childVDOM, `${x}`])
);
return {
DOM: innerDOM$,
};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.select(':root')
.element()
.drop(1)
.take(4)
.addListener({
next: (root: Element) => {
setTimeout(() => {
const foo = root.querySelector('.foo');
if (!foo) {
return;
}
(foo as any).click();
}, 0);
},
});
setTimeout(() => {
assert.strictEqual(clicksCount, 4);
dispose();
done();
}, 800);
dispose = run();
});
it('should handle events when parent is removed and re-added, and has isolation scope', done => {
let clicksCount = 0;
function Child(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.foo')
.events('click')
.addListener({
next: () => {
clicksCount++;
},
});
return {
DOM: xs.of(div('.foo', ['This is foo'])),
};
}
function Parent(_sources: {DOM: MainDOMSource}) {
const child = isolate(Child, 'child')(_sources);
// change parent key, causing it to be recreated
const x$ = xs
.periodic(120)
.map(x => x + 1)
.startWith(0)
.take(4);
const innerDOM$ = xs
.combine<number, VNode>(x$, child.DOM)
.map(([x, childVDOM]) =>
div(`.parent${x}`, {key: `key${x}`}, [childVDOM, `${x}`])
);
return {
DOM: innerDOM$,
};
}
function main(_sources: {DOM: MainDOMSource}) {
const parent = isolate(Parent, 'parent')(_sources);
return {
DOM: parent.DOM,
};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.select(':root')
.element()
.drop(1)
.take(4)
.addListener({
next: (root: Element) => {
setTimeout(() => {
const foo = root.querySelector('.foo');
if (!foo) {
return;
}
(foo as any).click();
}, 0);
},
});
setTimeout(() => {
assert.strictEqual(clicksCount, 4);
dispose();
done();
}, 800);
dispose = run();
});
it(
'should allow an isolated child to receive events when it is used as ' +
'the vTree of an isolated parent component',
done => {
let dispose: any;
function Component(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.btn')
.events('click')
.addListener({
next: (ev: Event) => {
assert.strictEqual((ev.target as HTMLElement).tagName, 'BUTTON');
dispose();
done();
},
});
return {
DOM: xs.of(div('.component', {}, [button('.btn', {}, 'Hello')])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const component = isolate(Component)(_sources);
return {DOM: component.DOM};
}
function app(_sources: {DOM: MainDOMSource}) {
return isolate(main)(_sources);
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const element = root.querySelector('.btn') as HTMLElement;
assert.notStrictEqual(element, null);
setTimeout(() => element.click());
},
});
dispose = run();
}
);
it(
'should allow an sibling isolated child to receive events when it is used as ' +
'the vTree of an isolated parent component',
done => {
let dispose: any;
function Component(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.btn')
.events('click')
.addListener({
next: (ev: Event) => {
assert.strictEqual((ev.target as HTMLElement).tagName, 'BUTTON');
dispose();
done();
},
});
return {
DOM: xs.of(
div(
'.component',
{
props: {className: 'mydiv'},
},
[button('.btn', {}, 'Hello')]
)
),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const component = isolate(Component, '.foo')(_sources);
return {DOM: component.DOM};
}
function app(_sources: {DOM: MainDOMSource}) {
return isolate(main)(_sources);
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const element = root.querySelector('.btn') as HTMLElement;
assert.notStrictEqual(element, null);
setTimeout(() => element.click());
},
});
dispose = run();
}
);
it(
'should allow an isolated child to receive events when it is used as ' +
'the vTree of an isolated parent component when scope is explicitly ' +
'specified on child',
done => {
let dispose: any;
function Component(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.btn')
.events('click')
.addListener({
next: (ev: Event) => {
assert.strictEqual((ev.target as HTMLElement).tagName, 'BUTTON');
dispose();
done();
},
});
return {
DOM: xs.of(div('.component', {}, [button('.btn', {}, 'Hello')])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const component = isolate(Component, 'foo')(_sources);
return {DOM: component.DOM};
}
function app(_sources: {DOM: MainDOMSource}) {
return isolate(main)(_sources);
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const element = root.querySelector('.btn') as HTMLElement;
assert.notStrictEqual(element, null);
setTimeout(() => element.click());
},
});
dispose = run();
}
);
it(
'should allow an isolated child to receive events when it is used as ' +
'the vTree of an isolated parent component when scope is explicitly ' +
'specified on parent',
done => {
let dispose: any;
function Component(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.btn')
.events('click')
.addListener({
next: (ev: Event) => {
assert.strictEqual((ev.target as HTMLElement).tagName, 'BUTTON');
dispose();
done();
},
});
return {
DOM: xs.of(div('.component', {}, [button('.btn', {}, 'Hello')])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const component = isolate(Component)(_sources);
return {DOM: component.DOM};
}
function app(_sources: {DOM: MainDOMSource}) {
return isolate(main, 'foo')(_sources);
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const element = root.querySelector('.btn') as HTMLElement;
assert.notStrictEqual(element, null);
setTimeout(() => element.click());
},
});
dispose = run();
}
);
it(
'should allow an isolated child to receive events when it is used as ' +
'the vTree of an isolated parent component when scope is explicitly ' +
'specified on parent and child',
done => {
let dispose: any;
function Component(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.btn')
.events('click')
.addListener({
next: (ev: Event) => {
assert.strictEqual((ev.target as HTMLElement).tagName, 'BUTTON');
dispose();
done();
},
});
return {
DOM: xs.of(div('.component', {}, [button('.btn', {}, 'Hello')])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const component = isolate(Component, 'bar')(_sources);
return {DOM: component.DOM};
}
function app(_sources: {DOM: MainDOMSource}) {
return isolate(main, 'foo')(_sources);
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
});
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const element = root.querySelector('.btn') as HTMLElement;
assert.notStrictEqual(element, null);
setTimeout(() => element.click());
},
});
dispose = run();
}
);
it(
'should maintain virtual DOM list sanity using keys, in a list of ' +
'isolated components',
done => {
const componentRemove$ = xs.create<any>();
function Component(_sources: {DOM: MainDOMSource}) {
_sources.DOM.select('.btn')
.events('click')
.addListener({
next: (ev: Event) => {
componentRemove$.shamefullySendNext(null);
},
});
return {
DOM: xs.of(div('.component', {}, [button('.btn', {}, 'Hello')])),
};
}
function main(_sources: {DOM: MainDOMSource}) {
const remove$ = componentRemove$
.compose(delay(50))
.fold(acc => acc + 1, 0);
const first = isolate(Component, 'first')(_sources);
const second = isolate(Component, 'second')(_sources);
const vdom$ = xs
.combine(first.DOM, second.DOM, remove$)
.map(([vdom1, vdom2, r]) => {
if (r === 0) {
return div([vdom1, vdom2]);
} else if (r === 1) {
return div([vdom2]);
} else if (r === 2) {
return div([]);
} else {
done('This case must not happen.');
return div();
}
});
return {DOM: vdom$};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const components = root.querySelectorAll('.btn');
assert.strictEqual(components.length, 2);
const firstElement = components[0] as HTMLElement;
const secondElement = components[1] as HTMLElement;
setTimeout(() => {
firstElement.click();
}, 100);
setTimeout(() => {
secondElement.click();
}, 300);
setTimeout(() => {
assert.strictEqual(root.querySelectorAll('.component').length, 0);
dispose();
done();
}, 500);
},
});
dispose = run();
}
);
it('should allow null or undefined isolated child DOM', function(done) {
function child(_sources: {DOM: MainDOMSource}) {
const visible$ = xs
.periodic(50)
.take(1)
.fold((acc, _) => !acc, true);
const vdom$ = visible$.map(visible => (visible ? h4('child') : null));
return {
DOM: vdom$,
};
}
function main(_sources: {DOM: MainDOMSource}) {
const childSinks = isolate(child, 'child')(_sources);
const vdom$ = childSinks.DOM.map((childVDom: VNode) =>
div('.parent', [childVDom, h2('part of parent')])
);
return {
DOM: vdom$,
};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const parentEl = root.querySelector('.parent') as Element;
assert.strictEqual(parentEl.childNodes.length, 2);
assert.strictEqual(parentEl.children[0].tagName, 'H4');
assert.strictEqual(parentEl.children[0].textContent, 'child');
assert.strictEqual(parentEl.children[1].tagName, 'H2');
assert.strictEqual(
parentEl.children[1].textContent,
'part of parent'
);
},
});
sources.DOM.element()
.drop(2)
.take(1)
.addListener({
next: (root: Element) => {
const parentEl = root.querySelector('.parent') as Element;
assert.strictEqual(parentEl.childNodes.length, 1);
assert.strictEqual(parentEl.children[0].tagName, 'H2');
assert.strictEqual(
parentEl.children[0].textContent,
'part of parent'
);
dispose();
done();
},
});
dispose = run();
});
it('should allow recursive isolation using the same scope', done => {
function Item(_sources: {DOM: MainDOMSource}, count: number) {
const childVdom$: Stream<VNode> =
count > 0
? isolate(Item, '0')(_sources, count - 1).DOM
: xs.of<any>(null);
const highlight$ = _sources.DOM.select('button')
.events('click')
.mapTo(true)
.fold((x, _) => !x, false);
const vdom$ = xs
.combine(childVdom$, highlight$)
.map(([childVdom, highlight]) =>
div([
button('.btn', highlight ? 'HIGHLIGHTED' : 'click me'),
childVdom,
])
);
return {DOM: vdom$};
}
function main(_sources: {DOM: MainDOMSource}) {
const vdom$ = Item(_sources, 3).DOM;
return {DOM: vdom$};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.element()
.drop(1)
.take(1)
.addListener({
next: (root: Element) => {
const buttons = root.querySelectorAll('.btn');
assert.strictEqual(buttons.length, 4);
const firstButton = buttons[0];
const secondButton = buttons[1];
const thirdButton = buttons[2] as HTMLElement;
const forthButton = buttons[3];
setTimeout(() => {
thirdButton.click();
}, 100);
setTimeout(() => {
assert.notStrictEqual(firstButton.textContent, 'HIGHLIGHTED');
assert.notStrictEqual(secondButton.textContent, 'HIGHLIGHTED');
assert.strictEqual(thirdButton.textContent, 'HIGHLIGHTED');
assert.notStrictEqual(forthButton.textContent, 'HIGHLIGHTED');
dispose();
done();
}, 300);
},
});
dispose = run();
});
it('should not lose event delegators when components are moved around', function(done) {
function component(_sources: {DOM: MainDOMSource}) {
const click$ = _sources.DOM.select('.click-me')
.events('click')
.mapTo('clicked');
return {
DOM: xs.of(button('.click-me', 'click me')),
click$,
};
}
function app(_sources: {DOM: MainDOMSource}) {
const comp = isolate(component, 'child')(_sources);
const position$ = fromDiagram('1-2|');
return {
DOM: xs.combine(position$, comp.DOM).map(([position, childDom]) => {
const children =
position === '1'
? [div([childDom]), div()]
: [div(), div([childDom])];
return div(children);
}),
click$: comp.click$,
};
}
const {sinks, sources, run} = setup(app, {
DOM: makeDOMDriver(createRenderTarget()),
click$: () => {},
});
const expectedClicks = ['clicked', 'clicked'];
let dispose: any;
sinks.click$.take(2).addListener({
next: function(message: string) {
assert.strictEqual(message, expectedClicks.shift());
},
complete: function() {
assert.strictEqual(expectedClicks.length, 0);
done();
dispose();
},
});
sources.DOM.select(':root')
.element()
.drop(1)
.addListener({
next: function(root: Element) {
const _button = root.querySelector('button.click-me') as HTMLElement;
_button.click();
},
});
dispose = run();
});
it('should not break isolation if animated elements are removed', done => {
let eventProcessed = false;
function Child(_sources: {DOM: MainDOMSource}): any {
const remove$ = _sources.DOM.select('.click')
.events('click')
.mapTo(false);
_sources.DOM.select('.click')
.events('click')
.addListener({
next: (ev: any) => {
assert.strictEqual(ev.target.textContent, 'remove');
assert.strictEqual(eventProcessed, false);
eventProcessed = true;
},
});
const style = {
transition: 'transform 0.5s',
// remove handler broke isolation in earier versions
remove: {
transform: 'translateY(100%)',
},
};
return {
DOM: xs.of(button('.click', {style}, 'remove')),
remove: remove$,
};
}
function main(_sources: {DOM: MainDOMSource}): any {
const childSinks = isolate(Child)(_sources);
const showChild$ = _sources.DOM.select('.click')
.events('click')
.mapTo(true);
showChild$.addListener({
next: ev => assert(false),
});
const state$ = xs.merge(showChild$, childSinks.remove).startWith(true);
return {
DOM: xs
.combine(state$, childSinks.DOM)
.map(([show, child]) =>
div([button('.click', 'show'), show ? child : null])
),
};
}
const {sinks, sources, run} = setup(main, {
DOM: makeDOMDriver(createRenderTarget()),
});
let dispose: any;
sources.DOM.select(':root')
.element()
.drop(1)
.take(1)
.addListener({
next: function(root: Element) {
const _button = root.querySelector(
'button.click:nth-child(2)'
) as HTMLElement;
assert.strictEqual(_button.textContent, 'remove');
_button.click();
setTimeout(() => {
assert.strictEqual(eventProcessed, true);
assert.strictEqual(root.querySelectorAll('button').length, 1);
dispose();
done();
}, 600);
},
});
dispose = run();
});
}); | the_stack |
import React from "react"
import ReactDOM from "react-dom"
import Head from "@docusaurus/Head"
import * as ReactKakaoMapsSdk from "react-kakao-maps-sdk"
import clusterPositionsData from "./clusterPositions.json"
const AddMapControlStyle = () => (
<Head>
<style>{`
.map_wrap {position:relative;overflow:hidden;width:100%;height:350px;}
.radius_border{border:1px solid #919191;border-radius:5px;}
.custom_typecontrol {color:#000;display:flex;position:absolute;top:10px;right:10px;overflow:hidden;width:130px;height:30px;margin:0;padding:0;z-index:1;font-size:12px;font-family:'Malgun Gothic', '맑은 고딕', sans-serif;}
.custom_typecontrol span {display:block;width:65px;height:30px;float:left;text-align:center;line-height:30px;cursor:pointer;}
.custom_typecontrol .btn {background:#fff;background:linear-gradient(#fff, #e6e6e6);}
.custom_typecontrol .btn:hover {background:#f5f5f5;background:linear-gradient(#f5f5f5,#e3e3e3);}
.custom_typecontrol .btn:active {background:#e6e6e6;background:linear-gradient(#e6e6e6, #fff);}
.custom_typecontrol .selected_btn {color:#fff;background:#425470;background:linear-gradient(#425470, #5b6d8a);}
.custom_typecontrol .selected_btn:hover {color:#fff;}
.custom_zoomcontrol {position:absolute;top:50px;right:10px;width:36px;height:80px;overflow:hidden;z-index:1;background-color:#f5f5f5;}
.custom_zoomcontrol span {display:flex;justify-content:center;width:36px;height:40px;text-align:center;cursor:pointer;}
.custom_zoomcontrol span img {width:15px;height:15px;align-self:center;}
.custom_zoomcontrol span:first-child{border-bottom:1px solid #bfbfbf;}
`}</style>
</Head>
)
const RoadviewCustomOverlayStyle = () => (
<Head>
<style>{`
.overlay_info {
border-radius: 6px;
margin-bottom: 12px;
float: left;
position: relative;
border: 1px solid #ccc;
border-bottom: 2px solid #ddd;
background-color: #fff;
}
.overlay_info:nth-of-type(n) {
border: 0;
box-shadow: 0px 1px 2px #888;
}
.overlay_info a {
display: block;
background: #d95050;
background: #d95050
url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/arrow_white.png)
no-repeat right 14px center;
text-decoration: none;
color: #fff;
padding: 12px 36px 12px 14px;
font-size: 14px;
border-radius: 6px 6px 0 0;
}
.overlay_info a strong {
background: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/place_icon.png)
no-repeat;
padding-left: 27px;
}
.overlay_info .desc {
padding: 14px;
position: relative;
min-width: 190px;
height: auto;
}
.overlay_info img {
vertical-align: top;
}
.overlay_info .address {
font-size: 12px;
color: #333;
position: absolute;
left: 80px;
right: 14px;
top: 14px;
white-space: normal;
}
.overlay_info:after {
content: "";
position: absolute;
margin-left: -11px;
left: 50%;
bottom: -12px;
width: 22px;
height: 12px;
background: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/vertex_white.png)
no-repeat 0 bottom;
}
`}</style>
</Head>
)
const CustomOverlay1Style = () => (
<Head>
<style>{`
.label {
margin-bottom: 96px;
}
.label * {
display: inline-block;
vertical-align: top;
}
.label .left {
background: url("https://t1.daumcdn.net/localimg/localimages/07/2011/map/storeview/tip_l.png")
no-repeat;
display: inline-block;
height: 24px;
overflow: hidden;
vertical-align: top;
width: 7px;
}
.label .center {
background: url(https://t1.daumcdn.net/localimg/localimages/07/2011/map/storeview/tip_bg.png)
repeat-x;
display: inline-block;
height: 24px;
font-size: 12px;
line-height: 24px;
}
.label .right {
background: url("https://t1.daumcdn.net/localimg/localimages/07/2011/map/storeview/tip_r.png") -1px
0 no-repeat;
display: inline-block;
height: 24px;
overflow: hidden;
width: 6px;
}
`}</style>
</Head>
)
const CustomOverlay2Style = () => (
<Head>
<style>{`
.overlaybox {
position: relative;
width: 360px;
height: 350px;
background: url("https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/box_movie.png")
no-repeat;
padding: 15px 10px;
}
.overlaybox div,
ul {
overflow: hidden;
margin: 0;
padding: 0;
}
.overlaybox li {
list-style: none;
}
.overlaybox .boxtitle {
color: #fff;
font-size: 16px;
font-weight: bold;
background: url("https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/arrow_white.png")
no-repeat right 120px center;
margin-bottom: 8px;
}
.overlaybox .first {
position: relative;
width: 247px;
height: 136px;
background: url("https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/thumb.png")
no-repeat;
margin-bottom: 8px;
}
.first .text {
color: #fff;
font-weight: bold;
}
.first .triangle {
position: absolute;
width: 48px;
height: 48px;
top: 0;
left: 0;
background: url("https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/triangle.png")
no-repeat;
padding: 6px;
font-size: 18px;
}
.first .movietitle {
position: absolute;
width: 100%;
bottom: 0;
background: rgba(0, 0, 0, 0.4);
padding: 7px 15px;
font-size: 14px;
}
.overlaybox ul {
width: 247px;
}
.overlaybox li {
position: relative;
margin-bottom: 2px;
background: #2b2d36;
padding: 5px 10px;
color: #aaabaf;
line-height: 1;
}
.overlaybox li span {
display: inline-block;
}
.overlaybox li .number {
font-size: 16px;
font-weight: bold;
}
.overlaybox li .title {
font-size: 13px;
}
.overlaybox ul .arrow {
position: absolute;
margin-top: 8px;
right: 25px;
width: 5px;
height: 3px;
background: url("https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/updown.png")
no-repeat;
}
.overlaybox li .up {
background-position: 0 -40px;
}
.overlaybox li .down {
background-position: 0 -60px;
}
.overlaybox li .count {
position: absolute;
margin-top: 5px;
right: 15px;
font-size: 10px;
}
.overlaybox li:hover {
color: #fff;
background: #d24545;
}
.overlaybox li:hover .up {
background-position: 0 0px;
}
.overlaybox li:hover .down {
background-position: 0 -20px;
}
`}</style>
</Head>
)
const CategoryMarkerStyle = () => (
<Head>
<style>{`
#mapwrap{position:relative;overflow:hidden;}
.category, .category *{margin:0;padding:0;color:#000;}
.category {position:absolute;overflow:hidden;top:10px;left:10px;width:150px;height:50px;z-index:10;border:1px solid black;font-family:'Malgun Gothic','맑은 고딕',sans-serif;font-size:12px;text-align:center;background-color:#fff;}
.category .menu_selected {background:#FF5F4A;color:#fff;border-left:1px solid #915B2F;border-right:1px solid #915B2F;margin:0px;}
.category ul{display:flex}
.category li{list-style:none;float:left;width:50px;height:50px;margin:0 !important;padding-top:5px;cursor:pointer;}
.category .ico_comm {display:block;margin:0 auto 2px;width:22px;height:26px;background:url('https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/category.png') no-repeat;}
.category .ico_coffee {background-position:-10px 0;}
.category .ico_store {background-position:-10px -36px;}
.category .ico_carpark {background-position:-10px -72px;}
`}</style>
</Head>
)
const CalculatePolylineDistanceStyle = () => (
<Head>
<style>{`
.dot {overflow:hidden;float:left;width:12px;height:12px;background: url('https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/mini_circle.png');}
.dotOverlay {color:#000;position:relative;bottom:10px;border-radius:6px;border: 1px solid #ccc;border-bottom:2px solid #ddd;float:left;font-size:12px;padding:5px;background:#fff;}
.dotOverlay li {display:block;}
.dotOverlay:nth-of-type(n) {border:0; box-shadow:0px 1px 2px #888;}
.number {font-weight:bold;color:#ee6152;}
.dotOverlay:after {content:'position:absolute;margin-left:-6px;left:50%;bottom:-8px;width:11px;height:8px;background:url('https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/vertex_white_small.png')}
.distanceInfo {position:relative;list-style:none;margin:0;}
.distanceInfo .label {display:inline-block;width:50px;}
.distanceInfo:after {content:none;}
`}</style>
</Head>
)
const CalculatePolygonAreaStyle = () => (
<Head>
<style>{`
.info {color:#000;position:relative;top:5px;left:5px;border-radius:6px;border: 1px solid #ccc;border-bottom:2px solid #ddd;font-size:12px;padding:5px;background:#fff;list-style:none;margin:0;}
.info:nth-of-type(n) {border:0; box-shadow:0px 1px 2px #888;}
.info .label {display:inline-block;width:50px;}
.number {font-weight:bold;color:#00a0e9;}
`}</style>
</Head>
)
const AddPolygonMouseEvent2Style = () => (
<Head>
<style>{`
.area {
color: #000;
position: absolute;
background: #fff;
border: 1px solid #888;
border-radius: 3px;
font-size: 12px;
top: -5px;
left: 15px;
padding:2px;
}
.info {
color: #000;
font-size: 12px;
padding: 5px;
}
.info .title {
font-weight: bold;
}
`}</style>
</Head>
)
const CalculateCircleRadiusStyle = () => (
<Head>
<style>{`
.info {color:#000;position:relative;top:5px;left:5px;border-radius:6px;border: 1px solid #ccc;border-bottom:2px solid #ddd;font-size:12px;padding:5px;background:#fff;list-style:none;margin:0;}
.info:nth-of-type(n) {border:0; box-shadow:0px 1px 2px #888;}
.info .label {display:inline-block;width:50px;}
.number {font-weight:bold;color:#00a0e9;}
`}</style>
</Head>
)
const RemovableCustomOverlayStyle = () => (
<Head>
<style>{`
.wrap {color:#000;position: absolute;left: 0;bottom: 40px;width: 288px;height: 132px;margin-left: -144px;text-align: left;overflow: hidden;font-size: 12px;font-family: Malgun Gothic, dotum, 돋움, sans-serif;line-height: 1.5;}
.wrap * {padding: 0;margin: 0;}
.wrap .info {width: 286px;height: 120px;border-radius: 5px;border-bottom: 2px solid #ccc;border-right: 1px solid #ccc;overflow: hidden;background: #fff;}
.wrap .info:nth-child(1) {border: 0;box-shadow: 0px 1px 2px #888;}
.info .title {padding: 5px 0 0 10px;height: 30px;background: #eee;border-bottom: 1px solid #ddd;font-size: 18px;font-weight: bold;}
.info .close {position: absolute;top: 10px;right: 10px;color: #888;width: 17px;height: 17px;background: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/overlay_close.png);}
.info .close:hover {cursor: pointer;}
.info .body {position: relative;overflow: hidden;}
.info .desc {position: relative;margin: 13px 0 0 90px;height: 75px;}
.desc .ellipsis {overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}
.desc .jibun {font-size: 11px;color: #888;margin-top: -2px;}
.info .img {position: absolute;top: 6px;left: 5px;width: 73px;height: 71px;border: 1px solid #ddd;color: #888;overflow: hidden;}
.info:after {content: ;position: absolute;margin-left: -12px;left: 50%;bottom: 0;width: 22px;height: 12px;background: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/vertex_white.png)}
.info .link {color: #5085BB;}
`}</style>
</Head>
)
const MarkerWithCustomOverlayStyle = () => (
<Head>
<style>{`
.customoverlay {position:relative;bottom:85px;border-radius:6px;border: 1px solid #ccc;border-bottom:2px solid #ddd;float:left;}
.customoverlay:nth-of-type(n) {border:0; box-shadow:0px 1px 2px #888;}
.customoverlay a {display:block;text-decoration:none;color:#000;text-align:center;border-radius:6px;font-size:14px;font-weight:bold;overflow:hidden;background: #d95050;background: #d95050 url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/arrow_white.png) no-repeat right 14px center;}
.customoverlay .title {display:block;text-align:center;background:#fff;margin-right:35px;padding:10px 15px;font-size:14px;font-weight:bold;}
.customoverlay:after {content:'';position:absolute;margin-left:-12px;left:50%;bottom:-12px;width:22px;height:12px;background:url('https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/vertex_white.png')}
`}</style>
</Head>
)
const DragCustomOverlayStyle = () => (
<Head>
<style>{`
.overlay {
color:#000;
position:absolute;
left: -50px;
top:0;
width:100px;
height: 100px;
background: #fff;
border:1px solid #ccc;
border-radius: 5px;
padding:5px;
font-size:12px;
text-align: center;
white-space: pre;
word-wrap: break-word;
`}</style>
</Head>
)
const MarkerTrackerStyle = () => (
<Head>
<style>{`
.node {
position: absolute;
background-image: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/sign-info-64.png);
cursor: pointer;
width: 64px;
height: 64px;
}
.tooltip {
color:#000;
background-color: #fff;
position: absolute;
border: 2px solid #333;
font-size: 25px;
font-weight: bold;
padding: 3px 5px 0;
left: 65px;
top: 14px;
border-radius: 5px;
white-space: nowrap;
}
.tracker {
position: absolute;
margin: -35px 0 0 -30px;
cursor: pointer;
z-index: 3;
}
.icon {
position: absolute;
left: 6px;
top: 9px;
width: 48px;
height: 48px;
background-image: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/sign-info-48.png);
}
.balloon {
position: absolute;
width: 60px;
height: 60px;
background-image: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/balloon.png);
-ms-transform-origin: 50% 34px;
-webkit-transform-origin: 50% 34px;
transform-origin: 50% 34px;
}
`}</style>
</Head>
)
const MoveRoadviewStyle = () => (
<Head>
<style>{`
.map_wrap {overflow:hidden;height:330px}
/* 지도위에 로드뷰의 위치와 각도를 표시하기 위한 map walker 아이콘의 스타일 */
.MapWalker {position:absolute;margin:-26px 0 0 -51px}
.MapWalker .figure {position:absolute;width:25px;left:38px;top:-2px;
height:39px;background:url(https://t1.daumcdn.net/localimg/localimages/07/2018/pc/roadview_minimap_wk_2018.png) -298px -114px no-repeat}
.MapWalker .angleBack {width:102px;height:52px;background: url(https://t1.daumcdn.net/localimg/localimages/07/2018/pc/roadview_minimap_wk_2018.png) -834px -2px no-repeat;}
.MapWalker.m0 .figure {background-position: -298px -114px;}
.MapWalker.m1 .figure {background-position: -335px -114px;}
.MapWalker.m2 .figure {background-position: -372px -114px;}
.MapWalker.m3 .figure {background-position: -409px -114px;}
.MapWalker.m4 .figure {background-position: -446px -114px;}
.MapWalker.m5 .figure {background-position: -483px -114px;}
.MapWalker.m6 .figure {background-position: -520px -114px;}
.MapWalker.m7 .figure {background-position: -557px -114px;}
.MapWalker.m8 .figure {background-position: -2px -114px;}
.MapWalker.m9 .figure {background-position: -39px -114px;}
.MapWalker.m10 .figure {background-position: -76px -114px;}
.MapWalker.m11 .figure {background-position: -113px -114px;}
.MapWalker.m12 .figure {background-position: -150px -114px;}
.MapWalker.m13 .figure {background-position: -187px -114px;}
.MapWalker.m14 .figure {background-position: -224px -114px;}
.MapWalker.m15 .figure {background-position: -261px -114px;}
.MapWalker.m0 .angleBack {background-position: -834px -2px;}
.MapWalker.m1 .angleBack {background-position: -938px -2px;}
.MapWalker.m2 .angleBack {background-position: -1042px -2px;}
.MapWalker.m3 .angleBack {background-position: -1146px -2px;}
.MapWalker.m4 .angleBack {background-position: -1250px -2px;}
.MapWalker.m5 .angleBack {background-position: -1354px -2px;}
.MapWalker.m6 .angleBack {background-position: -1458px -2px;}
.MapWalker.m7 .angleBack {background-position: -1562px -2px;}
.MapWalker.m8 .angleBack {background-position: -2px -2px;}
.MapWalker.m9 .angleBack {background-position: -106px -2px;}
.MapWalker.m10 .angleBack {background-position: -210px -2px;}
.MapWalker.m11 .angleBack {background-position: -314px -2px;}
.MapWalker.m12 .angleBack {background-position: -418px -2px;}
.MapWalker.m13 .angleBack {background-position: -522px -2px;}
.MapWalker.m14 .angleBack {background-position: -626px -2px;}
.MapWalker.m15 .angleBack {background-position: -730px -2px;}
`}</style>
</Head>
)
const RoadviewOverlay1Style = () => (
<Head>
<style>{`
.screen_out {display:block;overflow:hidden;position:absolute;left:-9999px;width:1px;height:1px;font-size:0;line-height:0;text-indent:-9999px}
.wrap_content {}
.wrap_map {display:inline-block;width:50%;height:300px;position:relative}
.wrap_roadview {display:inline-block;width:50%;height:300px;position:relative}
.wrap_button {position:absolute;left:15px;top:12px;z-index:2}
.btn_comm {border:none;float:left;display:block;width:70px;height:27px;background:url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/sample_button_control.png) no-repeat}
.btn_linkMap {background-position:0 0;}
.btn_resetMap {background-position:-69px 0;}
.btn_linkRoadview {background-position:0 0;}
.btn_resetRoadview {background-position:-69px 0;}
`}</style>
</Head>
)
const RoadviewImageOverlayStyle = () => (
<Head>
<style>{`
#overlayImg {
width: 394px;
height: 242px;
border: 1px solid #096320;
transition: linear 0.5s opacity;
}
#overlayImg:hover {
opacity: 0;
}
`}</style>
</Head>
)
const RoadviewWithMapButtonStyle = () => (
<Head>
<style>{`
#container {overflow:hidden;height:300px;position:relative;}
#rvWrapper {width:50%;height:300px;top:0;right:0;position:absolute;z-index:0;}
#container.view_roadview #mapWrapper {width: 50%;}
#roadviewControl {position:absolute;top:5px;left:5px;width:42px;height:42px;z-index: 1;cursor: pointer; background: url(https://t1.daumcdn.net/localimg/localimages/07/2018/pc/common/img_search.png) 0 -450px no-repeat;}
#roadviewControl.active {background-position:0 -350px;}
#close {position: absolute;padding: 4px;top: 5px;left: 5px;cursor: pointer;background: #fff;border-radius: 4px;border: 1px solid #c8c8c8;box-shadow: 0px 1px #888;}
#close .img {display: block;background: url(https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/rv_close.png) no-repeat;width: 14px;height: 14px;}
`}</style>
</Head>
)
// Add react-live imports you need here
const ReactLiveScope = {
React,
...React,
ReactDOM,
...ReactDOM,
...ReactKakaoMapsSdk,
clusterPositionsData,
Head,
AddMapControlStyle,
RoadviewCustomOverlayStyle,
CustomOverlay1Style,
CustomOverlay2Style,
CategoryMarkerStyle,
CalculatePolylineDistanceStyle,
CalculatePolygonAreaStyle,
AddPolygonMouseEvent2Style,
CalculateCircleRadiusStyle,
RemovableCustomOverlayStyle,
MarkerWithCustomOverlayStyle,
DragCustomOverlayStyle,
MarkerTrackerStyle,
MoveRoadviewStyle,
RoadviewOverlay1Style,
RoadviewImageOverlayStyle,
RoadviewWithMapButtonStyle,
}
export default ReactLiveScope | the_stack |
import React, { useState } from "react";
import {
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TableSortLabel,
} from "@material-ui/core";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import { useHistory, useParams } from "react-router-dom";
import { useClickOutside } from "@iris/hooks";
interface Props {
projects: any[];
name: string;
}
interface Data {
name: string;
images?: number;
labels?: string[];
created?: Date;
modified?: Date;
}
const months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
type Order = "asc" | "desc";
function getComparator(order: Order, orderBy: any): (a: any, b: any) => number {
return order === "desc"
? (a, b) => descendingComparator(a, b, orderBy)
: (a, b) => -descendingComparator(a, b, orderBy);
}
function stableSort<T>(array: T[], comparator: (a: T, b: T) => number) {
const stabilizedThis = array.map((el, index) => ({ el, index }));
stabilizedThis.sort((a, b) => {
const order = comparator(a.el, b.el);
if (order !== 0) return order;
return a.index - b.index;
});
return stabilizedThis.map(({ el }) => el);
}
const cellSize: { [key: string]: number } = {
name: -1,
labels: 350,
images: 140,
modified: 200,
};
interface HeadCell {
id: keyof Data;
label: string;
}
const headCells: HeadCell[] = [
{ id: "name", label: "Name" },
{ id: "labels", label: "Labels" },
{ id: "images", label: "Images" },
{ id: "modified", label: "Modified" },
];
interface EnhancedTableProps {
classes: ReturnType<typeof useStyles>;
onRequestSort: (
event: React.MouseEvent<unknown>,
property: keyof Data
) => void;
order: Order;
orderBy: string;
}
function EnhancedTableHead(props: EnhancedTableProps) {
const { classes, order, orderBy, onRequestSort } = props;
const createSortHandler =
(property: keyof Data) => (event: React.MouseEvent<unknown>) => {
onRequestSort(event, property);
};
return (
<TableHead className={classes.tableHead}>
<TableRow className={classes.tableHeadRow}>
{headCells.map((headCell) => (
<TableCell
className={classes.tableHeadCell}
key={headCell.id}
style={
cellSize[headCell.id] >= 0
? {
flexGrow: 0,
flexShrink: 0,
flexBasis: cellSize[headCell.id],
}
: { flexGrow: 1, flexShrink: 1, flexBasis: "auto" }
}
align="left"
padding="none"
sortDirection={orderBy === headCell.id ? order : false}
>
<TableSortLabel
active={orderBy === headCell.id}
direction={orderBy === headCell.id ? order : "asc"}
onClick={createSortHandler(headCell.id)}
>
{headCell.label}
</TableSortLabel>
</TableCell>
))}
<TableCell padding="none" style={{ width: 16 }}></TableCell>
</TableRow>
</TableHead>
);
}
const useStyles = makeStyles((theme: Theme) =>
createStyles({
header: {
position: "absolute",
top: 0,
left: 0,
right: 0,
height: 47,
// backgroundColor: "var(--secondaryBg)",
display: "flex",
alignItems: "center",
},
title: {
padding: "0 24px",
fontSize: 18,
marginRight: "auto",
},
tableHead: {
position: "absolute",
display: "block",
top: 47,
left: 16,
right: 32,
// paddingRight: 16,
height: 40,
},
tableHeadRow: {
display: "flex",
height: "100%",
},
tableHeadCell: {
color: "rgba(255, 255, 255, 0.76)",
fontSize: 13,
fontWeight: 500,
padding: "0 8px",
display: "flex",
alignItems: "center",
"& .MuiTableSortLabel-active": {
color: "rgba(255, 255, 255, 0.76)",
},
"& > .MuiTableSortLabel-root:hover": {
color: "rgba(255, 255, 255, 1)",
},
},
tableBody: {
position: "absolute",
display: "block",
top: 47 + 40,
bottom: 0,
left: 16,
right: 32,
paddingRight: 16,
overflow: "scroll",
paddingBottom: 32,
userSelect: "none",
},
tableRow: {
display: "flex",
height: 48,
"& .MuiTableCell-root": {
// borderBottom: "1px solid #393939",
// borderBottom: "1px solid #262626",
borderBottom: "1px solid rgba(111, 111, 111, 0.16)",
},
"&:last-child .MuiTableCell-root": {
borderBottom: "1px solid transparent",
},
"&.MuiTableRow-hover:hover": {
backgroundColor: "transparent",
},
"&.Mui-selected": {
backgroundColor: "rgba(111, 111, 111, 0.16) !important",
},
"& td": {
color: "rgba(255, 255, 255, 0.51)",
},
},
tableCell: {
display: "flex",
alignItems: "center",
padding: "0 8px",
},
root: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: "var(--bg)",
},
tags: {
display: "flex",
},
tagOverflow: {
fontSize: 12,
marginRight: 8,
padding: "4px 4px",
color: "#ffffff",
// backgroundColor: "#273142",
// backgroundColor: "#263245",
// backgroundColor: "#212e46",
backgroundColor: "#263040",
borderRadius: "6px",
},
tag: {
fontSize: 12,
marginRight: 8,
padding: "4px 8px",
color: "#ffffff",
// backgroundColor: "#273142",
// backgroundColor: "#263245",
// backgroundColor: "#212e46",
backgroundColor: "#263040",
borderRadius: "20px",
},
})
);
function formatDate(d: Date) {
return `${months[d.getMonth()]} ${d.getDate()}, ${d.getUTCFullYear()}`;
}
function EnhancedTable({
rows,
name: connectionName,
}: {
rows: Data[];
name: string;
}) {
const classes = useStyles();
const [order, setOrder] = useState<Order>("desc");
const [orderBy, setOrderBy] = useState<keyof Data>("modified");
const [selected, setSelected] = useState<string[]>([]);
const history = useHistory();
const { providerID, connectionID } = useParams<any>();
const { ref } = useClickOutside<HTMLDivElement>(() => {
setSelected([]);
});
const handleRequestSort = (
event: React.MouseEvent<unknown>,
property: keyof Data
) => {
const isAsc = orderBy === property && order === "asc";
setOrder(isAsc ? "desc" : "asc");
setOrderBy(property);
};
const handleClick = (event: React.MouseEvent<unknown>, name: string) => {
if (selected.includes(name)) {
setSelected([]);
return;
}
setSelected([name]);
return;
};
const isSelected = (name: string) => selected.indexOf(name) !== -1;
return (
<div className={classes.root} ref={ref}>
<div className={classes.header}>
<div className={classes.title}>{connectionName}</div>
</div>
<TableContainer>
<Table
aria-labelledby="tableTitle"
size="medium"
aria-label="enhanced table"
>
<EnhancedTableHead
classes={classes}
order={order}
orderBy={orderBy}
onRequestSort={handleRequestSort}
/>
<TableBody className={classes.tableBody}>
{stableSort(rows, getComparator(order, orderBy)).map(
(row, index) => {
const isItemSelected = isSelected(row.name);
const labelId = `enhanced-table-checkbox-${index}`;
return (
<TableRow
className={classes.tableRow}
hover
onClick={(event) => handleClick(event, row.name)}
onDoubleClick={(e) =>
history.push(
`/projects/${providerID}/${connectionID}/${row.name}`
)
}
role="checkbox"
aria-checked={isItemSelected}
tabIndex={-1}
key={row.name}
selected={isItemSelected}
>
<TableCell
className={classes.tableCell}
style={
cellSize.name >= 0
? {
flexGrow: 0,
flexShrink: 0,
flexBasis: cellSize.name,
}
: { flexGrow: 1, flexShrink: 1, flexBasis: "auto" }
}
component="th"
id={labelId}
scope="row"
padding="none"
>
{row.name}
</TableCell>
<TableCell
style={
cellSize.labels >= 0
? {
flexGrow: 0,
flexShrink: 0,
flexBasis: cellSize.labels,
}
: { flexGrow: 1, flexShrink: 1, flexBasis: "auto" }
}
className={classes.tableCell}
align="left"
>
{row.labels && row.labels.length > 0 ? (
<div className={classes.tags}>
{row.labels.map((l) => (
<div className={classes.tag}>{l}</div>
))}
{/* <div className={classes.tagOverflow}>+2</div> */}
</div>
) : (
"—"
)}
</TableCell>
<TableCell
style={
cellSize.images >= 0
? {
flexGrow: 0,
flexShrink: 0,
flexBasis: cellSize.images,
}
: { flexGrow: 1, flexShrink: 1, flexBasis: "auto" }
}
className={classes.tableCell}
align="left"
>
{row.images ? row.images.toLocaleString() : "—"}
</TableCell>
<TableCell
style={
cellSize.modified >= 0
? {
flexGrow: 0,
flexShrink: 0,
flexBasis: cellSize.modified,
}
: { flexGrow: 1, flexShrink: 1, flexBasis: "auto" }
}
className={classes.tableCell}
align="left"
>
{row.modified ? formatDate(row.modified) : "—"}
</TableCell>
</TableRow>
);
}
)}
</TableBody>
</Table>
</TableContainer>
</div>
);
}
function Main({ projects, name }: Props) {
return (
<EnhancedTable
name={name}
rows={[
...projects.map((p) => ({
name: p.name,
labels: Object.values(p.labels ?? []).map((l: any) => l.name),
images: p.images,
created: p.created ? new Date(p.created) : undefined,
modified: p.modified ? new Date(p.modified) : undefined,
})),
]}
/>
);
}
export default Main; | the_stack |
import { EChartsType, registerMap } from '../../../../src/echarts';
import { GeoJSON } from '../../../../src/coord/geo/geoTypes';
import { createChart } from '../../core/utHelper';
describe('api/converter', function () {
const DELTA = 1E-3;
function pointEquals(p1: number | number[], p2: number | number[]): boolean {
if (p1 instanceof Array && p2 instanceof Array) {
return Math.abs(p1[0] - p2[0]) < DELTA && Math.abs(p1[1] - p2[1]) < DELTA;
}
else if (typeof p1 === 'number' && typeof p2 === 'number') {
return Math.abs(p1 - p2) < DELTA;
}
else {
throw Error('Iillegal p1 or p2');
}
}
const testGeoJson1: GeoJSON = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[
2000,
3000
],
[
5000,
3000
],
[
5000,
8000
],
[
2000,
8000
]
]
]
},
'properties': {
'name': 'Afghanistan',
'childNum': 1
}
}
]
};
const testGeoJson2: GeoJSON = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[
200,
300
],
[
500,
300
],
[
500,
800
],
[
200,
800
]
]
]
},
'properties': {
'name': 'Afghanistan',
'childNum': 1
}
}
]
};
registerMap('converter_test_geo_1', testGeoJson1);
registerMap('converter_test_geo_2', testGeoJson2);
let chart: EChartsType;
beforeEach(function () {
chart = createChart();
});
afterEach(function () {
chart.dispose();
});
it('geo', function () {
// TODO Needs namespace
chart.setOption({
geo: [
{
id: 'aa',
left: 10,
right: 20,
top: 30,
bottom: 40,
map: 'converter_test_geo_1'
},
{
id: 'bb',
left: 10,
right: 20,
top: 30,
bottom: 40,
map: 'converter_test_geo_2'
}
],
series: [
{id: 'k1', type: 'scatter', coordinateSystem: 'geo', geoIndex: 1},
{id: 'k2', type: 'scatter', coordinateSystem: 'geo'},
{ // Should not be affected by map.
id: 'm1',
type: 'map',
map: 'converter_test_geo_1',
left: 10,
right: 20,
top: 30,
bottom: 40
}
]
});
const width = chart.getWidth();
const height = chart.getHeight();
expect(pointEquals(chart.convertToPixel('geo', [5000, 3000]), [width - 20, height - 40])).toEqual(true);
expect(pointEquals(chart.convertFromPixel('geo', [width - 20, height - 40]), [5000, 3000])).toEqual(true);
expect(pointEquals(chart.convertToPixel({geoIndex: 1}, [500, 800]), [width - 20, 30])).toEqual(true);
expect(pointEquals(chart.convertFromPixel({geoIndex: 1}, [width - 20, 30]), [500, 800])).toEqual(true);
expect(pointEquals(chart.convertToPixel({geoId: 'bb'}, [200, 300]), [10, height - 40])).toEqual(true);
expect(pointEquals(chart.convertFromPixel({geoId: 'bb'}, [10, height - 40]), [200, 300])).toEqual(true);
expect(pointEquals(chart.convertToPixel({seriesIndex: 0}, [200, 800]), [10, 30])).toEqual(true);
expect(pointEquals(chart.convertFromPixel({seriesIndex: 0}, [10, 30]), [200, 800])).toEqual(true);
expect(pointEquals(chart.convertToPixel({seriesId: 'k2'}, [2000, 8000]), [10, 30])).toEqual(true);
expect(pointEquals(chart.convertFromPixel({seriesId: 'k2'}, [10, 30]), [2000, 8000])).toEqual(true);
});
it('map', function () {
chart.setOption({
geo: [ // Should not be affected by geo
{
id: 'aa',
left: 10,
right: 20,
top: 30,
bottom: 40,
map: 'converter_test_geo_1'
}
],
series: [
{
id: 'k1',
type: 'map',
map: 'converter_test_geo_1',
left: 10,
right: 20,
top: 30,
bottom: 40
},
{
id: 'k2',
type: 'map',
map: 'converter_test_geo_2',
left: 10,
right: 20,
top: 30,
bottom: 40
}
]
});
expect(pointEquals(chart.convertToPixel({seriesIndex: 0}, [2000, 8000]), [10, 30])).toEqual(true);
expect(pointEquals(chart.convertFromPixel({seriesIndex: 0}, [10, 30]), [2000, 8000])).toEqual(true);
expect(pointEquals(chart.convertToPixel({seriesId: 'k2'}, [200, 800]), [10, 30])).toEqual(true);
expect(pointEquals(chart.convertFromPixel({seriesId: 'k2'}, [10, 30]), [200, 800])).toEqual(true);
});
it('cartesian', function () {
chart.setOption({
geo: [ // Should not affect grid converter.
{
map: 'converter_test_geo_1'
}
],
grid: [
{
id: 'g0',
left: 10,
right: '50%',
top: 30,
bottom: 40
},
{
id: 'g1',
left: '50%',
right: 20,
top: 30,
bottom: 40
}
],
xAxis: [
{
id: 'x0',
type: 'value',
min: -500,
max: 3000,
gridId: 'g0'
},
{
id: 'x1',
type: 'value',
min: -50,
max: 300,
gridId: 'g0'
},
{
id: 'x2',
type: 'value',
min: -50,
max: 300,
gridId: 'g1'
}
],
yAxis: [
{
id: 'y0',
type: 'value',
min: 6000,
max: 9000,
gridId: 'g0'
},
{
id: 'y1',
type: 'value',
inverse: true, // test inverse
min: 600,
max: 900,
gridId: 'g1'
}
],
series: [
{
id: 'k1',
type: 'scatter',
// left: 0,
// right: 0,
// top: 0,
// bottom: 0,
data: [[1000, 700]]
},
{
id: 'k2',
type: 'scatter',
// left: 0,
// right: 0,
// top: 0,
// bottom: 0,
data: [[100, 800]]
},
{
id: 'j1',
type: 'scatter',
// left: 0,
// right: 0,
// top: 0,
// bottom: 0,
data: [[100, 800]],
xAxisIndex: 1
},
{
id: 'i1',
type: 'scatter',
// left: 0,
// right: 0,
// top: 0,
// bottom: 0,
data: [],
xAxisId: 'x2',
yAxisId: 'y1'
}
]
});
const width = chart.getWidth();
const height = chart.getHeight();
expect(
pointEquals(chart.convertToPixel({seriesIndex: 1}, [-500, 6000]), [10, height - 40])
).toEqual(true);
expect(
pointEquals(chart.convertFromPixel({seriesIndex: 1}, [10, height - 40]), [-500, 6000])
).toEqual(true);
expect(
pointEquals(chart.convertToPixel({seriesId: 'i1'}, [300, 900]), [width - 20, height - 40])
).toEqual(true);
expect(
pointEquals(chart.convertFromPixel({seriesId: 'i1'}, [width - 20, height - 40]), [300, 900])
).toEqual(true);
expect(
pointEquals(chart.convertToPixel({xAxisIndex: 2, yAxisId: 'y1'}, [300, 900]), [width - 20, height - 40])
).toEqual(true);
expect(
pointEquals(chart.convertFromPixel({xAxisIndex: 2, yAxisId: 'y1'}, [width - 20, height - 40]), [300, 900])
).toEqual(true);
expect(
pointEquals(chart.convertToPixel({gridId: 'g1'}, [300, 900]), [width - 20, height - 40])
).toEqual(true);
expect(
pointEquals(chart.convertFromPixel({gridId: 'g1'}, [width - 20, height - 40]), [300, 900])
).toEqual(true);
expect(pointEquals(chart.convertToPixel({xAxisId: 'x0'}, 3000), width / 2)).toEqual(true);
expect(pointEquals(chart.convertFromPixel({xAxisId: 'x0'}, width / 2), 3000)).toEqual(true);
expect(pointEquals(chart.convertToPixel({yAxisIndex: 1}, 600), 30)).toEqual(true);
expect(pointEquals(chart.convertFromPixel({yAxisIndex: 1}, 30), 600)).toEqual(true);
});
it('graph', function () {
chart.setOption({
geo: [ // Should not affect graph converter.
{
map: 'converter_test_geo_1'
}
],
series: [
{
id: 'k1',
type: 'graph',
left: 10,
right: 20,
top: 30,
bottom: 40,
data: [
{x: 1000, y: 2000},
{x: 1000, y: 5000},
{x: 3000, y: 5000},
{x: 3000, y: 2000}
],
links: []
},
{
id: 'k2',
type: 'graph',
left: 10,
right: 20,
top: 30,
bottom: 40,
data: [
{x: 100, y: 200},
{x: 100, y: 500},
{x: 300, y: 500},
{x: 300, y: 200}
],
links: []
}
]
});
const width = chart.getWidth();
const height = chart.getHeight();
expect(
pointEquals(
chart.convertToPixel({seriesIndex: 0}, [2000, 3500]), [10 + (width - 30) / 2, 30 + (height - 70) / 2]
)
).toEqual(true);
expect(
pointEquals(
chart.convertFromPixel({seriesIndex: 0}, [10 + (width - 30) / 2, 30 + (height - 70) / 2]), [2000, 3500]
)
).toEqual(true);
expect(pointEquals(chart.convertToPixel({seriesId: 'k2'}, [100, 500]), [10, height - 40])).toEqual(true);
expect(pointEquals(chart.convertFromPixel({seriesId: 'k2'}, [10, height - 40]), [100, 500])).toEqual(true);
});
}); | the_stack |
import { ComponentPath, HierarchyPath, isPropertyPath, TargetPath } from './target-path';
import { IValueProxyFactory } from './value-proxy';
import * as easing from './easing';
import { BezierControlPoints } from './bezier';
import { CompactValueTypeArray } from '../data/utils/compact-value-type-array';
import { serializable } from '../data/decorators';
import { AnimCurve, RatioSampler } from './animation-curve';
import { QuatCurve, QuatInterpolationMode, RealCurve, RealInterpolationMode, RealKeyframeValue, TangentWeightMode } from '../curves';
import { assertIsTrue } from '../data/utils/asserts';
import { Track, TrackPath } from './tracks/track';
import { UntypedTrack } from './tracks/untyped-track';
import { warn, warnID } from '../platform';
import { RealTrack } from './tracks/real-track';
import { Color, lerp, Quat, Size, Vec2, Vec3, Vec4 } from '../math';
import { CubicSplineNumberValue, CubicSplineQuatValue, CubicSplineVec2Value, CubicSplineVec3Value, CubicSplineVec4Value } from './cubic-spline-value';
import { ColorTrack } from './tracks/color-track';
import { VectorTrack } from './tracks/vector-track';
import { QuatTrack } from './tracks/quat-track';
import { ObjectTrack } from './tracks/object-track';
import { SizeTrack } from './tracks/size-track';
import { EasingMethod } from '../curves/curve';
/**
* 表示曲线值,曲线值可以是任意类型,但必须符合插值方式的要求。
*/
export type LegacyCurveValue = any;
/**
* 表示曲线的目标对象。
*/
export type LegacyCurveTarget = Record<string, any>;
/**
* 内置帧时间渐变方式名称。
*/
export type LegacyEasingMethodName = keyof (typeof easing);
/**
* 帧时间渐变方式。可能为内置帧时间渐变方式的名称或贝塞尔控制点。
*/
export type LegacyEasingMethod = LegacyEasingMethodName | BezierControlPoints;
export type LegacyCompressedEasingMethods = Record<number, LegacyEasingMethod>;
export type LegacyLerpFunction<T = any> = (from: T, to: T, t: number, dt: number) => T;
export interface LegacyClipCurveData {
/**
* 曲线使用的时间轴。
* @see {AnimationClip.keys}
*/
keys: number;
/**
* 曲线值。曲线值的数量应和 `keys` 所引用时间轴的帧数相同。
*/
values: LegacyCurveValue[];
/**
* 曲线任意两帧时间的渐变方式。仅当 `easingMethods === undefined` 时本字段才生效。
*/
easingMethod?: LegacyEasingMethod;
/**
* 描述了每一帧时间到下一帧时间之间的渐变方式。
*/
easingMethods?: LegacyEasingMethod[] | LegacyCompressedEasingMethods;
/**
* 是否进行插值。
* @default true
*/
interpolate?: boolean;
/**
* For internal usage only.
*/
_arrayLength?: number;
}
export interface LegacyClipCurve {
commonTarget?: number;
modifiers: TargetPath[];
valueAdapter?: IValueProxyFactory;
data: LegacyClipCurveData;
}
export interface LegacyCommonTarget {
modifiers: TargetPath[];
valueAdapter?: IValueProxyFactory;
}
export type LegacyMaybeCompactCurve = Omit<LegacyClipCurve, 'data'> & {
data: Omit<LegacyClipCurveData, 'values'> & {
values: any[] | CompactValueTypeArray;
};
};
export type LegacyMaybeCompactKeys = Array<number[] | CompactValueTypeArray>;
export type LegacyRuntimeCurve = Pick<LegacyClipCurve, 'modifiers' | 'valueAdapter' | 'commonTarget'> & {
/**
* 属性曲线。
*/
curve: AnimCurve;
/**
* 曲线采样器。
*/
sampler: RatioSampler | null;
}
// interface ConvertMap<TValue, TTrack> {
// valueConstructor: Constructor<TValue>;
// trackConstructor: Constructor<TTrack>;
// properties: [keyof TValue, number][];
// }
// const VECTOR_LIKE_CURVE_CONVERT_TABLE = [
// {
// valueConstructor: Size,
// trackConstructor: SizeTrack,
// properties: [['width', 0], ['height', 1]],
// } as ConvertMap<Size, SizeTrack>,
// {
// valueConstructor: Color,
// trackConstructor: ColorTrack,
// properties: [['r', 0], ['g', 1], ['b', 2], ['a', 3]],
// } as ConvertMap<Color, ColorTrack>,
// ];
export class AnimationClipLegacyData {
constructor (duration: number) {
this._duration = duration;
}
get keys () {
return this._keys;
}
set keys (value) {
this._keys = value;
}
get curves () {
return this._curves;
}
set curves (value) {
this._curves = value;
delete this._runtimeCurves;
}
get commonTargets () {
return this._commonTargets;
}
set commonTargets (value) {
this._commonTargets = value;
}
/**
* 此动画的数据。
*/
get data () {
return this._data;
}
public getPropertyCurves (): readonly LegacyRuntimeCurve[] {
if (!this._runtimeCurves) {
this._createPropertyCurves();
}
return this._runtimeCurves!;
}
public toTracks () {
const newTracks: Track[] = [];
const {
keys: legacyKeys,
curves: legacyCurves,
commonTargets: legacyCommonTargets,
} = this;
const convertTrackPath = (track: Track, modifiers: TargetPath[], valueAdapter: IValueProxyFactory | undefined) => {
const trackPath = new TrackPath();
for (const modifier of modifiers) {
if (typeof modifier === 'string') {
trackPath.toProperty(modifier);
} else if (typeof modifier === 'number') {
trackPath.toElement(modifier);
} else if (modifier instanceof HierarchyPath) {
trackPath.toHierarchy(modifier.path);
} else if (modifier instanceof ComponentPath) {
trackPath.toComponent(modifier.component);
} else {
trackPath.toCustomized(modifier);
}
}
track.path = trackPath;
track.proxy = valueAdapter;
};
const untypedTracks = legacyCommonTargets.map((legacyCommonTarget) => {
const track = new UntypedTrack();
convertTrackPath(track, legacyCommonTarget.modifiers, legacyCommonTarget.valueAdapter);
newTracks.push(track);
return track;
});
for (const legacyCurve of legacyCurves) {
const legacyCurveData = legacyCurve.data;
const legacyValues = legacyCurveData.values;
if (legacyValues.length === 0) {
// Legacy clip did not record type info.
continue;
}
const legacyKeysIndex = legacyCurveData.keys;
// Rule: negative index means single frame.
const times = legacyKeysIndex < 0 ? [0.0] : legacyKeys[legacyCurveData.keys];
const firstValue = legacyValues[0];
// Rule: default to true.
const interpolate = legacyCurveData.interpolate ?? true;
// Rule: _arrayLength only used for morph target, internally.
assertIsTrue(typeof legacyCurveData._arrayLength !== 'number' || typeof firstValue === 'number');
const legacyEasingMethodConverter = new LegacyEasingMethodConverter(legacyCurveData, times.length);
const installPathAndSetter = (track: Track) => {
convertTrackPath(track, legacyCurve.modifiers, legacyCurve.valueAdapter);
};
let legacyCommonTargetCurve: RealCurve | undefined;
if (typeof legacyCurve.commonTarget === 'number') {
// Rule: common targets should only target Vectors/`Size`/`Color`.
if (!legacyValues.every((value) => typeof value === 'number')) {
warnID(3932);
continue;
}
// Rule: Each curve that has common target should be numeric curve and targets string property.
if (legacyCurve.valueAdapter || legacyCurve.modifiers.length !== 1 || typeof legacyCurve.modifiers[0] !== 'string') {
warnID(3933);
continue;
}
const propertyName = legacyCurve.modifiers[0];
const untypedTrack = untypedTracks[legacyCurve.commonTarget];
const { curve } = untypedTrack.addChannel(propertyName);
legacyCommonTargetCurve = curve;
}
const convertCurve = () => {
if (typeof firstValue === 'number') {
if (!legacyValues.every((value) => typeof value === 'number')) {
warnID(3934);
return;
}
let realCurve: RealCurve;
if (legacyCommonTargetCurve) {
realCurve = legacyCommonTargetCurve;
} else {
const track = new RealTrack();
installPathAndSetter(track);
newTracks.push(track);
realCurve = track.channel.curve;
}
const interpolationMethod = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
realCurve.assignSorted(times, (legacyValues as number[]).map(
(value) => ({ value, interpolationMode: interpolationMethod }),
));
legacyEasingMethodConverter.convert(realCurve);
return;
} else if (typeof firstValue === 'object') {
switch (true) {
default:
break;
case everyInstanceOf(legacyValues, Vec2):
case everyInstanceOf(legacyValues, Vec3):
case everyInstanceOf(legacyValues, Vec4): {
type Vec4plus = Vec4[];
type Vec3plus = (Vec3 | Vec4)[];
type Vec2plus = (Vec2 | Vec3 | Vec4)[];
const components = firstValue instanceof Vec2 ? 2 : firstValue instanceof Vec3 ? 3 : 4;
const track = new VectorTrack();
installPathAndSetter(track);
track.componentsCount = components;
const [{ curve: x }, { curve: y }, { curve: z }, { curve: w }] = track.channels();
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
const valueToFrame = (value: number): Partial<RealKeyframeValue> => ({ value, interpolationMode });
switch (components) {
case 4:
w.assignSorted(times, (legacyValues as Vec4plus).map((value) => valueToFrame(value.w)));
legacyEasingMethodConverter.convert(w);
// falls through
case 3:
z.assignSorted(times, (legacyValues as Vec3plus).map((value) => valueToFrame(value.z)));
legacyEasingMethodConverter.convert(z);
// falls through
default:
x.assignSorted(times, (legacyValues as Vec2plus).map((value) => valueToFrame(value.x)));
legacyEasingMethodConverter.convert(x);
y.assignSorted(times, (legacyValues as Vec2plus).map((value) => valueToFrame(value.y)));
legacyEasingMethodConverter.convert(y);
break;
}
newTracks.push(track);
return;
}
case everyInstanceOf(legacyValues, Quat): {
const track = new QuatTrack();
installPathAndSetter(track);
const interpolationMode = interpolate ? QuatInterpolationMode.SLERP : QuatInterpolationMode.CONSTANT;
track.channel.curve.assignSorted(times, (legacyValues as Quat[]).map((value) => ({
value: Quat.clone(value),
interpolationMode,
})));
legacyEasingMethodConverter.convertQuatCurve(track.channel.curve);
newTracks.push(track);
return;
}
case everyInstanceOf(legacyValues, Color): {
const track = new ColorTrack();
installPathAndSetter(track);
const [{ curve: r }, { curve: g }, { curve: b }, { curve: a }] = track.channels();
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
const valueToFrame = (value: number): Partial<RealKeyframeValue> => ({ value, interpolationMode });
r.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.r)));
legacyEasingMethodConverter.convert(r);
g.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.g)));
legacyEasingMethodConverter.convert(g);
b.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.b)));
legacyEasingMethodConverter.convert(b);
a.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.a)));
legacyEasingMethodConverter.convert(a);
newTracks.push(track);
return;
}
case everyInstanceOf(legacyValues, Size): {
const track = new SizeTrack();
installPathAndSetter(track);
const [{ curve: width }, { curve: height }] = track.channels();
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
const valueToFrame = (value: number): Partial<RealKeyframeValue> => ({ value, interpolationMode });
width.assignSorted(times, (legacyValues as Size[]).map((value) => valueToFrame(value.width)));
legacyEasingMethodConverter.convert(width);
height.assignSorted(times, (legacyValues as Size[]).map((value) => valueToFrame(value.height)));
legacyEasingMethodConverter.convert(height);
newTracks.push(track);
return;
}
case everyInstanceOf(legacyValues, CubicSplineNumberValue): {
assertIsTrue(legacyEasingMethodConverter.nil);
const track = new RealTrack();
installPathAndSetter(track);
const interpolationMode = interpolate ? RealInterpolationMode.CUBIC : RealInterpolationMode.CONSTANT;
track.channel.curve.assignSorted(times, (legacyValues as CubicSplineNumberValue[]).map((value) => ({
value: value.dataPoint,
leftTangent: value.inTangent,
rightTangent: value.outTangent,
interpolationMode,
})));
newTracks.push(track);
return;
}
case everyInstanceOf(legacyValues, CubicSplineVec2Value):
case everyInstanceOf(legacyValues, CubicSplineVec3Value):
case everyInstanceOf(legacyValues, CubicSplineVec4Value): {
assertIsTrue(legacyEasingMethodConverter.nil);
type Vec4plus = CubicSplineVec4Value[];
type Vec3plus = (CubicSplineVec3Value | CubicSplineVec4Value)[];
type Vec2plus = (CubicSplineVec2Value | CubicSplineVec3Value | CubicSplineVec4Value)[];
const components = firstValue instanceof CubicSplineVec2Value ? 2 : firstValue instanceof CubicSplineVec3Value ? 3 : 4;
const track = new VectorTrack();
installPathAndSetter(track);
track.componentsCount = components;
const [x, y, z, w] = track.channels();
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
const valueToFrame = (value: number, inTangent: number, outTangent: number): Partial<RealKeyframeValue> => ({
value,
leftTangent: inTangent,
rightTangent: outTangent,
interpolationMode,
});
switch (components) {
case 4:
w.curve.assignSorted(times, (legacyValues as Vec4plus).map(
(value) => valueToFrame(value.dataPoint.w, value.inTangent.w, value.outTangent.w),
));
// falls through
case 3:
z.curve.assignSorted(times, (legacyValues as Vec3plus).map(
(value) => valueToFrame(value.dataPoint.z, value.inTangent.z, value.outTangent.z),
));
// falls through
default:
x.curve.assignSorted(times, (legacyValues as Vec2plus).map(
(value) => valueToFrame(value.dataPoint.y, value.inTangent.y, value.outTangent.y),
));
y.curve.assignSorted(times, (legacyValues as Vec2plus).map(
(value) => valueToFrame(value.dataPoint.x, value.inTangent.x, value.outTangent.x),
));
break;
}
newTracks.push(track);
return;
}
case legacyValues.every((value) => value instanceof CubicSplineQuatValue): {
warnID(3935);
break;
}
} // End switch
}
const objectTrack = new ObjectTrack();
installPathAndSetter(objectTrack);
objectTrack.channel.curve.assignSorted(times, legacyValues);
newTracks.push(objectTrack);
};
convertCurve();
}
return newTracks;
}
private _keys: number[][] = [];
private _curves: LegacyClipCurve[] = [];
private _commonTargets: LegacyCommonTarget[] = [];
private _ratioSamplers: RatioSampler[] = [];
private _runtimeCurves?: LegacyRuntimeCurve[];
private _data: Uint8Array | null = null;
private _duration: number;
protected _createPropertyCurves () {
this._ratioSamplers = this._keys.map(
(keys) => new RatioSampler(
keys.map(
(key) => key / this._duration,
),
),
);
this._runtimeCurves = this._curves.map((targetCurve): LegacyRuntimeCurve => ({
curve: new AnimCurve(targetCurve.data, this._duration),
modifiers: targetCurve.modifiers,
valueAdapter: targetCurve.valueAdapter,
sampler: this._ratioSamplers[targetCurve.data.keys],
commonTarget: targetCurve.commonTarget,
}));
}
}
function everyInstanceOf<T> (array: unknown[], constructor: Constructor<T>): array is T[] {
return array.every((element) => element instanceof constructor);
}
// #region Legacy data structures prior to 1.2
export interface LegacyObjectCurveData {
[propertyName: string]: LegacyClipCurveData;
}
export interface LegacyComponentsCurveData {
[componentName: string]: LegacyObjectCurveData;
}
export interface LegacyNodeCurveData {
props?: LegacyObjectCurveData;
comps?: LegacyComponentsCurveData;
}
// #endregion
class LegacyEasingMethodConverter {
constructor (legacyCurveData: LegacyClipCurveData, keyframesCount: number) {
const { easingMethods } = legacyCurveData;
if (Array.isArray(easingMethods)) {
// Different
if (easingMethods.length === 0 && keyframesCount !== 0) {
// This shall not happen as specified in doc on legacy easing methods
// but it does in history project(see cocos-creator/3d-tasks/issues/#8468).
// This may be a promise breaking BUG between engine & Editor.
// Let's capture this case.
this._easingMethods = new Array(keyframesCount).fill(null);
} else {
this._easingMethods = easingMethods;
}
} else if (easingMethods === undefined) {
// Same
this._easingMethods = new Array(keyframesCount).fill(legacyCurveData.easingMethod);
} else {
// Compressed as record
this._easingMethods = Array.from({ length: keyframesCount }, (_, index) => easingMethods[index] ?? null);
}
}
get nil () {
return !this._easingMethods || this._easingMethods.every((easingMethod) => easingMethod === null || easingMethod === undefined);
}
public convert (curve: RealCurve) {
const { _easingMethods: easingMethods } = this;
if (!easingMethods) {
return;
}
const nKeyframes = curve.keyFramesCount;
if (curve.keyFramesCount < 2) {
return;
}
if (Array.isArray(easingMethods)) {
assertIsTrue(nKeyframes === easingMethods.length);
}
const iLastKeyframe = nKeyframes - 1;
for (let iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
const easingMethod = easingMethods[iKeyframe];
if (!easingMethod) {
continue;
}
if (Array.isArray(easingMethod)) {
// Time bezier points
timeBezierToTangents(
easingMethod,
curve.getKeyframeTime(iKeyframe),
curve.getKeyframeValue(iKeyframe),
curve.getKeyframeTime(iKeyframe + 1),
curve.getKeyframeValue(iKeyframe + 1),
);
} else {
applyLegacyEasingMethodName(
easingMethod,
curve,
iKeyframe,
);
}
}
}
public convertQuatCurve (curve: QuatCurve) {
const { _easingMethods: easingMethods } = this;
if (!easingMethods) {
return;
}
const nKeyframes = curve.keyFramesCount;
if (curve.keyFramesCount < 2) {
return;
}
if (Array.isArray(easingMethods)) {
assertIsTrue(nKeyframes === easingMethods.length);
}
const iLastKeyframe = nKeyframes - 1;
for (let iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
const easingMethod = easingMethods[iKeyframe];
if (!easingMethod) {
continue;
}
if (Array.isArray(easingMethod)) {
curve.getKeyframeValue(iKeyframe).easingMethod = easingMethod.slice() as BezierControlPoints;
} else {
applyLegacyEasingMethodNameIntoQuatCurve(
easingMethod,
curve,
iKeyframe,
);
}
}
}
private _easingMethods: Array<LegacyEasingMethod | null> | undefined;
}
/**
* @returns Inserted keyframes count.
*/
function applyLegacyEasingMethodName (
easingMethodName: LegacyEasingMethodName,
curve: RealCurve,
keyframeIndex: number,
) {
assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
assertIsTrue(easingMethodName in easingMethodNameMap);
const keyframeValue = curve.getKeyframeValue(keyframeIndex);
const easingMethod = easingMethodNameMap[easingMethodName];
if (easingMethod === EasingMethod.CONSTANT) {
keyframeValue.interpolationMode = RealInterpolationMode.CONSTANT;
} else {
keyframeValue.interpolationMode = RealInterpolationMode.LINEAR;
keyframeValue.easingMethod = easingMethod;
}
}
function applyLegacyEasingMethodNameIntoQuatCurve (
easingMethodName: LegacyEasingMethodName,
curve: QuatCurve,
keyframeIndex: number,
) {
assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
assertIsTrue(easingMethodName in easingMethodNameMap);
const keyframeValue = curve.getKeyframeValue(keyframeIndex);
const easingMethod = easingMethodNameMap[easingMethodName];
keyframeValue.easingMethod = easingMethod;
}
const easingMethodNameMap: Record<LegacyEasingMethodName, EasingMethod> = {
constant: EasingMethod.CONSTANT,
linear: EasingMethod.LINEAR,
quadIn: EasingMethod.QUAD_IN,
quadOut: EasingMethod.QUAD_OUT,
quadInOut: EasingMethod.QUAD_IN_OUT,
quadOutIn: EasingMethod.QUAD_OUT_IN,
cubicIn: EasingMethod.CUBIC_IN,
cubicOut: EasingMethod.CUBIC_OUT,
cubicInOut: EasingMethod.CUBIC_IN_OUT,
cubicOutIn: EasingMethod.CUBIC_OUT_IN,
quartIn: EasingMethod.QUART_IN,
quartOut: EasingMethod.QUART_OUT,
quartInOut: EasingMethod.QUART_IN_OUT,
quartOutIn: EasingMethod.QUART_OUT_IN,
quintIn: EasingMethod.QUINT_IN,
quintOut: EasingMethod.QUINT_OUT,
quintInOut: EasingMethod.QUINT_IN_OUT,
quintOutIn: EasingMethod.QUINT_OUT_IN,
sineIn: EasingMethod.SINE_IN,
sineOut: EasingMethod.SINE_OUT,
sineInOut: EasingMethod.SINE_IN_OUT,
sineOutIn: EasingMethod.SINE_OUT_IN,
expoIn: EasingMethod.EXPO_IN,
expoOut: EasingMethod.EXPO_OUT,
expoInOut: EasingMethod.EXPO_IN_OUT,
expoOutIn: EasingMethod.EXPO_OUT_IN,
circIn: EasingMethod.CIRC_IN,
circOut: EasingMethod.CIRC_OUT,
circInOut: EasingMethod.CIRC_IN_OUT,
circOutIn: EasingMethod.CIRC_OUT_IN,
elasticIn: EasingMethod.ELASTIC_IN,
elasticOut: EasingMethod.ELASTIC_OUT,
elasticInOut: EasingMethod.ELASTIC_IN_OUT,
elasticOutIn: EasingMethod.ELASTIC_OUT_IN,
backIn: EasingMethod.BACK_IN,
backOut: EasingMethod.BACK_OUT,
backInOut: EasingMethod.BACK_IN_OUT,
backOutIn: EasingMethod.BACK_OUT_IN,
bounceIn: EasingMethod.BOUNCE_IN,
bounceOut: EasingMethod.BOUNCE_OUT,
bounceInOut: EasingMethod.BOUNCE_IN_OUT,
bounceOutIn: EasingMethod.BOUNCE_OUT_IN,
smooth: EasingMethod.SMOOTH,
fade: EasingMethod.FADE,
};
/**
* Legacy curve uses time based bezier curve interpolation.
* That's, interpolate time 'x'(time ratio between two frames, eg.[0, 1])
* and then use the interpolated time to sample curve.
* Now we need to compute the the end tangent of previous frame and the start tangent of the next frame.
* @param timeBezierPoints Bezier points used for legacy time interpolation.
* @param previousTime Time of the previous keyframe.
* @param previousValue Value of the previous keyframe.
* @param nextTime Time of the next keyframe.
* @param nextValue Value of the next keyframe.
*/
export function timeBezierToTangents (
timeBezierPoints: BezierControlPoints,
previousTime: number,
previousKeyframe: RealKeyframeValue,
nextTime: number,
nextKeyframe: RealKeyframeValue,
) {
const [p1X, p1Y, p2X, p2Y] = timeBezierPoints;
const { value: previousValue } = previousKeyframe;
const { value: nextValue } = nextKeyframe;
const dValue = nextValue - previousValue;
const dTime = nextTime - previousTime;
const fx = 3 * dTime;
const fy = 3 * dValue;
const t1x = p1X * fx;
const t1y = p1Y * fy;
const t2x = (1.0 - p2X) * fx;
const t2y = (1.0 - p2Y) * fy;
const ONE_THIRD = 1.0 / 3.0;
const previousTangent = t1y / t1x;
const previousTangentWeight = Math.sqrt(t1x * t1x + t1y * t1y) * ONE_THIRD;
const nextTangent = t2y / t2x;
const nextTangentWeight = Math.sqrt(t2x * t2x + t2y * t2y) * ONE_THIRD;
previousKeyframe.interpolationMode = RealInterpolationMode.CUBIC;
previousKeyframe.tangentWeightMode = ensureRightTangentWeightMode(previousKeyframe.tangentWeightMode);
previousKeyframe.rightTangent = previousTangent;
previousKeyframe.rightTangentWeight = previousTangentWeight;
nextKeyframe.tangentWeightMode = ensureLeftTangentWeightMode(nextKeyframe.tangentWeightMode);
nextKeyframe.leftTangent = nextTangent;
nextKeyframe.leftTangentWeight = nextTangentWeight;
}
function ensureLeftTangentWeightMode (tangentWeightMode: TangentWeightMode) {
if (tangentWeightMode === TangentWeightMode.NONE) {
return TangentWeightMode.LEFT;
} else if (tangentWeightMode === TangentWeightMode.RIGHT) {
return TangentWeightMode.BOTH;
} else {
return tangentWeightMode;
}
}
function ensureRightTangentWeightMode (tangentWeightMode: TangentWeightMode) {
if (tangentWeightMode === TangentWeightMode.NONE) {
return TangentWeightMode.RIGHT;
} else if (tangentWeightMode === TangentWeightMode.LEFT) {
return TangentWeightMode.BOTH;
} else {
return tangentWeightMode;
}
}
// #region TODO: convert power easing method
// type Powers = [number, number, number, number];
// const POWERS_QUAD_IN: Powers = [0.0, 0.0, 1.0, 0.0]; // k * k
// const POWERS_QUAD_OUT: Powers = [0.0, 2.0, -1.0, 0.0]; // k * (2 - k)
// const POWERS_CUBIC_IN: Powers = [0.0, 0.0, 0.0, 1.0]; // k * k * k
// const POWERS_CUBIC_OUT: Powers = [0.0, 0.0, 0.0, 1.0]; // --k * k * k + 1
// const BACK_S = 1.70158;
// const POWERS_BACK_IN: Powers = [1.0, 0.0, -BACK_S, BACK_S + 1.0]; // k * k * ((s + 1) * k - s)
// const POWERS_BACK_OUT: Powers = [1.0, 0.0, BACK_S, BACK_S + 1.0]; // k * k * ((s + 1) * k - s)
// const POWERS_SMOOTH: Powers = [0.0, 0.0, 3.0, -2.0]; // k * k * (3 - 2 * k)
// function convertPowerMethod (curve: RealCurve, keyframeIndex: number, powers: Powers) {
// assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
// const nextKeyframeIndex = keyframeIndex + 1;
// powerToTangents(
// powers,
// curve.getKeyframeTime(keyframeIndex),
// curve.getKeyframeValue(keyframeIndex),
// curve.getKeyframeTime(nextKeyframeIndex),
// curve.getKeyframeValue(nextKeyframeIndex),
// );
// return 0;
// };
// function convertInOutPowersMethod (curve: RealCurve, keyframeIndex: number, inPowers: Powers, outPowers: Powers) {
// assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
// const nextKeyframeIndex = keyframeIndex + 1;
// const previousTime = curve.getKeyframeTime(keyframeIndex);
// const nextTime = curve.getKeyframeTime(nextKeyframeIndex);
// const previousKeyframeValue = curve.getKeyframeValue(keyframeIndex);
// const nextKeyframeValue = curve.getKeyframeValue(nextKeyframeIndex);
// const middleTime = previousTime + (nextTime - previousTime);
// const middleValue = previousKeyframeValue.value + (nextKeyframeValue.value - previousKeyframeValue.value);
// const middleKeyframeValue = curve.getKeyframeValue(curve.addKeyFrame(middleTime, middleValue));
// powerToTangents(
// inPowers,
// previousTime,
// previousKeyframeValue,
// middleTime,
// middleKeyframeValue,
// );
// powerToTangents(
// outPowers,
// middleTime,
// middleKeyframeValue,
// nextTime,
// nextKeyframeValue,
// );
// return 1;
// };
// function powerToTangents (
// [a, b, c, d]: [number, number, number, number],
// previousTime: number,
// previousKeyframe: RealKeyframeValue,
// nextTime: number,
// nextKeyframe: RealKeyframeValue,
// ) {
// const bernstein = powerToBernstein([a, b, c, d]);
// const { value: previousValue } = previousKeyframe;
// const { value: nextValue } = nextKeyframe;
// timeBezierToTangents(
// [???????],
// previousTime,
// previousValue,
// nextTime,
// nextValue,
// );
// }
// function powerToBernstein ([p0, p1, p2, p3]: [number, number, number, number]) {
// // https://stackoverflow.com/questions/33859199/convert-polynomial-curve-to-bezier-curve-control-points
// // https://blog.demofox.org/2016/12/08/evaluating-polynomials-with-the-gpu-texture-sampler/
// const m00 = p0;
// const m01 = p1 / 3.0;
// const m02 = p2 / 3.0;
// const m03 = p3;
// const m10 = m00 + m01;
// const m11 = m01 + m02;
// const m12 = m02 + m03;
// const m20 = m10 + m11;
// const m21 = m11 + m12;
// const m30 = m20 + m21;
// const bernstein = new Float64Array(4);
// bernstein[0] = m00;
// bernstein[1] = m10;
// bernstein[2] = m20;
// bernstein[3] = m30;
// return bernstein;
// }
// #endregion | the_stack |
import * as React from "react";
import { Logger, LogLevel } from "@pnp/logging";
import isEqual from "lodash/isEqual";
import filter from "lodash/filter";
import includes from "lodash/includes";
import concat from "lodash/concat";
import uniqBy from "lodash/uniqBy";
import sortBy from "lodash/sortBy";
import find from "lodash/find";
import cloneDeep from "lodash/cloneDeep";
import forEach from "lodash/forEach";
import { Pivot, PivotItem, SearchBox, CommandBarButton } from "office-ui-fabric-react";
import * as strings from "M365LPStrings";
import AssetDetailsCommands from "../Atoms/AssetDetailsCommands";
import AssetDetails from "./AssetDetails";
import AssetSearchPanel from "./AssetSearchPanel";
import { IAsset, ITechnology, IPlaylist, IMultilingualString, Asset } from "../../../common/models/Models";
import { CustomWebpartSource, SearchFields } from "../../../common/models/Enums";
export interface IAssetInfoProps {
editDisabled: boolean;
assets: IAsset[];
technologies: ITechnology[];
playlist: IPlaylist;
playlistDirty: (dirty: boolean) => void;
updatePlaylist: (playlist: IPlaylist, save: boolean) => void;
upsertAsset: (asset: IAsset) => Promise<string>;
translateAsset: (asset: IAsset) => IAsset;
}
export interface IAssetInfoState {
currentPivot: string;
editAsset: IAsset;
edit: boolean;
message: string;
success: boolean;
playlistChanged: boolean;
searchAsset: boolean;
searchValue: string;
searchResults: IAsset[];
}
export class AssetInfoState implements IAssetInfoState {
constructor(
public playlistChanged: boolean = false,
public editAsset: IAsset = null,
public edit: boolean = false,
public message: string = "",
public success: boolean = true,
public searchAsset: boolean = false,
public searchValue: string = "",
public searchResults: IAsset[] = null,
public currentPivot: string = "CurrentPlaylist"
) { }
}
export default class AssetInfo extends React.Component<IAssetInfoProps, IAssetInfoState> {
private LOG_SOURCE: string = "AssetInfo";
constructor(props) {
super(props);
this.state = new AssetInfoState();
}
public shouldComponentUpdate(nextProps: Readonly<IAssetInfoProps>, nextState: Readonly<IAssetInfoState>) {
if ((isEqual(nextState, this.state) && isEqual(nextProps, this.props)))
return false;
return true;
}
private moveAsset(array: string[], oldIndex, newIndex) {
try {
if (newIndex >= array.length) {
var k = newIndex - array.length + 1;
while (k--) {
array.push(undefined);
}
}
array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (moveAsset) - ${err}`, LogLevel.Error);
}
}
private moveAssetUp = (index: number) => {
try {
let playlist = cloneDeep(this.props.playlist);
this.moveAsset(playlist.Assets, index, index - 1);
this.props.updatePlaylist(playlist, true);
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (moveAssetUp) - ${err}`, LogLevel.Error);
}
}
private moveAssetDown = (index: number) => {
try {
let playlist = cloneDeep(this.props.playlist);
this.moveAsset(playlist.Assets, index, index + 1);
this.props.updatePlaylist(playlist, true);
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (moveAssetDown) - ${err}`, LogLevel.Error);
}
}
private removeAsset = (index: number) => {
try {
let playlist = cloneDeep(this.props.playlist);
playlist.Assets.splice(index, 1);
this.props.updatePlaylist(playlist, true);
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (removeAsset) - ${err}`, LogLevel.Error);
}
}
private doSearch = (searchValue: string): void => {
let searchResults: IAsset[] = [];
try {
if (searchValue.length > 0) {
//Search Assets
//Matching technologies and subjects
let technologies: string[] = [];
let subjects: string[] = [];
forEach(this.props.technologies, (t) => {
if (t.Name && t.Name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1) {
technologies.push(t.Id);
}
if (t.Subjects && t.Subjects.length > 0) {
forEach(t.Subjects, (s) => {
if (s.Name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1) {
subjects.push(s.Id);
}
});
}
});
let spTech = filter(this.props.assets, o => {
return (includes(technologies, o.TechnologyId));
});
searchResults = concat(searchResults, spTech);
let spSub = filter(this.props.assets, o => {
return (includes(subjects, o.SubjectId));
});
searchResults = concat(searchResults, spSub);
//Matching search fields
for (let i = 0; i < SearchFields.length; i++) {
let sp = filter(this.props.assets, o => {
if (o[SearchFields[i]] == undefined) return false;
let fieldValue: string = null;
if (o[SearchFields[i]] instanceof Array)
fieldValue = (o[SearchFields[i]] as IMultilingualString[])[0].Text;
else
fieldValue = o[SearchFields[i]];
return (fieldValue.toLowerCase().indexOf(searchValue.toLowerCase()) > -1);
});
searchResults = concat(searchResults, sp);
}
searchResults = uniqBy(searchResults, (r) => { return r.Id; });
searchResults = sortBy(searchResults, (r) => {
let title = (r.Title instanceof Array) ? (r.Title as IMultilingualString[])[0].Text : r.Title as string;
return title.toLowerCase();
});
}
this.setState({
searchValue: searchValue,
searchResults: searchResults,
currentPivot: "SearchResults"
});
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (doSearch) - ${err}`, LogLevel.Error);
}
}
private insertAsset = (assetId: string) => {
try {
let playlist = cloneDeep(this.props.playlist);
playlist.Assets.push(assetId);
this.props.updatePlaylist(playlist, true);
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (insertAsset) - ${err}`, LogLevel.Error);
}
}
private upsertAsset = async (asset: IAsset): Promise<boolean> => {
try {
let newAsset = (asset.Id === "0");
if (newAsset)
this.props.playlistDirty(true);
let assetResult = await this.props.upsertAsset(asset);
let message: string = "";
let success: boolean = true;
if (assetResult !== "0") {
if (newAsset) {
this.insertAsset(assetResult);
}
//message = strings.PlaylistEditAssetSavedMessage;
} else {
if (newAsset)
this.props.playlistDirty(false);
message = strings.PlaylistEditAssetSaveFailedMessage;
success = false;
}
this.setState({
message: message,
success: success
}, () => {
if (this.state.message.length > 0) {
//Auto dismiss message
window.setTimeout(() => {
this.setState({
message: "",
success: true
});
}, 5000);
}
});
return success;
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (upsertAsset) - ${err}`, LogLevel.Error);
return false;
}
}
private selectSearchAsset = async (assets: string[]) => {
try {
if (assets && assets.length > 0) {
let playlist = cloneDeep(this.props.playlist);
playlist.Assets = playlist.Assets.concat(assets);
this.props.updatePlaylist(playlist, true);
this.closeSearch();
}
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (selectSearchAsset) - ${err}`, LogLevel.Error);
}
}
private closeSearch = () => {
this.setState({
searchValue: "",
searchResults: [],
searchAsset: false,
currentPivot: "CurrentPlaylist"
});
}
public render(): React.ReactElement<IAssetInfoProps> {
try {
return (
<div data-component={this.LOG_SOURCE}>
{!this.props.editDisabled &&
<div className="cmdbar-beta">
<CommandBarButton
text={strings.PlaylistEditAssetNewLabel}
iconProps={{ iconName: "Add" }}
disabled={(this.props.playlist.Id === "0")}
onClick={() => this.setState({ editAsset: new Asset(), edit: true })}
/>
<SearchBox
placeholder={strings.AssetSearchPlaceHolderLabel}
onSearch={this.doSearch}
onClear={() => { this.doSearch(""); }}
/>
</div>
}
<Pivot selectedKey={this.state.currentPivot} onLinkClick={(i: PivotItem) => { this.setState({ currentPivot: i.props.itemKey }); }}>
<PivotItem headerText={strings.HeaderPlaylistPanelCurrentPlaylistLabel} itemKey="CurrentPlaylist" key="CurrentPlaylist">
{(this.state.editAsset && this.state.editAsset.Id === "0") &&
<AssetDetails
technologies={this.props.technologies}
asset={this.state.editAsset}
cancel={() => { this.setState({ editAsset: null, edit: false }); }}
save={this.upsertAsset}
edit={true}
/>
}
{this.props.playlist.Assets && this.props.playlist.Assets.length > 0 && this.props.playlist.Assets.map((a, index) => {
let asset = cloneDeep(find(this.props.assets, { Id: a }));
if (asset.Source !== CustomWebpartSource.Tenant)
asset = this.props.translateAsset(asset);
return (
<div className="learningwrapper">
<AssetDetailsCommands
assetIndex={index}
assetTotal={this.props.playlist.Assets.length - 1}
assetTitle={(asset.Title instanceof Array) ? (asset.Title as IMultilingualString[])[0].Text : asset.Title as string}
editDisabled={this.props.editDisabled || (asset && asset.Source !== CustomWebpartSource.Tenant) || (this.state.edit)}
allDisabled={this.props.editDisabled}
edit={() => { this.setState({ editAsset: asset, edit: true }); }}
moveUp={() => { this.moveAssetUp(index); }}
moveDown={() => { this.moveAssetDown(index); }}
remove={() => { this.removeAsset(index); }}
select={() => { this.setState({ editAsset: (this.state.editAsset === null) ? asset : null, edit: false }); }}
/>
{this.state.editAsset && (this.state.editAsset.Id === asset.Id) &&
<AssetDetails
technologies={this.props.technologies}
asset={asset}
cancel={() => { this.setState({ editAsset: null, edit: false }); }}
save={this.upsertAsset}
edit={this.state.edit}
/>
}
</div>
);
})}
</PivotItem>
{!this.props.editDisabled && (this.state.searchValue && this.state.searchValue.length > 0) &&
<PivotItem headerText="Search Results" itemKey="SearchResults" key="SearchResults" >
<AssetSearchPanel
allTechnologies={this.props.technologies}
searchResults={this.state.searchResults}
loadSearchResult={this.selectSearchAsset}
/>
</PivotItem>
}
</Pivot>
</div>
);
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (render) - ${err}`, LogLevel.Error);
return null;
}
}
} | the_stack |
import { join } from 'aurelia-path';
import { PLATFORM } from 'aurelia-pal';
import deepExtend from './deep-extend';
import { WindowInfo } from './window-info';
export class Configuration {
private environment: string = 'default';
private environments: string[] | null = null;
private directory: string = 'config';
private config_file: string = 'config.json';
private cascade_mode: boolean = true;
private base_path_mode: boolean = false;
private window: WindowInfo;
private _config_object: {} | any = {};
private _config_merge_object: {} | any = {};
constructor() {
// Setup the window object with the current browser window information
this.window = new WindowInfo();
this.window.hostName = PLATFORM.location.hostname;
this.window.port = PLATFORM.location.port;
// Only sets the pathname when its not '' or '/'
if (PLATFORM.location.pathname && PLATFORM.location.pathname.length > 1) {
this.window.pathName = PLATFORM.location.pathname;
}
}
/**
* Set Directory
*
* Sets the location to look for the config file
*
* @param path
*/
setDirectory(path: string) {
this.directory = path;
}
/**
* Set Config
*
* Sets the filename to look for in the defined directory
*
* @param name
*/
setConfig(name: string) {
this.config_file = name;
}
/**
* Set Environment
*
* Changes the environment value
*
* @param environment
*/
setEnvironment(environment: string) {
this.environment = environment;
}
/**
* Set Environments
*
* Specify multiple environment domains to allow for
* dynamic environment switching.
*
* @param environments
*/
setEnvironments(environments: any = null) {
if (environments !== null) {
this.environments = environments;
// Check the hostname value and determine our environment
this.check();
}
}
/**
* Set Cascade Mode
*
* By default if a environment config value is not found, it will
* go looking up the config file to find it (a la inheritance style). Sometimes
* you just want a config value from a specific environment and nowhere else
* use this to disabled this functionality
*
* @param bool
*/
setCascadeMode(bool: boolean = true) {
this.cascade_mode = bool;
}
/**
* Used to override default window information during contruction.
* Should only be used during unit testing, no need to set it up in normal
* operation
*
* @param bool
*/
setWindow(window: WindowInfo) {
this.window = window;
}
/**
* Set Path Base Mode
*
* If you have several app on the same domain, you can emable base path mode to
* use window.location.pathname to help determine your environment. This would
* help a lot in scenarios where you have :
* http://mydomain.com/dev/, http://mydomain.com/qa/, http://mydomain.com/prod/
* That was you can have different config depending where your app is deployed.
*
* @param bool
*/
setBasePathMode(bool: boolean = true) {
this.base_path_mode = bool;
}
/**
* Get Config
* Returns the entire configuration object pulled and parsed from file
*
* @returns {V}
*/
get obj() {
return this._config_object;
}
/**
* Get Config
*
* Get the config file name
*
* @returns {V}
*/
get config() {
return this.config_file;
}
/**
* Is
*
* A method for determining if the current environment
* equals that of the supplied environment value*
* @param environment
* @returns {boolean}
*/
is(environment: string) {
return environment === this.environment;
}
/**
* Check
* Looks for a match of the hostName to any of the domain
* values specified during the configuration bootstrapping
* phase of Aurelia.
*
*/
check() {
let hostname = this.window.hostName;
if (this.window.port != '') {
hostname += ':' + this.window.port;
}
if (this.base_path_mode) {
hostname += this.window.pathName;
}
// Check we have environments we can loop
if (this.environments) {
// Loop over supplied environments
for (let env in this.environments) {
// Get environment hostnames
let hostnames = this.environments[env];
// Make sure we have hostnames
if (hostnames) {
// Loop the hostnames
for (let host of hostnames) {
if (hostname.search('(?:^|W)' + host + '(?:$|W)') !== -1) {
this.setEnvironment(env);
// We have successfully found an environment, stop searching
return;
}
}
}
}
}
}
/**
* Environment Enabled
* A handy method for determining if we are using the default
* environment or have another specified like; staging
*
* @returns {boolean}
*/
environmentEnabled() {
return !(this.environment === 'default' || this.environment === '' || !this.environment);
}
/**
* Environment Exists
* Checks if the environment section actually exists within
* the configuration file or defaults to default
*
* @returns {boolean}
*/
environmentExists() {
return this.environment in this.obj;
}
/**
* GetDictValue
* Gets a value from a dict in an arbitrary depth or throws
* an error, if the key does not exist
*
* @param baseObject
* @param key
* @returns {*}
*/
getDictValue(baseObject: {} | any, key: string) {
let splitKey = key.split('.');
let currentObject = baseObject;
splitKey.forEach(key => {
if (currentObject[key]) {
currentObject = currentObject[key];
} else {
throw 'Key ' + key + ' not found';
}
});
return currentObject;
}
/**
* Get
* Gets a configuration value from the main config object
* with support for a default value if nothing found
*
* @param key
* @param defaultValue
* @returns {*}
*/
get(key: string, defaultValue: any = null) {
// By default return the default value
let returnVal = defaultValue;
// Singular non-namespaced value
if (key.indexOf('.') === -1) {
// Using default environment
if (!this.environmentEnabled()) {
return this.obj[key] ? this.obj[key] : defaultValue;
}
if (this.environmentEnabled()) {
// Value exists in environment
if (this.environmentExists() && this.obj[this.environment][key]) {
returnVal = this.obj[this.environment][key];
// Get default value from non-namespaced section if enabled
} else if (this.cascade_mode && this.obj[key]) {
returnVal = this.obj[key];
}
return returnVal;
}
} else {
// nested key and environment is enabled
if (this.environmentEnabled()) {
if (this.environmentExists()) {
try {
return this.getDictValue(this.obj[this.environment], key);
} catch {
// nested key, env exists, key is not in environment
if (this.cascade_mode) {
try {
return this.getDictValue(this.obj, key);
} catch {}
}
}
}
} else {
try {
return this.getDictValue(this.obj, key);
} catch {}
}
}
return returnVal;
}
/**
* Set
* Saves a config value temporarily
*
* @param key
* @param val
*/
set(key: string, val: string) {
if (key.indexOf('.') === -1) {
this.obj[key] = val;
} else {
let splitKey = key.split('.');
let parent = splitKey[0];
let child = splitKey[1];
if (this.obj[parent] === undefined) {
this.obj[parent] = {};
}
this.obj[parent][child] = val;
}
}
/**
* Merge
*
* Allows you to merge in configuration options.
* This method might be used to merge in server-loaded
* configuration options with local ones.
*
* @param obj
*
*/
merge(obj: {} | any) {
let currentConfig = this._config_object;
this._config_object = deepExtend(currentConfig, obj);
}
/**
* Lazy Merge
*
* Allows you to merge in configuration options.
* This method might be used to merge in server-loaded
* configuration options with local ones. The merge
* occurs after the config has been loaded.
*
* @param obj
*
*/
lazyMerge(obj: {} | any) {
let currentMergeConfig = this._config_merge_object || {};
this._config_merge_object = deepExtend(currentMergeConfig, obj);
}
/**
* Set All
* Sets and overwrites the entire configuration object
* used internally, but also can be used to set the configuration
* from outside of the usual JSON loading logic.
*
* @param obj
*/
setAll(obj: {} | any) {
this._config_object = obj;
}
/**
* Get All
* Returns all configuration options as an object
*
* @returns {V}
*/
getAll() {
return this.obj;
}
/**
* Load Config
* Loads the configuration file from specified location,
* merges in any overrides, then returns a Promise.
*
* @returns {Promise}
*/
loadConfig() {
return this.loadConfigFile(join(this.directory, this.config), (data: string) =>
this.setAll(data),
).then(() => {
if (this._config_merge_object) {
this.merge(this._config_merge_object);
this._config_merge_object = null;
}
});
}
/**
* Load Config File
* Loads the configuration file from the specified location
* and then returns a Promise.
*
* @returns {Promise}
*/
loadConfigFile(path: string, action: Function) {
return new Promise((resolve, reject) => {
let pathClosure = path.toString();
let xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('application/json');
}
xhr.open('GET', pathClosure, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
let data = JSON.parse(this.responseText);
action(data);
resolve(data);
}
};
xhr.onloadend = function() {
if (xhr.status == 404) {
reject('Configuration file could not be found: ' + path);
}
};
xhr.onerror = function() {
reject(`Configuration file could not be found or loaded: ${pathClosure}`);
};
xhr.send(null);
});
}
/**
* Merge Config File
*
* Allows you to merge in configuration options from a file.
* This method might be used to merge in server-loaded
* configuration options with local ones.
*
* @param path The path to the config file to load.
* @param optional When true, errors encountered while loading the config file will be ignored.
*
*/
mergeConfigFile(path: string, optional: boolean) {
return new Promise((resolve, reject) => {
this.loadConfigFile(path, (data: {} | any) => {
this.lazyMerge(data);
resolve();
}).catch(error => {
if (optional === true) {
resolve();
} else {
reject(error);
}
});
});
}
} | the_stack |
import { ClassSchema, getClassSchema, PropertySchema } from './model';
import { TypeConverterCompiler } from './serializer-compiler';
import { ClassType } from '@deepkit/core';
import {
getClassToXFunction,
getPartialClassToXFunction,
getPartialXToClassFunction,
getPropertyClassToXFunction,
getPropertyXtoClassFunction,
getXToClassFunction,
JitConverterOptions,
resolvePropertySchema
} from './jit';
import { AnyEntity, ExtractClassType, PlainOrFullEntityFromClassTypeOrSchema } from './utils';
import { validate, ValidationFailed } from './validation';
import { binaryTypes, Types } from './types';
type CompilerTypes = Types | 'undefined' | 'null';
export class SerializerCompilers {
public compilers = new Map<string, TypeConverterCompiler>();
constructor(public serializer: Serializer, public parent?: SerializerCompilers) {
}
append(type: CompilerTypes, compiler: TypeConverterCompiler) {
const old = this.get(type);
this.compilers.set(type, (property, compilerState) => {
if (compilerState.ended) return;
if (old) {
old(property, compilerState);
if (compilerState.ended) return;
compiler(property, compilerState);
return;
}
const parent = this.parent?.get(type);
if (parent) {
parent(property, compilerState);
if (compilerState.ended) return;
compiler(property, compilerState);
} else {
if (compilerState.ended) return;
compiler(property, compilerState);
return;
}
});
}
prepend(type: CompilerTypes, compiler: TypeConverterCompiler) {
const old = this.get(type);
this.compilers.set(type, (property, compilerState) => {
compiler(property, compilerState);
if (compilerState.ended) return;
if (old) {
old(property, compilerState);
return;
}
const parent = this.parent?.get(type);
if (!parent) {
if (compilerState.ended) return;
compiler(property, compilerState);
return;
}
parent(property, compilerState);
});
}
/**
* Registers a new compiler template for a certain type in certain direction
* (for example: plain to class or class to plain).
*
* Note: Don't handle isArray/isMap/isPartial or isOptional at `property` as those are already handled before
* your compiler code is called. Focus on marshalling the given type as fast and clear as possible.
* The value you can access via `accessor` is at this stage never undefined and never null.
*
* Note: When you come from `class` to x (fromClass.register) then values additionally are
* guaranteed to have certain value types since the TS system enforces it.
* If a user overwrites with `as any` its not our business to convert them implicitly.
*
* Warning: Context is shared across types, so make sure either your assigned names are unique or generate new variable
* name using `reserveVariable`.
*
* INTERNAL WARNING: Coming from `plain` to `x` the property values usually come from user input which makes
* it necessary to check the type and convert it if necessary. This is extremely important to not
* introduce security issues. Serializing from plain to your target format is made by calling first jsonSerializer.deserialize()
* and then yourSerializer.serialize() with the result, deepkit/type is fast enough to buy this convenience
* (of not having to declare too many compiler templates).
*/
register(type: CompilerTypes, compiler: TypeConverterCompiler) {
this.compilers.set(type, compiler);
}
/**
* Removes a compiler. If the serializer has a parent, then parent's serializer code is used.
* Use `noop` to remove an existing serializer code.
*/
reset(type: CompilerTypes) {
this.compilers.delete(type);
}
/**
* Sets a noop compiler, basically disabling serialization for this type.
*/
noop(type: CompilerTypes) {
this.compilers.set(type, (property, state) => {
state.addSetter(`${state.accessor}`);
});
}
/**
* Adds a compiler template all typed arrays (Uint8Array, ...) and ArrayBuffer.
*/
registerForBinary(compiler: TypeConverterCompiler) {
for (const type of binaryTypes) this.register(type, compiler);
}
fork(serializer: Serializer) {
return new SerializerCompilers(serializer, this);
}
get(type: CompilerTypes): TypeConverterCompiler | undefined {
const t = this.compilers.get(type);
if (t) return t;
return this.parent ? this.parent.get(type) : undefined;
}
has(type: CompilerTypes): boolean {
if (this.compilers.has(type)) return true;
return this.parent ? this.parent.has(type) : false;
}
}
export class Serializer {
/**
* Serializer compiler for serializing from the serializer format to the class instance. Used in .for().deserialize().
*/
public toClass = new SerializerCompilers(this);
/**
* Serializer compiler for serializing from the class instance to the serializer format. Used in .for().serialize().
*/
public fromClass = new SerializerCompilers(this);
public toClassSymbol: symbol;
public fromClassSymbol: symbol;
public partialToClassSymbol: symbol;
public partialFromClassSymbol: symbol;
constructor(
public readonly name: string
) {
this.toClassSymbol = Symbol('toClass-' + name);
this.fromClassSymbol = Symbol('fromClass-' + name);
this.partialToClassSymbol = Symbol('partialToClass-' + name);
this.partialFromClassSymbol = Symbol('partialFromClass-' + name);
}
fork(name: string): ClassType<Serializer> {
const self = this;
abstract class Res extends Serializer {
constructor() {
super(name);
this.toClass = self.toClass.fork(this);
this.fromClass = self.fromClass.fork(this);
}
}
return Res as any;
}
public for<T extends ClassType | ClassSchema>(schemaOrType: T): ScopedSerializer<ClassSchema<ExtractClassType<T>>> {
return new ScopedSerializer(this, getClassSchema(schemaOrType));
}
/**
* Serializes given class instance value to the serializer format.
*/
serializeProperty(property: PropertySchema, value: any): any {
return getPropertyClassToXFunction(property, this)(value);
}
/**
* Converts serialized value to class type.
*/
deserializeProperty(property: PropertySchema, value: any): any {
return getPropertyXtoClassFunction(property, this)(value);
}
/**
* Converts given serialized data to the class instance.
*/
deserializeMethodResult(property: PropertySchema, value: any): any {
return getPropertyXtoClassFunction(property, this)(value);
}
}
type FirstParameter<T> = T extends ((a: infer A) => any) ? A : never;
export class ScopedSerializer<T extends ClassSchema> {
protected _serialize?: (instance: ExtractClassType<T>, options?: JitConverterOptions) => any = undefined;
protected _deserialize?: (data: any, options?: JitConverterOptions, parents?: any[]) => ExtractClassType<T> = undefined;
protected _partialSerialize?: (instance: { [name: string]: any }, options?: JitConverterOptions) => any = undefined;
protected _partialDeserialize?: <P extends { [name: string]: any }>(
data: P,
options?: JitConverterOptions
) => Pick<ExtractClassType<T>, keyof P> = undefined;
constructor(public readonly serializer: Serializer, protected schema: T) {
}
from<S extends Serializer, SC extends ReturnType<S['for']>>(serializer: S, ...args: Parameters<SC['deserialize']>): ReturnType<this['serialize']> {
return this.serialize((serializer.for(this.schema).deserialize as any)(...args)) as any;
}
to<S extends Serializer, SC extends ReturnType<S['for']>>(serializer: S, ...args: Parameters<this['deserialize']>): ReturnType<SC['serialize']> {
return serializer.for(this.schema).serialize((this.deserialize as any)(...args)) as any;
}
fromPartial<S extends Serializer, SC extends ReturnType<S['for']>>(serializer: S, a: FirstParameter<ReturnType<S['for']>['partialDeserialize']>, options?: JitConverterOptions) {
return this.partialSerialize(serializer.for(this.schema).partialDeserialize(a, options));
}
toPartial<S extends Serializer, SC extends ReturnType<S['for']>, A extends FirstParameter<this['partialDeserialize']>>(serializer: S, a: A): ReturnType<SC['partialSerialize']> {
return serializer.for(this.schema).partialSerialize((this.partialDeserialize as any)(a)) as any;
}
fromPatch<S extends Serializer>(serializer: S, a: FirstParameter<ReturnType<S['for']>['patchDeserialize']>, options?: JitConverterOptions) {
return this.patchSerialize(serializer.for(this.schema).patchDeserialize(a, options));
}
toPatch<S extends Serializer, SC extends ReturnType<S['for']>>(serializer: S, ...args: Parameters<this['patchDeserialize']>) {
return serializer.for(this.schema).patchSerialize((this.patchDeserialize as any)(...args));
}
/**
* Serializes given class instance to the serialization format.
* -> class to serializer.
*/
serialize(instance: ExtractClassType<T>, options?: JitConverterOptions): any {
if (!this._serialize) this._serialize = getClassToXFunction(this.schema, this.serializer);
return this._serialize(instance, options);
}
/**
* Same as `deserialize` but with validation after creating the class instance.
*
* ```typescript
* try {
* const entity = jsonSerializer.for(MyEntity).validatedDeserialize({field1: 'value'});
* entity instanceof MyEntity; //true
* } catch (error) {
* if (error instanceof ValidationFailed) {
* //handle that case.
* }
* }
* ```
* @throws ValidationFailed
*/
validatedDeserialize(
data: PlainOrFullEntityFromClassTypeOrSchema<T>,
options?: JitConverterOptions
): ExtractClassType<T> {
if (!this._deserialize) this._deserialize = getXToClassFunction(this.schema, this.serializer);
const item = this._deserialize(data, options);
const errors = validate(this.schema, item);
if (errors.length) throw new ValidationFailed(errors);
return item;
}
/**
* Converts given data in form of this serialization format to the target (default JS primitive/class) type.
* -> serializer to class.
*/
deserialize(
data: PlainOrFullEntityFromClassTypeOrSchema<T>,
options?: JitConverterOptions,
parents?: any[]
): ExtractClassType<T> {
if (!this._deserialize) this._deserialize = getXToClassFunction(this.schema, this.serializer);
return this._deserialize(data, options, parents);
}
/**
* Serialized one property value from class instance to serialization target.
*
* Property name is either a property name or a deep path (e.g. config.value)
*/
serializeProperty(name: (keyof ExtractClassType<T> & string) | string, value: any): any {
const property = this.schema.getPropertiesMap().get(name) ?? resolvePropertySchema(this.schema, name);
return getPropertyClassToXFunction(property, this.serializer)(value);
}
/**
* Converts given data in form of this serialization format to the target (default JS primitive/class) type.
*
* Property name is either a property name or a deep path (e.g. config.value)
*/
deserializeProperty(name: (keyof ExtractClassType<T> & string) | string, value: any) {
const property = this.schema.getPropertiesMap().get(name) ?? resolvePropertySchema(this.schema, name);
return getPropertyXtoClassFunction(property, this.serializer)(value);
}
serializeMethodArgument(methodName: string, property: number, value: any): ReturnType<this['serializeProperty']> {
return getPropertyClassToXFunction(this.schema.getMethodProperties(methodName)[property], this.serializer)(value);
}
deserializeMethodArgument(methodName: string, property: number, value: any) {
return getPropertyXtoClassFunction(this.schema.getMethodProperties(methodName)[property], this.serializer)(value);
}
serializeMethodResult(methodName: string, value: any): ReturnType<this['serializeProperty']> {
return getPropertyClassToXFunction(this.schema.getMethod(methodName), this.serializer)(value);
}
deserializeMethodResult(methodName: string, value: any) {
return getPropertyXtoClassFunction(this.schema.getMethod(methodName), this.serializer)(value);
}
/**
* Serialized a partial instance to the serialization format.
*/
partialSerialize<R extends { [name: string]: any }>(
data: R,
options?: JitConverterOptions
): AnyEntity<R> {
if (!this._partialSerialize) this._partialSerialize = getPartialClassToXFunction(this.schema, this.serializer);
return this._partialSerialize(data, options);
}
/**
* Converts data in form of this serialization format to the same partial target (default JS primitive/class) type.
*/
partialDeserialize<P extends { [name: string]: any }>(
data: P,
options?: JitConverterOptions
): Pick<ExtractClassType<T>, keyof P> {
if (!this._partialDeserialize) this._partialDeserialize = getPartialXToClassFunction(this.schema, this.serializer);
return this._partialDeserialize(data, options);
}
public patchDeserialize<R extends { [name: string]: any }>(
partial: R,
options?: JitConverterOptions
): { [F in keyof R]?: any } {
const result: Partial<{ [F in keyof R]: any }> = {};
for (const i in partial) {
if (!partial.hasOwnProperty(i)) continue;
const property = this.schema.getPropertiesMap().get(i) ?? resolvePropertySchema(this.schema, i);
result[i] = getPropertyXtoClassFunction(property, this.serializer)(partial[i], options?.parents ?? [], options);
}
return result;
}
public patchSerialize<T, R extends object>(
partial: R,
options?: JitConverterOptions
): { [F in keyof R]?: any } {
const result: Partial<{ [F in keyof R]: any }> = {};
for (const i in partial) {
if (!partial.hasOwnProperty(i)) continue;
const property = this.schema.getPropertiesMap().get(i) ?? resolvePropertySchema(this.schema, i);
result[i] = getPropertyClassToXFunction(property, this.serializer)(partial[i], options);
}
return result;
}
}
export const emptySerializer = new class extends Serializer {
constructor() {
super('empty');
}
}; | the_stack |
import { RepositoryLocationLoadStatus, InstigationType, InstigationStatus, PipelineRunStatus, InstigationTickStatus } from "./../../types/globalTypes";
// ====================================================
// GraphQL query operation: InstanceSensorsQuery
// ====================================================
export interface InstanceSensorsQuery_instance_daemonHealth_allDaemonStatuses_lastHeartbeatErrors_cause {
__typename: "PythonError";
message: string;
stack: string[];
}
export interface InstanceSensorsQuery_instance_daemonHealth_allDaemonStatuses_lastHeartbeatErrors {
__typename: "PythonError";
message: string;
stack: string[];
cause: InstanceSensorsQuery_instance_daemonHealth_allDaemonStatuses_lastHeartbeatErrors_cause | null;
}
export interface InstanceSensorsQuery_instance_daemonHealth_allDaemonStatuses {
__typename: "DaemonStatus";
id: string;
daemonType: string;
required: boolean;
healthy: boolean | null;
lastHeartbeatErrors: InstanceSensorsQuery_instance_daemonHealth_allDaemonStatuses_lastHeartbeatErrors[];
lastHeartbeatTime: number | null;
}
export interface InstanceSensorsQuery_instance_daemonHealth {
__typename: "DaemonHealth";
id: string;
allDaemonStatuses: InstanceSensorsQuery_instance_daemonHealth_allDaemonStatuses[];
}
export interface InstanceSensorsQuery_instance {
__typename: "Instance";
daemonHealth: InstanceSensorsQuery_instance_daemonHealth;
}
export interface InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_displayMetadata {
__typename: "RepositoryMetadata";
key: string;
value: string;
}
export interface InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_locationOrLoadError_RepositoryLocation {
__typename: "RepositoryLocation";
id: string;
isReloadSupported: boolean;
serverId: string | null;
name: string;
}
export interface InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_locationOrLoadError_PythonError {
__typename: "PythonError";
message: string;
}
export type InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_locationOrLoadError = InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_locationOrLoadError_RepositoryLocation | InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_locationOrLoadError_PythonError;
export interface InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries {
__typename: "WorkspaceLocationEntry";
id: string;
name: string;
loadStatus: RepositoryLocationLoadStatus;
displayMetadata: InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_displayMetadata[];
updatedTimestamp: number;
locationOrLoadError: InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries_locationOrLoadError | null;
}
export interface InstanceSensorsQuery_workspaceOrError_Workspace {
__typename: "Workspace";
locationEntries: InstanceSensorsQuery_workspaceOrError_Workspace_locationEntries[];
}
export interface InstanceSensorsQuery_workspaceOrError_PythonError_cause {
__typename: "PythonError";
message: string;
stack: string[];
}
export interface InstanceSensorsQuery_workspaceOrError_PythonError {
__typename: "PythonError";
message: string;
stack: string[];
cause: InstanceSensorsQuery_workspaceOrError_PythonError_cause | null;
}
export type InstanceSensorsQuery_workspaceOrError = InstanceSensorsQuery_workspaceOrError_Workspace | InstanceSensorsQuery_workspaceOrError_PythonError;
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_location {
__typename: "RepositoryLocation";
id: string;
name: string;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_displayMetadata {
__typename: "RepositoryMetadata";
key: string;
value: string;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_nextTick {
__typename: "FutureInstigationTick";
timestamp: number;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_repositoryOrigin_repositoryLocationMetadata {
__typename: "RepositoryMetadata";
key: string;
value: string;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_repositoryOrigin {
__typename: "RepositoryOrigin";
id: string;
repositoryLocationName: string;
repositoryName: string;
repositoryLocationMetadata: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_repositoryOrigin_repositoryLocationMetadata[];
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_typeSpecificData_SensorData {
__typename: "SensorData";
lastRunKey: string | null;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_typeSpecificData_ScheduleData {
__typename: "ScheduleData";
cronSchedule: string;
}
export type InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_typeSpecificData = InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_typeSpecificData_SensorData | InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_typeSpecificData_ScheduleData;
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_runs {
__typename: "PipelineRun";
id: string;
runId: string;
status: PipelineRunStatus;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_ticks_error_cause {
__typename: "PythonError";
message: string;
stack: string[];
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_ticks_error {
__typename: "PythonError";
message: string;
stack: string[];
cause: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_ticks_error_cause | null;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_ticks {
__typename: "InstigationTick";
id: string;
status: InstigationTickStatus;
timestamp: number;
skipReason: string | null;
runIds: string[];
error: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_ticks_error | null;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState {
__typename: "InstigationState";
id: string;
name: string;
instigationType: InstigationType;
status: InstigationStatus;
repositoryOrigin: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_repositoryOrigin;
typeSpecificData: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_typeSpecificData | null;
runs: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_runs[];
ticks: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState_ticks[];
runningCount: number;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_targets {
__typename: "Target";
pipelineName: string;
solidSelection: string[] | null;
mode: string;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors {
__typename: "Sensor";
id: string;
jobOriginId: string;
name: string;
description: string | null;
minIntervalSeconds: number;
nextTick: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_nextTick | null;
sensorState: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_sensorState;
targets: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors_targets[] | null;
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes {
__typename: "Repository";
id: string;
name: string;
location: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_location;
displayMetadata: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_displayMetadata[];
sensors: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes_sensors[];
}
export interface InstanceSensorsQuery_repositoriesOrError_RepositoryConnection {
__typename: "RepositoryConnection";
nodes: InstanceSensorsQuery_repositoriesOrError_RepositoryConnection_nodes[];
}
export interface InstanceSensorsQuery_repositoriesOrError_PythonError_cause {
__typename: "PythonError";
message: string;
stack: string[];
}
export interface InstanceSensorsQuery_repositoriesOrError_PythonError {
__typename: "PythonError";
message: string;
stack: string[];
cause: InstanceSensorsQuery_repositoriesOrError_PythonError_cause | null;
}
export type InstanceSensorsQuery_repositoriesOrError = InstanceSensorsQuery_repositoriesOrError_RepositoryConnection | InstanceSensorsQuery_repositoriesOrError_PythonError;
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_repositoryOrigin_repositoryLocationMetadata {
__typename: "RepositoryMetadata";
key: string;
value: string;
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_repositoryOrigin {
__typename: "RepositoryOrigin";
id: string;
repositoryLocationName: string;
repositoryName: string;
repositoryLocationMetadata: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_repositoryOrigin_repositoryLocationMetadata[];
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_typeSpecificData_SensorData {
__typename: "SensorData";
lastRunKey: string | null;
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_typeSpecificData_ScheduleData {
__typename: "ScheduleData";
cronSchedule: string;
}
export type InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_typeSpecificData = InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_typeSpecificData_SensorData | InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_typeSpecificData_ScheduleData;
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_runs {
__typename: "PipelineRun";
id: string;
runId: string;
status: PipelineRunStatus;
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_ticks_error_cause {
__typename: "PythonError";
message: string;
stack: string[];
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_ticks_error {
__typename: "PythonError";
message: string;
stack: string[];
cause: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_ticks_error_cause | null;
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_ticks {
__typename: "InstigationTick";
id: string;
status: InstigationTickStatus;
timestamp: number;
skipReason: string | null;
runIds: string[];
error: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_ticks_error | null;
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results {
__typename: "InstigationState";
id: string;
name: string;
instigationType: InstigationType;
status: InstigationStatus;
repositoryOrigin: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_repositoryOrigin;
typeSpecificData: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_typeSpecificData | null;
runs: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_runs[];
ticks: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results_ticks[];
runningCount: number;
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates {
__typename: "InstigationStates";
results: InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates_results[];
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_PythonError_cause {
__typename: "PythonError";
message: string;
stack: string[];
}
export interface InstanceSensorsQuery_unloadableInstigationStatesOrError_PythonError {
__typename: "PythonError";
message: string;
stack: string[];
cause: InstanceSensorsQuery_unloadableInstigationStatesOrError_PythonError_cause | null;
}
export type InstanceSensorsQuery_unloadableInstigationStatesOrError = InstanceSensorsQuery_unloadableInstigationStatesOrError_InstigationStates | InstanceSensorsQuery_unloadableInstigationStatesOrError_PythonError;
export interface InstanceSensorsQuery {
instance: InstanceSensorsQuery_instance;
workspaceOrError: InstanceSensorsQuery_workspaceOrError;
repositoriesOrError: InstanceSensorsQuery_repositoriesOrError;
unloadableInstigationStatesOrError: InstanceSensorsQuery_unloadableInstigationStatesOrError;
} | the_stack |
import { TreeMap } from '../../../src/treemap/treemap';
import { TreeMapTooltip } from '../../../src/treemap/user-interaction/tooltip';
import { MouseEvents } from '../base/events.spec';
import { ILoadedEventArgs, ITreeMapEventArgs } from '../../../src/treemap/model/interface';
import { createElement, remove } from '@syncfusion/ej2-base';
import { jobData, sportsData } from '../base/data.spec';
import {profile , inMB, getMemoryProfile} from '../common.spec';
TreeMap.Inject(TreeMapTooltip);
let jobDataSource: Object[] = jobData;
let gameDataSource: Object[] = sportsData;
/**
* Tree map spec document
*/
describe('TreeMap component Spec', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('TreeMap drill down spec', () => {
let element: Element;
let treemap: TreeMap;
let prevent: Function = (): void => { };
let trigger: MouseEvents = new MouseEvents();
let id: string = 'drill-container';
beforeAll(() => {
element = createElement('div', { id: id });
(element as HTMLDivElement).style.width = '600px';
(element as HTMLDivElement).style.height = '400px';
document.body.appendChild(element);
treemap = new TreeMap({
border: {
color: 'red',
width: 2
},
titleSettings: {
text: 'Tree Map control',
},
dataSource: jobData,
weightValuePath: 'EmployeesCount',
leafItemSettings: {
interSectAction: 'Wrap',
labelFormat: '${JobGroup}<br>$${EmployeesCount}',
labelPath: 'JobGroup',
fill: '#6699cc',
labelPosition: 'BottomRight',
border: { color: 'black', width: 2 }
},
levels: [
{ groupPath: 'Country', fill: '#336699', border: { color: 'black', width: 2 } },
{ groupPath: 'JobDescription', fill: '#336699', border: { color: 'black', width: 2 } }
]
}, '#' + id);
});
afterAll(() => {
treemap.destroy();
remove(treemap.element);
});
it('Checking default tooltip ', () => {
treemap.loaded = (args: ILoadedEventArgs) => {
let layoutID: string = args.treemap.element.id + '_TreeMap_' + args.treemap.layoutType + '_Layout';
let element: Element = document.getElementById(layoutID);
let rectEle: Element;
let eventObj: Object;
for (let i: number = 0; i < element.childElementCount; i++) {
rectEle = element.childNodes[i] as Element;
eventObj = {
target: rectEle,
type: 'mousemove',
pageX: rectEle.getBoundingClientRect().left,
pageY: (rectEle.getBoundingClientRect().top + 10)
};
treemap.treeMapTooltipModule.renderTooltip(<PointerEvent>eventObj);
}
};
treemap.tooltipSettings.visible = true;
treemap.refresh();
});
it('Checking with currency format', () => {
treemap.loaded = (args: ILoadedEventArgs) => {
let layoutID: string = args.treemap.element.id + '_TreeMap_' + args.treemap.layoutType + '_Layout';
let rectEle: Element = document.getElementById(args.treemap.element.id + '_Level_Index_1_Item_Index_17_RectPath');
let rectBounds: ClientRect = rectEle.getBoundingClientRect();
let eventObj: Object = {
target: rectEle,
type: 'mousemove',
pageX: rectEle.getBoundingClientRect().left,
pageY: (rectEle.getBoundingClientRect().top + 10)
};
treemap.treeMapTooltipModule.renderTooltip(<PointerEvent>eventObj);
treemap.mouseLeaveOnTreeMap(<PointerEvent>eventObj);
};
treemap.format = 'c';
treemap.refresh();
});
it('Checking with tooltip format', () => {
treemap.loaded = (args: ILoadedEventArgs) => {
let rectEle: Element = document.getElementById(args.treemap.element.id + '_Level_Index_1_Item_Index_17_RectPath');
let rectBounds: ClientRect = rectEle.getBoundingClientRect();
let titleEle: Element = document.getElementById(args.treemap.element.id + '_TreeMap_title');
let eventObj: Object = {
target: rectEle,
type: 'touchend',
changedTouches: [{ pageX: rectEle.getBoundingClientRect().left, pageY: rectEle.getBoundingClientRect().top }]
};
treemap.treeMapTooltipModule.renderTooltip(<PointerEvent>eventObj);
eventObj = {
target: titleEle,
type: 'mousemove',
pageX: titleEle.getBoundingClientRect().left,
pageY: (titleEle.getBoundingClientRect().top + 10)
};
treemap.treeMapTooltipModule.renderTooltip(<PointerEvent>eventObj);
};
treemap.tooltipSettings.format = 'Employees Count: ${EmployeesCount}';
treemap.refresh();
});
it('Checking with tooltip template', () => {
treemap.loaded = (args: ILoadedEventArgs) => {
let rectEle: Element = document.getElementById(args.treemap.element.id + '_Level_Index_1_Item_Index_17_RectPath');
let eventObj: Object = {
target: rectEle,
type: 'touchend',
changedTouches: [{ pageX: rectEle.getBoundingClientRect().left, pageY: rectEle.getBoundingClientRect().top }]
};
treemap.mouseEndOnTreeMap(<PointerEvent>eventObj);
};
treemap.tooltipRendering = (args: ITreeMapEventArgs) => {
args.cancel = true;
};
treemap.tooltipSettings.template = '<div style="border 1px solid;">${EmployeesCount}</div>';
treemap.refresh();
});
it('Checking with add event listener method', () => {
treemap.isDestroyed = true;
treemap.treeMapTooltipModule.addEventListener();
});
it('Checking with initial drilldown', () => {
treemap.loaded = (args: ILoadedEventArgs) => {
// put the spec here//
};
treemap.initialDrillDown.groupIndex = 0;
treemap.initialDrillDown.groupName = 'Germany';
treemap.refresh();
});
});
describe('TreeMap tooltip spec with enable RTL ', () => {
let element: Element;
let treemap: TreeMap;
let prevent: Function = (): void => { };
let trigger: MouseEvents = new MouseEvents();
let id: string = 'drill-container';
beforeAll(() => {
element = createElement('div', { id: id });
(element as HTMLDivElement).style.width = '600px';
(element as HTMLDivElement).style.height = '400px';
document.body.appendChild(element);
treemap = new TreeMap({
border: {
color: 'red',
width: 2
},
titleSettings: {
text: 'Tree Map control',
},
dataSource: jobData,
enableRtl:true,
weightValuePath: 'EmployeesCount',
leafItemSettings: {
interSectAction: 'Wrap',
labelFormat: '${JobGroup}<br>$${EmployeesCount}',
labelPath: 'JobGroup',
fill: '#6699cc',
labelPosition: 'BottomRight',
border: { color: 'black', width: 2 }
},
levels: [
{ groupPath: 'Country', fill: '#336699', border: { color: 'black', width: 2 } },
{ groupPath: 'JobDescription', fill: '#336699', border: { color: 'black', width: 2 } }
]
}, '#' + id);
});
afterAll(() => {
treemap.destroy();
remove(treemap.element);
});
it('Checking with default tooltip ', () => {
treemap.loaded = (args: ILoadedEventArgs) => {
let layoutID: string = args.treemap.element.id + '_TreeMap_' + args.treemap.layoutType + '_Layout';
let element: Element = document.getElementById(layoutID);
let rectEle: Element;
let eventObj: Object;
for (let i: number = 0; i < element.childElementCount; i++) {
rectEle = element.childNodes[i] as Element;
eventObj = {
target: rectEle,
type: 'mousemove',
pageX: rectEle.getBoundingClientRect().left,
pageY: (rectEle.getBoundingClientRect().top + 10)
};
treemap.treeMapTooltipModule.renderTooltip(<PointerEvent>eventObj);
}
};
treemap.tooltipSettings.visible = true;
treemap.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import {Component, OnDestroy} from '@angular/core';
import {MatDialog, MatDialogConfig} from '@angular/material/dialog';
import {MatSnackBar} from '@angular/material/snack-bar';
import {ReplaySubject} from 'rxjs';
import {concatMap, filter, take, takeUntil} from 'rxjs/operators';
import {AdvancedActionDialogComponent} from '../advanced_actions_dialog/advanced_actions_dialog';
import {ActionModel, actionModelFromJson, ACTIONS, ActionSummaryMetaData, WorkflowModel} from '../constants/actions';
import {ActionColor, DEFAULT_WORKFLOW_NAME, MessageTypes, POPUP_DIALOG_DEFAULT_DIMENSION, TestStatusMsg} from '../constants/constants';
import {PlayActionRequest, PlayActionResponse} from '../constants/interfaces';
import {GlobalVariableSettingDialog} from '../popup_dialogs/global_var_setting_dialog';
import {HistoryDialog} from '../popup_dialogs/history_dialog';
import {PythonDebuggerSimpleDialog} from '../popup_dialogs/python_debugger_simple_dialog';
import {ReplayDetailsDialog} from '../popup_dialogs/replay_details_dialog';
import {BackendManagerService} from '../services/backend_manager_service';
import {ControlMessage, ControlMessageService} from '../services/control_message_service';
import {LogService, Message} from '../services/log_service';
import {ActionEditDialog} from '../test_explorer/action_edit_dialog';
/** Container of slider change event */
export interface SliderChangeEvent {
value: number;
}
/** The workflow editor component. */
@Component({
selector: 'workflow-editor',
templateUrl: 'workflow_editor.ng.html',
styleUrls: ['./workflow_editor.css'],
})
export class WorkflowEditorComponent implements OnDestroy {
readonly START_ACTION_STATUS_KEYWORD = 'Start Action Path:';
readonly END_ACTION_STATUS_KEYWORD = 'End Action Path:';
readonly PLAYACTION_STATUS_SPLITTER = '->';
showPython = true;
isReplaying = false;
workflowModel: WorkflowModel = {actionId: '', name: '', childrenActions: []};
/** Handle on-destroy Subject, used to unsubscribe. */
private readonly destroyed = new ReplaySubject<void>(1);
pathStack: ActionModel[] = [];
pathIndexStack: number[] = [];
playSpeedFactor = 1.0;
static SNACKBAR_DURATION_MS = 2000;
/**
* Indicates the actions which is currently playing. Stack stores all parent
* compound actions
*/
currentPlayActionPath: string = '';
constructor(
private readonly controlMessageService: ControlMessageService,
private readonly backendManagerService: BackendManagerService,
private readonly logService: LogService,
private readonly dialog: MatDialog,
private readonly snackBar: MatSnackBar,
) {
this.controlMessageService.getControlMessageSubject()
.pipe(
takeUntil(this.destroyed),
filter(
(msg: ControlMessage) =>
msg.messageType === MessageTypes.REFRESH_WORKFLOW),
concatMap(() => this.backendManagerService.getCurrentWorkflow()))
.subscribe(data => {
this.workflowModel = new WorkflowModel(JSON.stringify(data));
this.pathStack = [actionModelFromJson(JSON.stringify(data), 0)];
this.pathIndexStack = [0];
});
// Highlight the playing action by check the action id in log messages
this.logService.getMessages()
.pipe(
takeUntil(this.destroyed),
)
.subscribe((data: Message) => {
this.highlightAction(data.text);
});
// Sync the current workflow with backend
this.controlMessageService.sendRefreshWorkflowMsg();
}
/*
* Currently the highlight logic is based on the log information, originally,
* it searches the actionId in the log, and highlight, it works for most
* cases, however it won't work when we have multiple compound action in same
* workflow(will highlight both). We are using index path to track the
* progress. for example in the log, it will show 1->0->2, which indicates the
* index of child in compound action at each level.
*/
highlightAction(logContent: string) {
if (logContent.includes(this.START_ACTION_STATUS_KEYWORD)) {
this.currentPlayActionPath =
logContent.replace(this.START_ACTION_STATUS_KEYWORD, '').trim();
} else if (logContent.includes(this.END_ACTION_STATUS_KEYWORD)) {
// remove the last level trace, i.e. in the log we see <END> 1->2->3
// we want to backtrace remove the last section.
const indexArr =
this.currentPlayActionPath.split(this.PLAYACTION_STATUS_SPLITTER);
if (indexArr.length > 1) {
indexArr.pop();
this.currentPlayActionPath =
indexArr.join(this.PLAYACTION_STATUS_SPLITTER);
} else {
this.currentPlayActionPath = '';
}
}
}
addActionPlus() {
this.dialog.open(AdvancedActionDialogComponent, {
width: POPUP_DIALOG_DEFAULT_DIMENSION.width,
});
}
addScreenShot() {
const action: ActionSummaryMetaData = {
type: ACTIONS.SCREEN_CAP_ACTION.type,
name: ACTIONS.SCREEN_CAP_ACTION.shortName
};
this.backendManagerService.addActionToWorkflow(action)
.pipe(take(1))
.subscribe(() => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
addWait() {
const action: ActionSummaryMetaData = {
type: ACTIONS.WAIT_ACTION.type,
name: ACTIONS.WAIT_ACTION.shortName,
};
this.backendManagerService.addActionToWorkflow(action)
.pipe(take(1))
.subscribe(() => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
clearRecord() {
this.backendManagerService.createNewWorkSpace().pipe(take(1)).subscribe(
() => {
this.pathStack = [];
this.pathIndexStack = [];
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
getActionToolTip(action: ActionModel) {
if (!action.actionDescription || '' === action.actionDescription) {
return action.name;
}
return action.actionDescription;
}
onDropSuccess() {
const reorderActions: string[] =
this.workflowModel.childrenActions.map(action => action.actionId);
this.backendManagerService.reorderActions(reorderActions)
.pipe(take(1))
.subscribe(() => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
openHistoryDialog() {
this.dialog.open(
HistoryDialog, {width: POPUP_DIALOG_DEFAULT_DIMENSION.width});
}
openSaveWorkflowDialog() {
if (this.workflowModel.name === '' ||
this.workflowModel.name.includes(
DEFAULT_WORKFLOW_NAME)) { // New workflow
const dialogRef = this.dialog.open(ActionEditDialog, {
width: POPUP_DIALOG_DEFAULT_DIMENSION.width,
data: {uuid: this.workflowModel.actionId, isSaveWorkflow: true}
});
dialogRef.afterClosed().subscribe(data => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
} else {
this.backendManagerService.saveCurrentWorkflowWithoutMetadata()
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(response => {
if (response === true) {
this.snackBar.open(
'Current workflow saved!', 'OK',
{duration: WorkflowEditorComponent.SNACKBAR_DURATION_MS});
} else {
this.snackBar.open(
'Error: Current workflow failed to save!', 'OK',
{duration: WorkflowEditorComponent.SNACKBAR_DURATION_MS});
}
});
}
}
openActionEditDialog(id: string, index: string) {
const dialogConfig = new MatDialogConfig();
dialogConfig.width = POPUP_DIALOG_DEFAULT_DIMENSION.width;
dialogConfig.data = {'uuid': id, 'index': index};
const dialogRef = this.dialog.open(ActionEditDialog, dialogConfig);
dialogRef.afterClosed()
.pipe(
filter(
data => data && data.hasOwnProperty('playWorkflowRequested')),
concatMap(() => {
this.preparePlay();
const playActionRequest: PlayActionRequest = {
actionId: id,
playSpeedFactor: this.playSpeedFactor,
};
return this.backendManagerService.playCurrentWorkflowFromAction(
playActionRequest);
}))
.subscribe(data => {
this.finishPlay(data);
});
}
preparePlay(): boolean {
if (this.isReplaying) {
this.backendManagerService.cancelCurrentWorkflow()
.pipe(take(1))
.subscribe(() => {
this.isReplaying = false;
this.logService.log(TestStatusMsg.TEST_END_CANCELLED);
});
return false;
}
this.isReplaying = true;
this.logService.log(TestStatusMsg.TEST_START);
return true;
}
finishPlay(data: PlayActionResponse) {
this.isReplaying = false;
this.controlMessageService.sendRefreshWorkflowMsg();
this.logService.log(TestStatusMsg.TEST_END);
this.dialog.open(
ReplayDetailsDialog,
{width: POPUP_DIALOG_DEFAULT_DIMENSION.width, data});
}
playCurrentWorkflow() {
if (!this.preparePlay()) {
return;
}
const playActionRequest: PlayActionRequest = {
actionId: this.workflowModel.actionId,
playSpeedFactor: this.playSpeedFactor,
};
this.backendManagerService.playAction(playActionRequest)
.pipe(
take(1),
takeUntil(this.destroyed),
)
.subscribe((data) => {
this.finishPlay(data);
});
}
undo() {
this.backendManagerService.undo().pipe(take(1)).subscribe(() => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
redo() {
this.backendManagerService.redo().pipe(take(1)).subscribe(() => {
this.controlMessageService.sendRefreshWorkflowMsg();
});
}
getTextByType(actionModel: ActionModel) {
if (actionModel.actionType in ACTIONS) {
return ACTIONS[actionModel.actionType].shortName;
}
return 'UNKNOWN';
}
getColorByType(actionModel: ActionModel) {
if (actionModel.actionType in ACTIONS) {
return ACTIONS[actionModel.actionType].color;
}
return ActionColor.BLACK;
}
getBackgroundColor(actionModel: ActionModel) {
if (!this.isReplaying) {
return this.getColorByType(actionModel);
}
if (this.needHighLightCurrentAction(actionModel.actionIndex)) {
return ActionColor.BLUE;
}
return ActionColor.GRAY;
}
needHighLightCurrentAction(actionIndex: number) {
const pathList = this.pathIndexStack.slice(0);
pathList.push(actionIndex);
const pathStr = pathList.join(this.PLAYACTION_STATUS_SPLITTER);
// Current path could be 1->6 or 1->6->4, both cases we want to hight light
// 7th element. Can not just do startsWith, since we could something like
// 1->61->2 in the path. It will highlight both 6th and 61th.
if (this.currentPlayActionPath === pathStr ||
this.currentPlayActionPath.startsWith(
pathStr + this.PLAYACTION_STATUS_SPLITTER)) {
return true;
}
return false;
}
expandCompoundAction(action: ActionModel, event: MouseEvent) {
this.logService.log('Expand Compound Action: ' + action.name);
this.pathStack = [...this.pathStack, action];
this.pathIndexStack = [...this.pathIndexStack, action.actionIndex];
event.stopPropagation();
this.backendManagerService.loadWorkflow(action.actionId).subscribe(data => {
this.workflowModel = new WorkflowModel(JSON.stringify(data));
});
}
goBackFromExpandedCompoundAction(action: ActionModel) {
this.logService.log('Go back to:' + action.name);
const index = this.pathStack.findIndex(x => x.actionId === action.actionId);
this.pathStack = this.pathStack.slice(0, index + 1);
this.pathIndexStack = this.pathIndexStack.slice(0, index + 1);
this.backendManagerService.loadWorkflow(action.actionId).subscribe(data => {
this.workflowModel = new WorkflowModel(JSON.stringify(data));
});
}
openGlobalVarSettings() {
this.dialog.open(
GlobalVariableSettingDialog,
{width: POPUP_DIALOG_DEFAULT_DIMENSION.width});
}
openPdbDebuggerDialog() {
this.dialog.open(
PythonDebuggerSimpleDialog, {panelClass: 'python-overlay-style'});
}
onSpeedSliderChange(event: SliderChangeEvent) {
if (this.isReplaying) {
this.backendManagerService.setPlaySpeedFactor(event.value)
.pipe(take(1), takeUntil(this.destroyed))
.subscribe();
}
}
ngOnDestroy() {
// Unsubscribes all pending subscriptions.
this.destroyed.next();
}
} | the_stack |
const FIXTURES = "network";
import { existsSync } from "fs";
import * as cheerio from "cheerio";
import * as debug from "debug";
import { diffJson as diff } from "diff";
import { back as nockBack } from "nock";
import { default as fetch } from "node-fetch";
import { _getBody as getBody } from "..";
import { _getSchemaMetadata as getSchemaMetadata } from "..";
import { _getInlineMetadata as getInlineMetadata } from "..";
import { _getImageSize as getImageSize } from "..";
import { _getCorsEndpoints as getCorsEndpoints } from "..";
import * as linter from "..";
import throat = require("throat");
const PASS = linter.PASS();
const log = debug("linter");
nockBack.fixtures = `${__dirname}/${FIXTURES}`;
// Need to throttle to one run at a time because nock() works by monkey patching
// the (global) http.* object, which means it can't run in parallel.
const withFixture = throat(1,
async <T>(fixtureName: string, fn: () => Promise<T>): Promise<T> => {
const fixturePath = `${fixtureName}.json`;
if (existsSync(`${nockBack.fixtures}/${fixturePath}`)) {
log(`nocking HTTP requests with fixture [${fixturePath}]`);
nockBack.setMode("lockdown");
const { nockDone } = await nockBack(fixturePath);
const res = await fn();
nockDone();
return res;
} else {
log(`recording HTTP requests to fixture [${fixturePath}] ...`);
nockBack.setMode("record");
const { nockDone } = await nockBack(fixturePath);
const res = await fn();
return new Promise<T>((resolve) => {
setTimeout(() => { // wait for probe-image-size's aborts to settle
nockDone();
log(`... created fixture [${fixturePath}]`);
resolve(res);
}, 2000);
});
}
}
) as <T>(fixtureName: string, fn: () => Promise<T>) => Promise<T>;
async function assertEqual<T extends object>(
testName: string,
actual: T|Promise<T>,
expected: T|Promise<T>
) {
COUNT++;
const res = diff(
await Promise.resolve(expected),
await Promise.resolve(actual)
);
if (res && res.length === 1) {
console.log(`ok ${COUNT} - ${testName}`);
} else {
const as = JSON.stringify(await Promise.resolve(actual));
const es = JSON.stringify(await Promise.resolve(expected));
console.log(`not ok ${COUNT} - ${testName} actual: ${as}, expected: ${es}`);
}
return res;
}
async function assertNotEqual<T extends object>(
testName: string,
actual: T|Promise<T>,
expected: T|Promise<T>
) {
COUNT++;
const res = diff(
await Promise.resolve(expected),
await Promise.resolve(actual)
);
if (res && res.length === 1) {
const as = JSON.stringify(await Promise.resolve(actual));
const es = JSON.stringify(await Promise.resolve(expected));
console.log(`not ok ${COUNT} - ${testName} actual: ${as}, expected: ${es}`);
} else {
console.log(`ok ${COUNT} - ${testName}`);
}
return res;
}
async function assertMatch<T extends object>(
testName: string,
actual: T|Promise<T>,
expected: string
) {
COUNT++;
const s = JSON.stringify(await Promise.resolve(actual));
if (s.match(expected)) {
console.log(`ok ${COUNT} - ${testName}`);
} else {
console.log(`not ok ${COUNT} - ${testName} actual: ${s}`);
}
}
async function assertFn<T extends object>(
testName: string,
actual: T|Promise<T>,
expectedFn: (actual: T) => string,
) {
COUNT++;
const res = expectedFn(await actual);
if (!res) {
console.log(`ok ${COUNT} - ${testName}`);
} else {
console.log(`not ok ${COUNT} - ${testName} [${res}]`);
}
return res;
}
async function runTest<T>(fn: linter.Test, url: string) {
const res = await fetch(url);
const body = await res.text();
const $ = cheerio.load(body);
const context = {
$,
headers: {},
url
};
return Promise.resolve(fn(context));
}
async function runTestList<T>(fn: linter.TestList, url: string) {
const res = await fetch(url);
const body = await res.text();
const $ = cheerio.load(body);
const context = {
$,
headers: {},
url
};
return Promise.resolve(fn(context));
}
async function runCheerioFn<T>(fn: ($: CheerioStatic, url?: string) => T|Promise<T>, url: string) {
const res = await fetch(url);
const body = await res.text();
const $ = cheerio.load(body);
return Promise.resolve(fn($, url));
}
async function runUrlFn<T>(fn: (url: string) => T, url: string) {
return Promise.resolve(fn(url));
}
let COUNT = 0;
withFixture("getschemametadata", () => assertEqual(
"getSchemaMetadata",
runCheerioFn(
getSchemaMetadata,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"item": {
"@id": "https://ampbyexample.com/#/stories#stories/introduction",
"name": "Introduction",
},
"position": 1,
},
{
"@type": "ListItem",
"item": {
"@id":
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/",
"name": " AMP Story Hello World",
},
"position": 2,
}
]
},
));
withFixture("getinlinemetadata", () => assertEqual(
"getInlineMetadata",
runCheerioFn(
getInlineMetadata,
"https://ithinkihaveacat.github.io/hello-world-amp-story/"
),
{
"poster-portrait-src":
[
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/",
"Cantilever_bridge_human_model.jpg/",
"627px-Cantilever_bridge_human_model.jpg"
].join(""),
"publisher": "Michael Stillwell",
"publisher-logo-src":
"https://s.gravatar.com/avatar/3928085cafc1e496fb3d990a9959f233?s=150",
"title": "Hello, Ken Burns",
},
));
withFixture("thumbnails1", () => assertFn<linter.Message[]>(
"testThumbnails - correctly sized",
runTestList(
linter.testThumbnails,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
(actual) => {
return actual.length === 0 ? "" : "expected no errors";
}
));
withFixture("thumbnails2", () => assertMatch(
"testThumbnails - publisher-logo-src missing",
runTestList(
linter.testThumbnails,
"https://regular-biology.glitch.me/"
),
"publisher-logo-src"
));
withFixture("thumbnails3", () => assertMatch(
"testThumbnails - poster-portrait-src not found",
runTestList(
linter.testThumbnails,
"http://localhost:5000/"
),
"not 200"
));
withFixture("testvalidity1", () => assertEqual(
"testValidity - valid",
runTest(
linter.testValidity,
"https://www.ampproject.org/"
),
PASS
));
withFixture("testvalidity2", async () => assertNotEqual(
"testValidity - not valid",
runTest(
linter.testValidity,
"https://precious-sturgeon.glitch.me/"
),
PASS
));
withFixture("testcanonical1", () => assertEqual(
"testCanonical - canonical",
runTest(
linter.testCanonical,
"https://regular-biology.glitch.me/"
),
PASS
));
withFixture("testcanonical2", () => assertMatch(
"testCanonical - not canonical",
runTest(
linter.testCanonical,
"https://regular-biology.glitch.me/"
),
"https://regular-biology.glitch.me/"
));
withFixture("testcanonical3", () => assertEqual(
"testCanonical - relative",
runTest(
linter.testCanonical,
"https://regular-biology.glitch.me/"
),
PASS
));
withFixture("testvideosize1", () => assertEqual(
"testVideoSize - too big",
runTest(
linter.testVideoSize,
"https://regular-biology.glitch.me/"
),
{
message: "videos over 4MB: [https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4]",
status: "FAIL"
}
));
withFixture("testvideosize2", () => assertEqual(
"testVideoSize - good size #1",
runTest(
linter.testVideoSize,
"https://regular-biology.glitch.me/"
),
PASS
));
withFixture("testvideosize3", () => assertEqual(
"testVideoSize - good size #2",
runTest(
linter.testVideoSize,
"https://ampbyexample.com/stories/features/media/preview/embed/"
),
PASS
));
withFixture("bookendsameorigin1", () => assertEqual(
"testBookendSameOrigin - configured correctly",
runTest(
linter.testBookendSameOrigin,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
PASS
));
withFixture("bookendsameorigin2", () => assertMatch(
"testBookendSameOrigin - bookend not application/json",
runTest(
linter.testBookendSameOrigin,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
"application/json"
));
withFixture("bookendsameorigin3", () => assertMatch(
"testBookendSameOrigin - bookend not JSON",
runTest(
linter.testBookendSameOrigin,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
"JSON"
));
withFixture("bookendsameorgin4", () => assertEqual(
"testBookendSameOrigin - v0 AMP Story - configured correctly",
runTest(
linter.testBookendSameOrigin,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
PASS
));
withFixture("bookendcache1", () => assertEqual(
"testBookendCache - configured correctly",
runTest(
linter.testBookendCache,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
PASS
));
withFixture("bookendcache2", () => assertMatch(
"testBookendCache - incorrect headers",
runTest(
linter.testBookendCache,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
"access-control-allow-origin"
));
withFixture("ampstoryv1metadata1", () => assertEqual(
"testAmpStoryV1Metadata - valid metadata",
runTest(
linter.testAmpStoryV1Metadata,
"https://ithinkihaveacat.github.io/hello-world-amp-story/"
),
PASS
));
withFixture("ampstoryv1metadata2", () => assertMatch(
"testAmpStoryV1Metadata - invalid metadata",
runTest(
linter.testAmpStoryV1Metadata,
"https://ithinkihaveacat-hello-world-amp-story-7.glitch.me/"
),
"publisher-logo-src"
));
withFixture("ampimg1", () => assertFn<linter.Message[]>(
"testAmpImg - height/width are incorrect #1",
runTestList(
linter.testAmpImg,
"https://ampbyexample.com/components/amp-img/"
),
(res) => {
if (res.length !== 3) {
return "expected 3 failures";
}
const message = res[1].message;
if (typeof(message) !== "string" || !message.match("does-not-exist")) {
return "does-not-exist.jpg should be a 404";
}
return "";
}
));
withFixture("ampimg2", () => assertFn<linter.Message[]>(
"testAmpImg - height/width are incorrect #2",
runTestList(
linter.testAmpImg,
"https://www.ampproject.org/docs/reference/components/amp-story"
),
(res) => {
if (res.length !== 6) {
return "expected 6 failures";
}
const message1 = res[0].message;
if (typeof(message1) !== "string" || !message1.match("amp-story-tag-hierarchy")) {
return "amp-story-tag-hierarchy.png is wrong ratio";
}
const message2 = res[5].message;
if (typeof(message2) !== "string" || !message2.match("layers-layer-3")) {
return "layers-layer-3.jpg is too big";
}
return "";
}
));
withFixture("ampimg3", () => assertFn<linter.Message[]>(
"testAmpImg - height/width are correct",
runTestList(
linter.testAmpImg,
"https://ampbyexample.com/introduction/hello_world/"
),
(res) => {
return res.length === 0 ? "" : `expected 0 failures, got ${JSON.stringify(res)}`;
}
));
withFixture("corsendpoints1", () => assertEqual(
"getCorsEndpoints - all endpoints extracted (AMP)",
runCheerioFn(
getCorsEndpoints,
"https://swift-track.glitch.me/"
),
[
"https://ampbyexample.com/json/examples.json"
]
));
withFixture("corsendpoints2", () => assertEqual(
"getCorsEndpoints - all endpoints extracted (AMP Story)",
runCheerioFn(
getCorsEndpoints,
"https://ampbyexample.com/stories/introduction/amp_story_hello_world/preview/embed/"
),
[
"https://ampbyexample.com/json/bookend.json",
]
));
withFixture("cors1", () => assertFn<linter.Message[]>(
"testCors - all headers correct",
runTestList(
linter.testCorsSameOrigin,
"https://swift-track.glitch.me/"
),
(res) => {
return res.length === 0 ? "" : `expected 0 failures, got ${JSON.stringify(res)}`;
}
));
withFixture("cors2", () => assertMatch(
"testCors - endpoint is 404",
runTestList(
linter.testCorsSameOrigin,
"https://swift-track.glitch.me/"
),
"404"
));
withFixture("cors3", () => assertMatch(
"testCors - endpoint not application/json",
runTestList(
linter.testCorsSameOrigin,
"https://swift-track.glitch.me/"
),
"application/json"
));
withFixture("cors4", () => assertEqual(
"testCorsCache - all headers correct",
runTestList(
linter.testCorsCache,
"https://swift-track.glitch.me/"
),
[]
));
console.log("# dummy"); // https://github.com/scottcorgan/tap-spec/issues/63 (sigh)
console.log(`1..30`); | the_stack |
import { ElemID } from '@salto-io/adapter-api'
export const HUBSPOT = 'hubspot'
export const RECORDS_PATH = 'Records'
export const TYPES_PATH = 'Types'
export const SUBTYPES_PATH = 'Subtypes'
export const NAME = 'name'
const LABEL = 'label'
const PROPERTY_OPTIONS = 'options'
const DISPLAYORDER = 'displayOrder'
const CREATEDAT = 'createdAt'
export const OBJECTS_NAMES = {
FORM: 'Form',
MARKETINGEMAIL: 'Email',
WORKFLOW: 'Workflow',
CONTACT_PROPERTY: 'ContactProperty',
// Subtypes
PROPERTYGROUP: 'propertyGroup',
PROPERTY: 'property',
OPTIONS: 'options',
CONTACTLISTIDS: 'contactListIds',
RSSTOEMAILTIMING: 'rssToEmailTiming',
NURTURETIMERANGE: 'nurtureTimeTange',
ACTION: 'action',
ANCHORSETTING: 'anchorSetting',
CRITERIA: 'criteria',
EVENTANCHOR: 'eventAnchor',
CONDITIONACTION: 'conditionAction',
DEPENDENT_FIELD_FILTERS: 'dependentFieldFilters',
FIELD_FILTER: 'fieldFilter',
DEPENDEE_FORM_PROPERTY: 'dependeeFormProperty',
RICHTEXT: 'richText',
CONTACTPROPERTYOVERRIDES: 'contactPropertyOverrides',
}
export const FIELD_TYPES = {
TEXTAREA: 'textarea',
TEXT: 'text',
DATE: 'date',
FILE: 'file',
NUMBER: 'number',
SELECT: 'select',
RADIO: 'radio',
CHECKBOX: 'checkbox',
BOOLEANCHECKBOX: 'booleancheckbox',
USERIDENTIFIER: 'userIdentifier',
}
export const FORM_FIELDS = {
GUID: 'guid',
NAME,
CSSCLASS: 'cssClass',
REDIRECT: 'redirect',
SUBMITTEXT: 'submitText',
NOTIFYRECIPIENTS: 'notifyRecipients',
IGNORECURRENTVALUES: 'ignoreCurrentValues',
DELETABLE: 'deletable',
INLINEMESSAGE: 'inlineMessage',
CREATEDAT,
CAPTCHAENABLED: 'captchaEnabled',
CLONEABLE: 'cloneable',
EDITABLE: 'editable',
STYLE: 'style',
FORMFIELDGROUPS: 'formFieldGroups',
THEMENAME: 'themeName',
}
export const MARKETING_EMAIL_FIELDS = {
AB: 'ab',
ABHOURSWAIT: 'abHoursToWait',
ABVARIATION: 'abVariation',
ABSAMPLESIZEDEFAULT: 'abSampleSizeDefault',
ABSAMPLINGDEFAULT: 'abSamplingDefault',
ABSTATUS: 'abStatus',
ABSUCCESSMETRIC: 'abSuccessMetric',
ABTESTID: 'abTestId',
ABTESTPERCENTAGE: 'abTestPercentage',
ABSOLUTEURL: 'absoluteUrl',
ALLEMAILCAMPAIGNIDS: 'allEmailCampaignIds',
ANALYTICSPAGEID: 'analyticsPageId',
ANALYTICSPAGETYPE: 'analyticsPageType',
ARCHIVED: 'archived',
AUTHOR: 'author',
AUTHORAT: 'authorAt',
AUTHOREMAIL: 'authorEmail',
AUTHORNAME: 'authorName',
AUTHORUSERID: 'authorUserId',
BLOGEMAILTYPE: 'blogEmailType',
BLOGRSSSETTINGS: 'blogRssSettings',
CAMPAIGN: 'campaign',
CAMPAIGNNAME: 'campaignName',
CANSPAMSETTINGSID: 'canSpamSettingsId',
CATEGORYID: 'categoryId',
CLONEDFROM: 'clonedFrom',
CONTENTTYPECATEGORY: 'contentTypeCategory',
CREATEPAGE: 'createPage',
CREATED: 'created',
CURRENTLYPUBLISHED: 'currentlyPublished',
DOMAIN: 'domain',
EMAILBODY: 'emailBody',
EMAILNOTE: 'emailNote',
EMAILTYPE: 'emailType',
FEEDBACKEMAILCATEGORY: 'feedbackEmailCategory',
FEEDBACKSURVEYID: 'feedbackSurveyId',
FLEXAREAS: 'flexAreas',
FOLDERID: 'folderId',
FREEZEDATE: 'freezeDate',
FROMNAME: 'fromName',
HTMLTITLE: 'htmlTitle',
ID: 'id',
ISGRAYMAILSUPPRESSIONENABLED: 'isGraymailSuppressionEnabled',
ISLOCALTIMEZONESEND: 'isLocalTimezoneSend',
ISPUBLISHED: 'isPublished',
ISRECIPIENTFATIGUESUPPRESSIONENABLED: 'isRecipientFatigueSuppressionEnabled',
LEADFLOWID: 'leadFlowId',
LIVEDOMAIN: 'liveDomain',
MAILINGLISTSEXCLUDED: 'mailingListsExcluded',
MAILINGLISTSINCLUDED: 'mailingListsIncluded',
MAXRSSENTRIES: 'maxRssEntries',
METADESCRIPTION: 'metaDescription',
NAME: 'name',
PAGEEXPIRYDATE: 'pageExpiryDate',
PAGEEXPIRYREDIRECTEID: 'pageExpiryRedirectId',
PAGEREDIRECTED: 'pageRedirected',
PORTALID: 'portalId',
PREVIEWKEY: 'previewKey',
PROCESSINGSTATUS: 'processingStatus',
PUBLISHDATE: 'publishDate',
PUBLISHEDAT: 'publishedAt',
PUBLISHEDBYID: 'publishedById',
PUBLISHEDBYNAME: 'publishedByName',
PUBLISHIMMEDIATELY: 'publishImmediately',
PUBLISHEDURL: 'publishedUrl',
REPLYTO: 'replyTo',
RESOLVEDDOMAIN: 'resolvedDomain',
RSSEMAILAUTHORLINETEMPLATE: 'rssEmailAuthorLineTemplate',
RSSEMAILBLOGIMAGEMAXWIDTH: 'rssEmailBlogImageMaxWidth',
RSSEMAILBYTEXT: 'rssEmailByText',
RSSEMAILCLICKTHROUGHTEXT: 'rssEmailClickThroughText',
RSSEMAILCOMMENTTEXT: 'rssEmailCommentText',
RSSEMAILENTRYTEMPLATE: 'rssEmailEntryTemplate',
RSSEMAILENTRYTEMPLATEENABLED: 'rssEmailEntryTemplateEnabled',
RSSEMAILURL: 'rssEmailUrl',
RSSTOEMAILTIMING: 'rssToEmailTiming',
SLUG: 'slug',
SMARTEMAILFIELDS: 'smartEmailFields',
STYLESETTINGS: 'styleSettings',
SUBCATEGORY: 'subcategory',
SUBJECT: 'subject',
SUBSCRIPTION: 'subscription',
SUBSCRIPTIONBLOGID: 'subscriptionBlogId',
SUBSCRIPTIONNAME: 'subscription_name',
TEMPLATEPATH: 'templatePath',
TRANSACTIONAL: 'transactional',
UNPUBLISHEDAT: 'unpublishedAt',
UPDATED: 'updated',
UPDATEDBYID: 'updatedById',
URL: 'url',
USERSSHEADLINEASSUBJECT: 'useRssHeadlineAsSubject',
VIDSEXCLUDED: 'vidsExcluded',
VIDSINCLUDED: 'vidsIncluded',
WIDGETS: 'widgets',
WORKFLOWNAMES: 'workflowNames',
}
export const RSSTOEMAILTIMING_FIELDS = {
REPEATS: 'repeats',
REPEATS_ON_MONTHLY: 'repeats_on_monthly',
REPEATS_ON_WEEKLY: 'repeats_on_weekly',
TIME: 'time',
}
export const FORM_PROPERTY_GROUP_FIELDS = {
DEFAULT: 'default',
FIELDS: 'fields',
ISSMARTGROUP: 'isSmartGroup',
RICHTEXT: 'richText',
}
export const RICHTEXT_FIELDS = {
CONTENT: 'content',
}
export const FORM_PROPERTY_FIELDS = {
// Specific
REQUIRED: 'required',
ISSMARTFIELD: 'isSmartField',
DEFAULTVALUE: 'defaultValue',
SELECTEDOPTIONS: 'selectedOptions',
DEPENDENTFIELDFILTERS: 'dependentFieldFilters',
PLACEHOLDER: 'placeholder',
DESCRIPTION: 'description',
// From contactProperty
NAME,
GROUPNAME: 'groupName',
TYPE: 'type',
FIELDTYPE: 'fieldType',
HIDDEN: 'hidden',
// Override
DISPLAYORDER,
LABEL,
OPTIONS: PROPERTY_OPTIONS,
}
export const FORM_PROPERTY_INNER_FIELDS = {
CONTACT_PROPERTY: 'contactProperty',
CONTACT_PROPERTY_OVERRIDES: 'contactPropertyOverrides',
HELPTEXT: 'helpText',
}
export const CONTACT_PROPERTY_OVERRIDES_FIELDS = {
LABEL,
DISPLAYORDER,
OPTIONS: PROPERTY_OPTIONS,
}
export const DEPENDENT_FIELD_FILTER_FIELDS = {
FILTERS: 'filters',
DEPEDENTFORMFIELD: 'dependentFormField',
FORMFIELDACTION: 'formFieldAction',
}
export const FIELD_FILTER_FIELDS = {
OPERATOR: 'operator',
STRVALUE: 'strValue',
NUMBERVALUE: 'numValue',
BOOLVALUE: 'boolValue',
STRVALUES: 'strValues',
NUMVALUES: 'mnumberValues',
}
export const CONTACT_PROPERTY_FIELDS = {
NAME,
LABEL,
DESCRIPTION: 'description',
GROUPNAME: 'groupName',
TYPE: 'type',
FIELDTYPE: 'fieldType',
OPTIONS: PROPERTY_OPTIONS,
DELETED: 'deleted',
FORMFIELD: 'formField',
CREATEDAT,
DISPLAYORDER,
READONLYVALUE: 'readOnlyValue',
READONLYDEFINITION: 'readOnlyDefinition',
MUTABLEDEFINITIONNOTDELETABLE: 'mutableDefinitionNotDeletable',
HIDDEN: 'hidden',
CALCULATED: 'calculated',
EXTERNALOPTIONS: 'externalOptions',
}
export const OPTIONS_FIELDS = {
LABEL,
DESCRIPTION: 'description',
VALUE: 'value',
HIDDEN: 'hidden',
ISSMARTFIELD: 'isSmartField',
READONLY: 'readOnly',
DISPLAYORDER,
}
export const WORKFLOWS_FIELDS = {
ID: 'id',
NAME: 'name',
TYPE: 'type',
ENABLED: 'enabled',
INSERTEDAT: 'insertedAt',
UPDATEDAT: 'updatedAt',
PERSONTALIDS: 'personaTagIds',
CONTACTLISTIDS: 'contactListIds',
ACTIONS: 'actions',
INTERNAL: 'internal',
ONLYEXECONBIZDAYS: 'onlyExecOnBizDays',
NURTURETIMERANGE: 'nurtureTimeRange',
LISTENING: 'listening',
ALLOWCONTACTTOTRIGGERMULTIPLETIMES: 'allowContactToTriggerMultipleTimes',
GOALCRITERIA: 'goalCriteria',
ONLYENROLLMANUALLY: 'onlyEnrollsManually',
ENROLLONCRITERIAUPDATE: 'enrollOnCriteriaUpdate',
LASTUPDATEDBY: 'lastUpdatedBy',
SUPRESSIONLISTIDS: 'supressionListIds',
SEGMENTCRITERIA: 'segmentCriteria',
EVENTANCHOR: 'eventAnchor',
}
export const CRITERIA_FIELDS = {
FILTERFAMILY: 'filterFamily',
WITHINTIMEMODE: 'withinTimeMode',
OPERATOR: 'operator',
TYPE: 'type',
PROPERTY: 'property',
PROPERTYOBJECTTYPE: 'propertyObjectType',
VALUE: 'value',
}
export const EVENTANCHOR_FIELDS = {
STATICDATEANCHOR: 'staticDateAnchor',
CONTACTPROPERTYANCHOR: 'contactPropertyAnchor',
}
export const NURTURETIMERANGE_FIELDS = {
ENABLED: 'enabled',
STARTHOUR: 'startHour',
STOPHOUR: 'stopHour',
}
export const ACTION_FIELDS = {
TYPE: 'type',
ANCHORSETTING: 'anchorSetting',
ACTIONID: 'actionId',
DELAYMILLS: 'delayMillis',
STEPID: 'stepId',
FILTERSLISTID: 'filtersListId',
FILTERS: 'filters',
NEWVALUE: 'newValue',
ACCEPTACTIONS: 'acceptActions',
PROPERTYNAME: 'propertyName',
REJECTACTIONS: 'rejectActions',
STATICTO: 'staticTo',
BODY: 'body',
}
export const ANCHOR_SETTING_FIELDS = {
EXECTIMEOFDAY: 'execTimeOfDay',
EXECTIMEINMINUTES: 'execTimeInMinutes',
BOUNDARY: 'boundary',
}
export const CONTACTLISTIDS_FIELDS = {
ENROLLED: 'enrolled',
ACTIVE: 'active',
COMPLETED: 'completed',
SUCCEEDED: 'succeeded',
}
export const contactPropertyTypeValues = ['string', 'number', 'date', 'datetime', 'enumeration', 'bool', 'phone_number']
export const contactPropertyFieldTypeValues = ['textarea', 'text', 'date', 'file', 'number', 'select', 'calculation_equation',
'radio', 'checkbox', 'booleancheckbox', 'calculation_score', 'phonenumber', 'calculation_read_time']
// ElemIDs
export const formElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.FORM)
export const workflowsElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.WORKFLOW)
export const criteriaElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.CRITERIA)
export const propertyGroupElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.PROPERTYGROUP)
export const propertyElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.PROPERTY)
export const dependeeFormPropertyElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.DEPENDEE_FORM_PROPERTY)
export const optionsElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.OPTIONS)
export const contactListIdsElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.CONTACTLISTIDS)
export const marketingEmailElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.MARKETINGEMAIL)
export const rssToEmailTimingElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.RSSTOEMAILTIMING)
export const nurtureTimeRangeElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.NURTURETIMERANGE)
export const anchorSettingElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.ANCHORSETTING)
export const actionElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.ACTION)
export const eventAnchorElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.EVENTANCHOR)
export const conditionActionElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.CONDITIONACTION)
export const contactPropertyElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.CONTACT_PROPERTY)
export const dependentFormFieldFiltersElemID = new ElemID(HUBSPOT,
OBJECTS_NAMES.DEPENDENT_FIELD_FILTERS)
export const fieldFilterElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.FIELD_FILTER)
export const richTextElemID = new ElemID(HUBSPOT, OBJECTS_NAMES.RICHTEXT)
export const contactPropertyOverridesElemID = new ElemID(
HUBSPOT,
OBJECTS_NAMES.CONTACTPROPERTYOVERRIDES
)
export const userIdentifierElemID = new ElemID(HUBSPOT, FIELD_TYPES.USERIDENTIFIER) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.