@inappstory/slide-api 0.1.37 → 0.1.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3359,6 +3359,57 @@ class Timer {
3359
3359
  static get [Symbol.for("___CTOR_ARGS___")]() { return [`HTMLElement`, `Layer`, `Array`, `typeof WidgetTimer.api`, `WidgetCallbacks`, `WidgetDeps`]; }
3360
3360
  }
3361
3361
 
3362
+ class Reactions {
3363
+ _elementNodeRef;
3364
+ _widgetApi;
3365
+ _widgetCallbacks;
3366
+ _widgetDeps;
3367
+ static _className = "narrative-element-reactions";
3368
+ static className() {
3369
+ return Reactions._className;
3370
+ }
3371
+ constructor(_elementNodeRef, _widgetApi, _widgetCallbacks, _widgetDeps) {
3372
+ this._elementNodeRef = _elementNodeRef;
3373
+ this._widgetApi = _widgetApi;
3374
+ this._widgetCallbacks = _widgetCallbacks;
3375
+ this._widgetDeps = _widgetDeps;
3376
+ }
3377
+ static isTypeOf(element) {
3378
+ return element instanceof Reactions;
3379
+ }
3380
+ mediaElementsLoadingPromises = [];
3381
+ get nodeRef() {
3382
+ return this._elementNodeRef;
3383
+ }
3384
+ init(localData) {
3385
+ try {
3386
+ this._widgetApi.init(this._elementNodeRef, localData, this._widgetCallbacks, this._widgetDeps);
3387
+ }
3388
+ catch (e) {
3389
+ console.error(e);
3390
+ }
3391
+ return Promise.resolve(true);
3392
+ }
3393
+ onPause() { }
3394
+ onResume() { }
3395
+ onStart() {
3396
+ this._widgetApi.onStart(this._elementNodeRef);
3397
+ }
3398
+ onStop() {
3399
+ this._widgetApi.onStop(this._elementNodeRef);
3400
+ }
3401
+ onBeforeUnmount() {
3402
+ return Promise.resolve();
3403
+ }
3404
+ handleClick() {
3405
+ return false;
3406
+ }
3407
+ get isLayerForcePaused() {
3408
+ return false;
3409
+ }
3410
+ static get [Symbol.for("___CTOR_ARGS___")]() { return [`HTMLElement`, `typeof WidgetReactions.api`, `WidgetCallbacks`, `WidgetDeps`]; }
3411
+ }
3412
+
3362
3413
  // export const tryCreateAtLayer = (layerNodeRef: HTMLElement): IElement {
3363
3414
  // const
3364
3415
  // }
@@ -3421,6 +3472,8 @@ const tryCreateFromHtmlElement = (nodeRef, layer, widgetCallbacks, widgetDeps) =
3421
3472
  return layoutApi.widgetTooltipApi ? new Tooltip(nodeRef, layer, layoutApi.widgetTooltipApi, widgetCallbacks, widgetDeps) : null;
3422
3473
  case Timer.className():
3423
3474
  return layoutApi.widgetTimerApi ? new Timer(nodeRef, layer, layersNodesRefs, layoutApi.widgetTimerApi, widgetCallbacks, widgetDeps) : null;
3475
+ case Reactions.className():
3476
+ return layoutApi.widgetReactionsApi ? new Reactions(nodeRef, layoutApi.widgetReactionsApi, widgetCallbacks, widgetDeps) : null;
3424
3477
  }
3425
3478
  }
3426
3479
  return null;
@@ -5200,6 +5253,19 @@ let SlideApi$1 = class SlideApi {
5200
5253
  propagation = false; // по клику на варианты ответа(даже на законченной викторине) не делаем клик на слайде
5201
5254
  }
5202
5255
  }
5256
+ /** reactions */
5257
+ if (target?.classList.contains("narrative-element-reaction")) {
5258
+ element = target;
5259
+ }
5260
+ else {
5261
+ element = target?.closest(".narrative-element-reaction");
5262
+ }
5263
+ if (element) {
5264
+ if (this.layoutService.layoutApi.widgetReactionsApi) {
5265
+ propagation = this.layoutService.layoutApi.widgetReactionsApi.select(element);
5266
+ propagation = false;
5267
+ }
5268
+ }
5203
5269
  /** test */
5204
5270
  if (target?.classList.contains("narrative-element-test-answer")) {
5205
5271
  element = target;
@@ -6317,7 +6383,7 @@ class Slider {
6317
6383
  timer.classList.add("cards-slider__timer--reverse-direction");
6318
6384
  }
6319
6385
  const timeline = document.createElement("div");
6320
- timeline.classList.add("cards-slider__timer_timeline", "touchable");
6386
+ timeline.classList.add("cards-slider__timer_timeline");
6321
6387
  const timelineFill = document.createElement("div");
6322
6388
  timelineFill.classList.add("cards-slider__timer_timeline-fill");
6323
6389
  timeline.append(timelineFill);
@@ -6483,6 +6549,8 @@ class Slider {
6483
6549
  }
6484
6550
  }
6485
6551
  async updateTimeline(slideIndex, action, currentTime, duration, showLoader, showError) {
6552
+ // Don't use <activeSlide> and <activeIndex>, as <slideIndex> may differ from <activeIndex>
6553
+ const slide = this.slides[slideIndex];
6486
6554
  switch (action) {
6487
6555
  case "before_start" /* TIMELINE_ACTION.BEFORE_START */: {
6488
6556
  // switch timeline to active slide and wait for start (wait VOD loading)
@@ -6514,7 +6582,7 @@ class Slider {
6514
6582
  // we must resume timer - for trigger done callback and hide Card (SingleSlideTimer business logic)
6515
6583
  }
6516
6584
  if (resumeTimer) {
6517
- this.activeSlide?.timer.resume(currentTime, duration);
6585
+ slide?.timer.resume(currentTime, duration);
6518
6586
  }
6519
6587
  break;
6520
6588
  }
@@ -6522,7 +6590,7 @@ class Slider {
6522
6590
  if (showLoader) {
6523
6591
  this.config.onSlideDataWaiting();
6524
6592
  }
6525
- this.activeSlide?.timer.pause();
6593
+ slide?.timer.pause();
6526
6594
  if (this.isSingleSlideTimerActive) {
6527
6595
  this.pausedAt = new Date().getTime();
6528
6596
  }
@@ -6534,7 +6602,7 @@ class Slider {
6534
6602
  if (showError) {
6535
6603
  this.config.onSlideDataError();
6536
6604
  }
6537
- this.activeSlide?.timer.stop();
6605
+ slide?.timer.stop();
6538
6606
  // todo нужен STOP когда вручную переключаем слайд на другой
6539
6607
  // console.log("TIMELINE_ACTION.STOP", { activeSlide: this.activeSlide, duration });
6540
6608
  break;
@@ -6609,6 +6677,22 @@ class CardApi {
6609
6677
  this._overlappingActionBarHeight = config.overlappingActionBarHeight ?? 0;
6610
6678
  this._separateUserAndAppPause = config.separateUserAndAppPause;
6611
6679
  this._useSdkCacheForMultislideMode = config.useSdkCacheForMultislideMode;
6680
+ let isSafari = false;
6681
+ if (this.config.sdkApi.isIOS) {
6682
+ isSafari = true;
6683
+ }
6684
+ else {
6685
+ if (navigator.vendor &&
6686
+ navigator.vendor.indexOf("Apple") > -1 &&
6687
+ navigator.userAgent &&
6688
+ navigator.userAgent.indexOf("CriOS") == -1 &&
6689
+ navigator.userAgent.indexOf("FxiOS") == -1) {
6690
+ isSafari = true;
6691
+ }
6692
+ }
6693
+ if (isSafari) {
6694
+ this.config.root.classList.add("_isSafari");
6695
+ }
6612
6696
  this.refreshSizes = proxy(this.refreshSizes, this);
6613
6697
  this.getSdkClientVariables = proxy(this.getSdkClientVariables, this);
6614
6698
  this.refreshSizes();
@@ -24125,6 +24209,315 @@ class WidgetVote extends WidgetBase {
24125
24209
  static get [Symbol.for("___CTOR_ARGS___")]() { return [`HTMLElement`, `Partial`, `WidgetCallbacks`, `WidgetDeps`]; }
24126
24210
  }
24127
24211
 
24212
+ var ResultDisplayMode;
24213
+ (function (ResultDisplayMode) {
24214
+ ResultDisplayMode["Hide"] = "hide";
24215
+ ResultDisplayMode["Always"] = "always";
24216
+ ResultDisplayMode["AfterSelection"] = "afterSelection";
24217
+ })(ResultDisplayMode || (ResultDisplayMode = {}));
24218
+ var ResultDisplayFormat;
24219
+ (function (ResultDisplayFormat) {
24220
+ ResultDisplayFormat["Total"] = "total";
24221
+ ResultDisplayFormat["Percentage"] = "percentage";
24222
+ })(ResultDisplayFormat || (ResultDisplayFormat = {}));
24223
+
24224
+ const MIN_DURATION = 2000;
24225
+ const MAX_EXTRA_DURATION = 1500;
24226
+ const MIN_SCALE = 0.8;
24227
+ const SCALE_VARIATION = 0.4;
24228
+ const MAX_DRIFT_X = 40; // [-40, 40]
24229
+ const MAX_DELAY = 300;
24230
+ class ReactionFloatEffect {
24231
+ container;
24232
+ emoji;
24233
+ count;
24234
+ constructor(options) {
24235
+ this.container = options.container;
24236
+ this.emoji = options.emoji;
24237
+ this.count = options.count ?? 6;
24238
+ }
24239
+ animate() {
24240
+ for (let i = 0; i < this.count; i++) {
24241
+ const delay = Math.random() * MAX_DELAY;
24242
+ setTimeout(() => {
24243
+ this.spawnReaction();
24244
+ }, delay);
24245
+ }
24246
+ }
24247
+ spawnReaction() {
24248
+ const el = document.createElement("span");
24249
+ el.className = "narrative-element-reaction--float-effect";
24250
+ el.textContent = this.emoji;
24251
+ const containerWidth = this.container.clientWidth;
24252
+ const thresholdY = this.container.clientHeight / 2;
24253
+ const startX = Math.random() * containerWidth;
24254
+ const driftX = Math.random() * MAX_DRIFT_X * 2 - MAX_DRIFT_X;
24255
+ const duration = MIN_DURATION + Math.random() * MAX_EXTRA_DURATION;
24256
+ const randomScale = MIN_SCALE + Math.random() * SCALE_VARIATION;
24257
+ el.style.left = `${startX}px`;
24258
+ el.style.setProperty("--drift", `${driftX}px`);
24259
+ el.style.setProperty("--y-threshold", `${thresholdY}px`);
24260
+ el.style.setProperty("--duration", `${duration}ms`);
24261
+ el.style.setProperty("--scale", `${randomScale}`);
24262
+ this.container.appendChild(el);
24263
+ setTimeout(() => {
24264
+ el.remove();
24265
+ }, duration);
24266
+ }
24267
+ static get [Symbol.for("___CTOR_ARGS___")]() { return [`ReactionFloatEffectOptions`]; }
24268
+ }
24269
+
24270
+ class WidgetReactions extends WidgetBase {
24271
+ static DEFAULTS = {
24272
+ slide: null,
24273
+ activateAfterCreate: false,
24274
+ create: false,
24275
+ localData: {},
24276
+ layers: [],
24277
+ };
24278
+ static widgetClassName = "narrative-element-reactions";
24279
+ model;
24280
+ reactions;
24281
+ constructor(element, options, widgetCallbacks, widgetDeps) {
24282
+ super(element, options, widgetCallbacks, widgetDeps);
24283
+ this.model = this.createReactionsModel();
24284
+ this.reactions = Array.from(this.element.querySelectorAll(".narrative-element-reaction"));
24285
+ }
24286
+ onRefreshUserData(localData) {
24287
+ super.onRefreshUserData(localData);
24288
+ const data = this.getFromLocalData();
24289
+ if (data.selectedIndex == null || data.widgetDoneAt == null || this.reactions[data.selectedIndex] === undefined) {
24290
+ this.resetWidget();
24291
+ }
24292
+ else {
24293
+ const reaction = this.reactions[data.selectedIndex];
24294
+ this.initFromLocalData({ reaction, selectedIndex: data.selectedIndex, widgetDoneAt: data.widgetDoneAt });
24295
+ }
24296
+ this.firstOpenTime = new Date().getTime();
24297
+ }
24298
+ resetWidget() {
24299
+ for (const reaction of this.reactions) {
24300
+ reaction.classList.remove("narrative-element-reaction--selected");
24301
+ }
24302
+ this.element.classList.remove("narrative-element-reactions--done", "narrative-element-reactions--reacted");
24303
+ if (this.model.resultDisplayMode === ResultDisplayMode.Always) {
24304
+ const summary = this.getReactionsSummary();
24305
+ this.displayResults(summary.allocation);
24306
+ }
24307
+ }
24308
+ select(reaction) {
24309
+ try {
24310
+ if (this.isDone())
24311
+ return;
24312
+ const index = this.reactions.indexOf(reaction);
24313
+ if (index === -1)
24314
+ return;
24315
+ reaction.classList.add("narrative-element-reaction--selected");
24316
+ this.element.classList.add("narrative-element-reactions--reacted");
24317
+ this.completeWidget(index);
24318
+ }
24319
+ catch (error) {
24320
+ console.error(error);
24321
+ }
24322
+ }
24323
+ isDone() {
24324
+ return this.getFromLocalData().selectedIndex != null;
24325
+ }
24326
+ showAnimationAfterSelection(emoji) {
24327
+ if (!this.model.showAnimationAfterSelection)
24328
+ return;
24329
+ const geometryParent = this.element.closest(".narrative-slide-elements");
24330
+ if (!geometryParent)
24331
+ return;
24332
+ new ReactionFloatEffect({ container: geometryParent, emoji, count: 15 /* fontSize: getComputedStyle(this.reactions[0]).fontSize */ }).animate();
24333
+ }
24334
+ initFromLocalData({ selectedIndex, widgetDoneAt, reaction }) {
24335
+ try {
24336
+ const summary = this.getReactionsSummary();
24337
+ let allocation = summary.allocation;
24338
+ if (summary.serverTimestamp == null || widgetDoneAt > summary.serverTimestamp) {
24339
+ allocation = this.incrementAllocationByIndex(selectedIndex);
24340
+ }
24341
+ this.markWidgetAsDone(reaction);
24342
+ this.displayResults(allocation);
24343
+ this.startReadyPromise.then(() => {
24344
+ if (this.disableTimer) {
24345
+ this.onWidgetComplete();
24346
+ }
24347
+ });
24348
+ }
24349
+ catch (error) {
24350
+ console.error(error);
24351
+ }
24352
+ }
24353
+ createReactionsModel() {
24354
+ return {
24355
+ icons: getTagData(this.element, "icons")?.split(",") ?? [],
24356
+ showAnimationAfterSelection: getTagData(this.element, "showAnimationAfterSelection") === "true",
24357
+ resultDisplayMode: getTagData(this.element, "resultDisplayMode"),
24358
+ resultDisplayFormat: getTagData(this.element, "resultDisplayFormat"),
24359
+ };
24360
+ }
24361
+ displayResults(results) {
24362
+ try {
24363
+ switch (this.model.resultDisplayFormat) {
24364
+ case ResultDisplayFormat.Total:
24365
+ this.displayTotalResults(results);
24366
+ break;
24367
+ case ResultDisplayFormat.Percentage:
24368
+ this.displayPercentageResults(results);
24369
+ break;
24370
+ }
24371
+ }
24372
+ catch (error) {
24373
+ console.error(error);
24374
+ }
24375
+ }
24376
+ displayPercentageResults(counts) {
24377
+ const totalCount = counts.reduce((sum, value) => sum + value, 0);
24378
+ if (totalCount === 0)
24379
+ return;
24380
+ const formattedResults = counts.map(count => {
24381
+ const percent = Math.min(Math.round((count / totalCount) * 1000) / 10, 100);
24382
+ return `${percent}%`;
24383
+ });
24384
+ this.renderResults(formattedResults);
24385
+ }
24386
+ displayTotalResults(counts) {
24387
+ const formattedResults = counts.map(count => {
24388
+ if (count >= 1000000) {
24389
+ const value = count / 1000000;
24390
+ return `${+value.toPrecision(3)}M`;
24391
+ }
24392
+ if (count >= 1000) {
24393
+ const value = count / 1000;
24394
+ return `${+value.toPrecision(3)}K`;
24395
+ }
24396
+ return count.toString();
24397
+ });
24398
+ this.renderResults(formattedResults);
24399
+ }
24400
+ renderResults(results) {
24401
+ if (this.model.resultDisplayMode === ResultDisplayMode.Hide)
24402
+ return;
24403
+ this.reactions.forEach((reaction, index) => {
24404
+ const resultEl = reaction.querySelector(".narrative-element-reaction__result");
24405
+ if (!resultEl)
24406
+ return;
24407
+ resultEl.textContent = results[index];
24408
+ });
24409
+ }
24410
+ markWidgetAsDone(reaction) {
24411
+ reaction.classList.add("narrative-element-reaction--selected");
24412
+ this.element.classList.add("narrative-element-reactions--done");
24413
+ }
24414
+ getReactionsSummary() {
24415
+ const sharedData = this.widgetDeps.slideApiDeps.getWidgetsSharedData(this.cardId, "reactions" /* Widgets.Reactions */);
24416
+ let allocation = [];
24417
+ let timestamp = null;
24418
+ if (this.hasValidSharedData(sharedData)) {
24419
+ allocation = sharedData[this.elementId].slice();
24420
+ timestamp = sharedData.ts;
24421
+ }
24422
+ this.reactions.forEach((reaction, index) => {
24423
+ if (allocation[index] == null || !isNumber(allocation[index]))
24424
+ allocation[index] = 0;
24425
+ });
24426
+ return {
24427
+ allocation,
24428
+ serverTimestamp: timestamp,
24429
+ };
24430
+ }
24431
+ hasValidSharedData(sharedData) {
24432
+ if (!sharedData || sharedData[this.elementId] == null) {
24433
+ return false;
24434
+ }
24435
+ const elementData = sharedData[this.elementId];
24436
+ return isArray(elementData);
24437
+ }
24438
+ completeWidget(index) {
24439
+ this.saveToLocalData(index);
24440
+ this.sendStatEvent(index);
24441
+ this.showAnimationAfterSelection(this.model.icons[index]);
24442
+ const results = this.incrementAllocationByIndex(index);
24443
+ this.displayResults(results);
24444
+ this.markWidgetAsDone(this.reactions[index]);
24445
+ if (this.disableTimer) {
24446
+ this.onWidgetComplete();
24447
+ }
24448
+ }
24449
+ sendStatEvent(selectedIndex) {
24450
+ try {
24451
+ const duration = new Date().getTime() - this.firstOpenTime;
24452
+ this.sendStatisticEventToApp("w-reactions-answer", {
24453
+ ...this.statisticEventBaseFieldsShortForm,
24454
+ wi: this.elementId,
24455
+ wa: selectedIndex,
24456
+ d: duration,
24457
+ }, {
24458
+ ...this.statisticEventBaseFieldsFullForm,
24459
+ widget_id: this.elementId,
24460
+ widget_answer: selectedIndex,
24461
+ duration_ms: duration,
24462
+ });
24463
+ }
24464
+ catch (error) {
24465
+ console.error(error);
24466
+ }
24467
+ }
24468
+ getLocalDataKeys() {
24469
+ return {
24470
+ selectedIndex: "_re_g_" + this.elementId + "_r",
24471
+ widgetDoneAt: "_re_g_" + this.elementId + "_done_at",
24472
+ selectedAt: "_&ts_re_g_" + this.elementId + "_a_at",
24473
+ };
24474
+ }
24475
+ getFromLocalData() {
24476
+ const keys = this.getLocalDataKeys();
24477
+ return {
24478
+ selectedIndex: this.localData[keys.selectedIndex],
24479
+ widgetDoneAt: this.localData[keys.widgetDoneAt],
24480
+ };
24481
+ }
24482
+ saveToLocalData(selectedIndex) {
24483
+ const keys = this.getLocalDataKeys();
24484
+ const time = Math.round(new Date().getTime() / 1000);
24485
+ this.localData[keys.selectedIndex] = selectedIndex;
24486
+ this.localData[keys.widgetDoneAt] = time;
24487
+ this.localData[keys.selectedAt] = time;
24488
+ this.setLocalData(this.localData, true);
24489
+ }
24490
+ incrementAllocationByIndex(index) {
24491
+ const reactionsSummary = this.getReactionsSummary();
24492
+ if (reactionsSummary.allocation[index] == null)
24493
+ throw new Error(`No reaction allocation for the index <${index}>. Allocation: ${reactionsSummary.allocation.join(",")}`);
24494
+ reactionsSummary.allocation[index]++;
24495
+ return reactionsSummary.allocation;
24496
+ }
24497
+ static api = {
24498
+ widgetClassName: WidgetReactions.widgetClassName,
24499
+ onRefreshUserData: WidgetReactions.onRefreshUserData,
24500
+ init: function (element, localData, widgetCallbacks, widgetDeps) {
24501
+ WidgetReactions.initWidget(element, localData, (element, options) => new WidgetReactions(element, { ...options }, widgetCallbacks, widgetDeps));
24502
+ },
24503
+ onStart: function (element) {
24504
+ WidgetReactions.getInstance(element)?.onStart();
24505
+ },
24506
+ onStop: function (element) {
24507
+ WidgetReactions.getInstance(element)?.onStop();
24508
+ },
24509
+ select: function (element) {
24510
+ const widgetElement = element.closest(`.${WidgetReactions.widgetClassName}`);
24511
+ if (widgetElement) {
24512
+ const widget = WidgetReactions.getInstance(widgetElement);
24513
+ widget?.select(element);
24514
+ }
24515
+ return false;
24516
+ },
24517
+ };
24518
+ static get [Symbol.for("___CTOR_ARGS___")]() { return [`HTMLElement`, `Partial`, `WidgetCallbacks`, `WidgetDeps`]; }
24519
+ }
24520
+
24128
24521
  class EsModuleLayoutApi {
24129
24522
  slideApiPeerDeps;
24130
24523
  constructor(slideApiPeerDeps) {
@@ -24184,6 +24577,9 @@ class EsModuleLayoutApi {
24184
24577
  get widgetTimerApi() {
24185
24578
  return WidgetTimer.api;
24186
24579
  }
24580
+ get widgetReactionsApi() {
24581
+ return WidgetReactions.api;
24582
+ }
24187
24583
  get VideoPlayer() {
24188
24584
  return this.slideApiPeerDeps().VODPlayer;
24189
24585
  }