Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions webviewer-ask-ai/__mocks__/webviewer-ask-ai.mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// This file provides mock implementations for the webviewer-ask-ai module,
// allowing developers to test and develop features without relying on actual
// API calls.

// The mock responses are predefined based on specific prompt lines,
// simulating the behavior of the real module in a controlled environment.
const MOCK_RESPONSES = {
DOCUMENT_QUESTION: 'In 2011, Rosneft undertook several social responsibility initiatives, including: 1. Support for education by providing RUB 141 million to higher education institutions and extending loans totaling RUB 3.6 million to 97 workers for educational courses. 2. Charity efforts focused on socio-economic projects, healthcare, education, culture, and sports, with a total spending of RUB 2.9 billion on charity. 3. Maintenance of social infrastructure, with spending of RUB 1.0 billion aimed at optimizing facilities for employees and communities [14][15].',
SELECTED_TEXT_SUMMARY: 'The Tuapse license area covers 12,000 square km in the Black Sea and has geological similarities to the West-Kuban Trough, a historic oil production region in Russia [6]. The Tuapse Block has undergone comprehensive 2D seismic work, with the most promising areas also analyzed using 3D seismic technology [6]. Current data indicates the presence of 20 promising structures with an estimated 8.9 billion barrels of recoverable oil resources [6].'
};

// Checks if the application is running in mocking mode,
// which can be determined by checking a specific environment variable.
// This allows developers to easily switch between real and mock
// implementations based on their development needs.
export const isMockingModeEnabled = () => {
if (typeof window !== 'undefined')

Check warning on line 17 in webviewer-ask-ai/__mocks__/webviewer-ask-ai.mock.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `globalThis.window` over `window`.

See more on https://sonarcloud.io/project/issues?id=ApryseSDK_webviewer-samples&issues=AZzy4qAhnvODKcpv5P1K&open=AZzy4qAhnvODKcpv5P1K&pullRequest=83
return window.MODE_ENV === 'mocking';

Check warning on line 18 in webviewer-ask-ai/__mocks__/webviewer-ask-ai.mock.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `globalThis` over `window`.

See more on https://sonarcloud.io/project/issues?id=ApryseSDK_webviewer-samples&issues=AZzy4qAhnvODKcpv5P1L&open=AZzy4qAhnvODKcpv5P1L&pullRequest=83

return process.env.NODE_ENV === 'mocking';
};

// Simulates an API call to get a chat response based on
// the provided prompt line. It returns a promise that
// resolves with the corresponding mock response after a delay,
// mimicking the asynchronous nature of real API calls.
export const getMockChatResponse = (promptLine) => {
const mockResponse = MOCK_RESPONSES[promptLine] || '';

return new Promise((resolve) => {
setTimeout(() => {
resolve(mockResponse);
}, 1000);
});
};
108 changes: 108 additions & 0 deletions webviewer-ask-ai/__tests__/e2e/webviewer-ask-ai.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// This file contains end-to-end tests for the WebViewer Ask AI sample application,
// using the Playwright testing framework.

import { test, expect } from '@playwright/test';

// Validate the existence of key components in the DOM,
// such as the chatbot panel and its toggle button,
// as well as the askWebSDKButton in the text selection popup.
test('Components existence validation in DOM', async ({ page }) => {
// Go to the app page (adjust the URL if needed)
await page.goto('/client/index.html');

// Locate the askWebSDKPanelToggle button in ModularHeader
let component = page.locator('#viewer apryse-webviewer #app .App nav .ModularHeader .ModularHeaderItems .ToggleElementButton button[data-element="askWebSDKPanelToggle"]');
await expect(component).toHaveCount(1);
await expect(component).toBeVisible();

// Wait for 5 seconds to ensure the app is fully loaded
await page.waitForTimeout(5000);

Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated
// Locate the askWebSDKPanel panel in ModularPanel
component = page.locator('#viewer apryse-webviewer #app .App .content div.ModularPanel[data-element="askWebSDKPanel"]');
await expect(component).toHaveCount(1);
await expect(component).toBeVisible();

// Locate the askWebSDKButton button in the TextPopup
await page.evaluate((pageNumber) => {
const core = WebViewer.getInstance().Core;
const UI = WebViewer.getInstance().UI;
const documentViewer = core.documentViewer;
const textSelectTool = documentViewer.getTool(core.Tools.ToolNames.TEXT_SELECT);
documentViewer.setCurrentPage(pageNumber);
UI.setToolMode(core.Tools.ToolNames.TEXT_SELECT);
textSelectTool.select({ pageNumber: pageNumber, x: 56.69320848, y: 32.4018533200001 }, { pageNumber: pageNumber, x: 105.11567196000001, y: 40.06439572000011 });
setTimeout(() => {
UI.openElements(['textPopup']);
}, 1000);
}, 2);

component = page.locator('#viewer apryse-webviewer #app .App .Popup.TextPopup .container button[data-element="askWebSDKButton"]');
await expect(component).toHaveCount(1);
await expect(component).toBeVisible();
});

// Simulates user asking free question within the chatbot interface
test('Ask free question', async ({ page }) => {
await askQuestion(page);
Comment thread
DavidEGutierrez marked this conversation as resolved.
Outdated
});
Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated

// Simulates user selecting text on the document and asking the chatbot to summarize it
test('Summarize selected text', async ({ page }) => {
Comment thread
DavidEGutierrez marked this conversation as resolved.
// Go to the app page (adjust the URL if needed)
await page.goto('/client/index.html');

// Wait for 10 seconds to ensure the app is fully loaded
await page.waitForTimeout(10000);
Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated

// Select text on the document programmatically, to be summarized
await page.evaluate((pageNumber) => {
const core = WebViewer.getInstance().Core;
const UI = WebViewer.getInstance().UI;
const documentViewer = core.documentViewer;
const textSelectTool = documentViewer.getTool(core.Tools.ToolNames.TEXT_SELECT);
documentViewer.setCurrentPage(pageNumber);
UI.setToolMode(core.Tools.ToolNames.TEXT_SELECT);
// The coordinates used here are based on the PDF document used in this sample.
textSelectTool.select({ pageNumber: pageNumber, x: 179.72459999999998, y: 536.4002 }, { pageNumber: pageNumber, x: 141.165, y: 415.9352 });
setTimeout(() => {
UI.openElements(['textPopup']);
}, 1000);

const items = UI.textPopup.getItems();
const askWebSDKButton = items.find(item => item.dataElement === 'askWebSDKButton');
askWebSDKButton?.onClick();
}, 6);

// Wait for 2 seconds before finishing
// the test to capture the AI response
await page.waitForTimeout(2000);
Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated
});

// Simulates user toggling the visibility of the chatbot panel
test('Hide/Show chatbot panel', async ({ page }) => {
Comment thread
DavidEGutierrez marked this conversation as resolved.
await askQuestion(page);

// Click the toggle button to hide the chatbot panel
const toggleBtn = page.locator('#viewer apryse-webviewer #app .App nav .ModularHeader .ModularHeaderItems .ToggleElementButton button[data-element="askWebSDKPanelToggle"]');
await toggleBtn.click();

// Wait for 1 second between interactions
// to ensure the UI has updated
await page.waitForTimeout(1000);

// Click the toggle button again to show the chatbot panel
await toggleBtn.click();
});
Comment thread
DavidEGutierrez marked this conversation as resolved.

const askQuestion = async (page) => {
// Go to the app page (adjust the URL if needed)
await page.goto('/client/index.html');
// Ask question via input field
await page.fill('#askWebSDKQuestionInput', 'What social responsibility initiatives did Rosneft undertake in 2011?');
// Hit Enter to send the question
await page.press('#askWebSDKQuestionInput', 'Enter');
// Wait for 1 second before finishing
// the test to capture the AI response
await page.waitForTimeout(1000);
};
9 changes: 9 additions & 0 deletions webviewer-ask-ai/__tests__/package.playwright.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Install Playwright and add test script
Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated
Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated
{
"scripts": {
"test": "playwright test"
},
"devDependencies": {
"@playwright/test": "^1.43.1"
}
Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated
}
8 changes: 8 additions & 0 deletions webviewer-ask-ai/client/chatbot/chatbot.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ChatbotResponse from './response.js';
import { ChatbotSpinner } from './spinner.js';
import { getMockChatResponse, isMockingModeEnabled } from '../../__mocks__/webviewer-ask-ai.mock.js';

const spinner = new ChatbotSpinner();

Expand Down Expand Up @@ -47,7 +48,14 @@
return trimmedHistory;
}

async sendMessage(promptLine, message) {

Check failure on line 51 in webviewer-ask-ai/client/chatbot/chatbot.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=ApryseSDK_webviewer-samples&issues=AZzy4p-lnvODKcpv5P1I&open=AZzy4p-lnvODKcpv5P1I&pullRequest=83
// *********************************************
// MOCKING MODE: Return mock responses for
// testing, without backend
if (isMockingModeEnabled())
return getMockChatResponse(promptLine);
// *********************************************
Comment thread
Mohammed-AbdulRahman-Apryse marked this conversation as resolved.
Outdated

try {
// For document-level operations, use increased token limit to preserve messages history
// Adjust token limits based on prompt type to balance document content and messages history
Expand Down Expand Up @@ -204,7 +212,7 @@
let updatedCount = 0;
questionsLIs.forEach((configAndLiTags) => {

if (configAndLiTags[0] && configAndLiTags[0].promptType === 'DOCUMENT_CONTEXTUAL_QUESTION_EXACTLY') {

Check warning on line 215 in webviewer-ask-ai/client/chatbot/chatbot.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using an optional chain expression instead, as it's more concise and easier to read.

See more on https://sonarcloud.io/project/issues?id=ApryseSDK_webviewer-samples&issues=AZzy4p-lnvODKcpv5P1J&open=AZzy4p-lnvODKcpv5P1J&pullRequest=83

if (this.questionsContextuallySound[index] !== undefined) {
let li = configAndLiTags[1];
Expand Down
9 changes: 9 additions & 0 deletions webviewer-ask-ai/client/ui/functionMap.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isMockingModeEnabled } from '../../__mocks__/webviewer-ask-ai.mock.js';

const functionMap = {
// Render the WebViewer chat panel
'askWebSDKPanelRender': () => {
Expand All @@ -12,6 +14,13 @@ const functionMap = {
return;
}

// **********************************
// MOCKING MODE: Clear initial assistant
// messages for testing, without backend
if (isMockingModeEnabled())
configData.ASSISTANT_MESSAGES = [];
// **********************************

// The main container div
askWebSDKMainDiv = document.createElement('div');
askWebSDKMainDiv.id = 'askWebSDKMainDiv';
Expand Down
Loading
Loading