initializeWidget method

Future<void> initializeWidget(
  1. String domainName,
  2. String targetToken
)

Implementation

Future<void> initializeWidget(String domainName, String targetToken) async {
  try {
    final Uri url = Uri.parse(
        'https://$domainName/api/internal/spotcheck/widget/$targetToken/init');

    final response = await http.get(url);
    if (response.statusCode != 200) {
      log('Error fetching widget data: ${response.statusCode}');
      return;
    }

    final data = json.decode(response.body) as Map<String, dynamic>;
    if (data['filteredSpotChecks'] != null) {
      filteredSpotChecks.value =
          List<dynamic>.from(data['filteredSpotChecks']);
    }

    bool isClassicIframe = false, isChatIframe = false;

    for (final spotcheck in filteredSpotChecks) {
      final String mode = spotcheck['appearance']['mode'] as String;
      final String? surveyType =
          spotcheck['survey']?['surveyType'] as String?;

      if (mode == 'card' || mode == 'fullScreen' || mode=='miniCard') {
        isClassicIframe = true;
        if (mode == 'fullScreen' && isChatSurvey(surveyType)) {
          isChatIframe = true;
        }
      }
    }

    chatUrl.value =
        isChatIframe ? 'https://$domainName/eui-template/chat?isSpotCheck=true' : '';
    classicUrl.value =
        isClassicIframe ? 'https://$domainName/eui-template/classic?isSpotCheck=true' : '';

    void setupWebViewController(
        WebViewController controller, String url, RxBool loadingState) {
      controller
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..loadRequest(Uri.parse(url))
        ..setNavigationDelegate(NavigationDelegate(
          onPageFinished: (_) {
            controller.runJavaScript(
                """
        document.addEventListener('focusin', function(event) {
          if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
            var rect = event.target.getBoundingClientRect();
            var yPosition = rect.y + window.scrollY;
            var webViewHeight = window.innerHeight;
            var scaledY = (yPosition / webViewHeight) * ${screenHeight};

            flutterSpotCheckData.postMessage(JSON.stringify({
              type: 'position',
              y: scaledY
            }));
          }
        });
        (function() {
          var id = 'ss-sdk-lang-close-margin';
          if (!document.getElementById(id)) {
            var el = document.createElement('style');
            el.id = id;
            el.textContent =
              '.ss-language-selector--wrapper--spotcheck-sdk{margin-right:45px;}' +
              '.ss-eui-wrapper--rtl .ss-language-selector--wrapper--spotcheck-sdk{margin-left:25px;margin-right:0;}' +
              '.ss-eui-wrapper--rtl .ss-language-selector--wrapper.ss-language-selector--spotchecks{left:62px;right:auto;}' +
              '.ss-eui-wrapper--rtl .ss-language-selector--wrapper.ss-language-selector--spotchecks-no-close-btn{left:24px;right:auto;}';
            (document.head || document.documentElement).appendChild(el);
          }
        })();
        """
            );
          },
        ))
        ..addJavaScriptChannel("flutterSpotCheckData",
            onMessageReceived: (response) async {
              try {
                var jsonResponse = json.decode(response.message);
                if (jsonResponse['type'] == "spotCheckData") {
                  if(jsonResponse['data']['currentQuestionSize']!=null){
                    if(isFirstQuestion.value && isSurveyLoaded.value && spotChecksMode.value == 'miniCard'){
                      isFirstQuestion.value = false;
                    }
                    else {
                      var currentQuestionHeight = jsonResponse['data']['currentQuestionSize']['height'] ?? 0.0;
                      if (spotChecksMode.value == 'miniCard' && isCloseButtonEnabled.value) {
                        currentQuestionHeight += 8;
                      }

                      if (spotChecksMode.value == 'miniCard' && avatarEnabled.value) {
                        currentQuestionHeight += 8;
                      }

                      this.currentQuestionHeight.value = currentQuestionHeight;
                    }
                  }



                }
                else if (jsonResponse['type'] == "classicLoadEvent") {
                  isClassicLoading.value = false;
                }
                else if (jsonResponse['type'] == "chatLoadEvent") {
                  isChatLoading.value = false;
                }
                else if (jsonResponse['type'] == "surveyCompleted") {
                  await spotCheckListener?.onSurveyResponse(jsonResponse);
                  end();
                }
                else if(jsonResponse['type'] == 'surveyLoadStarted'){
                  isSurveyLoaded.value = true;
                  await spotCheckListener?.onSurveyLoaded(jsonResponse);
                }
              else if(jsonResponse['type'] == 'partialSubmission'){
                  await spotCheckListener?.onPartialSubmission(jsonResponse);
                }
              else if(jsonResponse['type'] == 'thankYouPageSubmission'){
                  isCloseButtonEnabled.value = false;
                   Timer(const Duration(seconds: 4), () {
                      end();
                    });
                  await spotCheckListener?.onSurveyResponse(jsonResponse);
              }
              else if (jsonResponse['type'] == 'languageChanged') {
                  isRtl.value = jsonResponse['data']?['isRtl'] ?? false;
                }
              else if (jsonResponse["type"] == 'slideInFrame') {
                  isMounted.value = true;
                } else if (jsonResponse["type"] == 'position') {
                  if(Platform.isAndroid) {
                    textPosition.value = jsonResponse["y"];
                    ever(currentKeyboardHeight, (
                        double currentKeyboardHeight) {
                      if (currentKeyboardHeight > 0) {
                        if(spotCheckType.value=="chat"){
                          _chatscrollController.animateTo(
                            currentKeyboardHeight,
                            duration: const Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                          );
                        }

                        else if (textPosition.value - currentKeyboardHeight - 175 >
                            0)
                          _scrollController.animateTo(
                            textPosition.value - currentKeyboardHeight - 175,
                            duration: const Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                          );
                      }
                    });
                  }
                }
              } catch (e) {
                log("Error decoding JSON: $e");
              }
            })
        ..addJavaScriptChannel("SsFlutterSdk", onMessageReceived: (response) {
          if (response.message == 'captureImage') {
            _captureImage();
          }
        });
    }

    if (isChatIframe) {
      chatController.value = WebViewController(
        onPermissionRequest: (WebViewPermissionRequest request) => request.grant(),
      );
      setupWebViewController(
          chatController.value!, chatUrl.value, isChatLoading);
    }

    if (isClassicIframe) {
      classicController.value = WebViewController(
        onPermissionRequest: (WebViewPermissionRequest request) => request.grant(),
      );
      setupWebViewController(
          classicController.value!, classicUrl.value, isClassicLoading);
    }

    if (isChatIframe || isClassicIframe) {
      isInit.value = true;
    }

  } catch (error) {
    log('Error initializing widget: $error');
  }
}