### Start Local Development Server
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/README.md
Starts a local development server for live preview. Changes are reflected without server restart.
```bash
yarn start
```
--------------------------------
### Install Dependencies with Yarn
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/README.md
Run this command to install all project dependencies using Yarn.
```bash
yarn
```
--------------------------------
### Install SBA Framework Libraries
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/guides/3-development.md
Use npm to install the core Sinequa SBA framework libraries. The `--legacy-peer-deps` flag is recommended to avoid automatic peer dependency installation, allowing for manual management.
```bash
npm install @sinequa/core @sinequa/components @sinequa/analytics --legacy-peer-deps
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/sinequa/sba-angular/blob/master/README.md
Run this command after cloning the repository to install all necessary Node.js dependencies.
```bash
npm install
```
--------------------------------
### Help Folder JSON Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/startup.md
Example JSON structure for configuring help folder options in the administration page.
```json
{
"help-folder-options": {
"folder": string,
"path": string,
"indexFile": string,
"useLocale": boolean,
"useLocaleAsPrefix": boolean
}
}
```
--------------------------------
### Basic Search Form Example
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/search-form.md
A simple example demonstrating the usage of the `sq-search-form` component.
```APIDOC
## Examples
A more complex example could be what Pepper does which includes an `sq-filters-view` to allow adding filters to the query, then an `sq-facet-container` to display the filters when we select a category, and finally the `app-autocomplete` (taken from [Vanilla Search](../../apps/vanilla-search)) to display the suggestions.
```html
{{'msg#searchForm.currentFilters' | sqMessage}}
```
```
--------------------------------
### TypeScript Module Example
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/intro.md
Demonstrates a basic TypeScript module with import and export statements.
```typescript
import { a } from './foo';
console.log(a);
export const b = a + 42;
```
--------------------------------
### Define StartConfig in app.module.ts
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/environment.md
This snippet shows how to import environment variables and use them to define the start configuration for your Sinequa SBA application.
```typescript
import { environment } from "../environments/environment";
export const startConfig: StartConfig = {
url: environment.url,
app: environment.app,
production: environment.production,
auditEnabled: environment.auditEnabled,
autoSAMLProvider: environment.autoSAMLProvider
};
```
--------------------------------
### Configure Sinequa Start Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/connection.md
Define the `startConfig` object with your Sinequa application name, auto-OAuth provider, and production settings. This configuration is passed to `WebServiceModule` to establish the connection.
```typescript
export const startConfig: StartConfig = {
app: "training",
autoOauthProvider: "identity-dev",
production: environment.production,
auditEnabled: true
};
```
--------------------------------
### Angular Module Example
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/intro.md
Shows a simple Angular module definition that imports another module.
```typescript
import { AnotherModule } from './foo';
@NgModule({
imports: [
AnotherModule
]
})
export class MyModule {}
```
--------------------------------
### Clone Sinequa SBA Angular Repository
Source: https://github.com/sinequa/sba-angular/blob/master/README.md
Use this command to clone the project repository. Ensure you have Git installed.
```bash
git clone https://github.com/sinequa/sba-angular.git
```
--------------------------------
### BsLabelsAutocomplete Component Example
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/labels.md
This example shows how to use the BsLabelsAutocomplete component, which is a key part of the Modals components. It functions as an input element with autocomplete capabilities for labels.
```html
```
--------------------------------
### Internationalization Setup
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/search.md
Include the search module's messages in your application's locale files for internationalization.
```typescript
import {enSearch} from "@sinequa/components/search";
const messages = Utils.merge({}, ..., enSearch, appMessages);
```
--------------------------------
### Importing Sinequa Stylesheet
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/intro.md
Provides an example of importing a Sinequa library's global stylesheet into your main SCSS file for proper component styling.
```scss
@importĀ "../../../components/facet/bootstrap/facet.scss";
```
--------------------------------
### Inject Hard-coded Credentials for Development
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/releases/release-11-10-0.md
Example of how to provide hard-coded username and password for development or CI purposes using the CREDENTIALS token.
```typescript
{provide: CREDENTIALS, useValue: {username: "", password: ""}}
```
--------------------------------
### Create New Angular Workspace
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/guides/3-development.md
Initialize a new Angular workspace using the Angular CLI and navigate into the project directory. This serves as a foundation for installing SBA Framework libraries.
```bash
# Create a new Angular workspace
ng new my-project
cd my-project
```
--------------------------------
### Facet Configuration Example (TypeScript)
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/apps/2-vanilla-search.md
Defines the structure for a facet configuration object, including its name, aggregation, title, type, icon, and parameters. Ensure a corresponding aggregation exists on the Sinequa server.
```typescript
{
name: "geo",
aggregation: "Geo",
title: "msg#facet.geo.title",
type: "list",
icon: "fas fa-fw fa-globe-americas",
parameters: {
showCount: true,
searchable: true,
focusSearch: true,
allowExclude: true,
allowOr: true,
allowAnd: false,
displayEmptyDistributionIntervals: false,
}
}
```
--------------------------------
### MultiLevelPieChart with Custom Data
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/fusioncharts.md
This example demonstrates using the `data` input to provide custom data for the MultiLevelPieChart. When `data` is provided, the `aggregation` input is ignored.
```html
```
--------------------------------
### App Module Configuration (app.module.ts)
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/completed-app.md
This is the main application module file. It imports all necessary Sinequa modules and components, sets up routing, and defines the application's start configuration and locale settings.
```typescript
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { RouterModule } from '@angular/router';
import { LocationStrategy, HashLocationStrategy } from "@angular/common";
import { HTTP_INTERCEPTORS } from "@angular/common/http";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { Observable, from } from "rxjs";
import { WebServicesModule, StartConfigWebService, StartConfig } from "@sinequa/core/web-services";
import { LoginModule, LoginInterceptor } from "@sinequa/core/login";
import { IntlModule, LocaleData, LocalesConfig, Locale } from "@sinequa/core/intl";
import { ModalModule } from "@sinequa/core/modal";
import { NotificationsInterceptor } from "@sinequa/core/notification";
import { AuditInterceptor } from "@sinequa/core/app-utils";
import { BsSearchModule } from '@sinequa/components/search';
import { BsFacetModule } from '@sinequa/components/facet';
import { BsActionModule } from '@sinequa/components/action';
import { PreviewModule } from '@sinequa/components/preview';
import { BsModalModule } from '@sinequa/components/modal';
import { BsSavedQueriesModule } from '@sinequa/components/saved-queries';
import { SearchFormComponent } from "@sinequa/components/search-form";
import { environment } from "../environments/environment";
import { AppComponent } from "./app.component";
import { Preview } from "./preview";
import { HomeComponent } from './home/home.component';
import { SearchComponent } from './search/search.component';
import { Autocomplete } from "./autocomplete";
import { SearchFormComponent as AppSearchFormComponent } from './search-form/search-form.component';
import { SCREEN_SIZE_RULES } from '@sinequa/components/utils';
export const startConfig: StartConfig = {
app: "training",
autoOauthProvider: "identity-dev",
production: environment.production,
auditEnabled: true
};
// Locales configuration
export class AppLocalesConfig implements LocalesConfig {
locales: Locale[] = [
{ name: "en", display: "msg#locale.en" },
{ name: "fr", display: "msg#locale.fr" }
];
defaultLocale: Locale = this.locales[0];
loadLocale(locale: string): Observable {
return from(import('../locales/' + locale).then(m => m.default));
}
}
export function StartConfigInitializer(startConfigWebService: StartConfigWebService) {
return () => startConfigWebService.fetchPreLoginAppConfig();
}
// Screen size breakpoints (must be consistent with Bootstrap custom breakpoints in styles/app.scss)
export const breakpoints = {
lg: "(min-width: 1000px)",
sm: "(min-width: 600px) and (max-width: 999px)",
xs: "(max-width: 599px)",
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot([
{ path: "home", component: HomeComponent },
{ path: "search", component: SearchComponent },
{ path: "**", redirectTo: "home" }
]),
FormsModule,
ReactiveFormsModule,
WebServicesModule.forRoot(startConfig),
IntlModule.forRoot(AppLocalesConfig),
LoginModule.forRoot(), // Just use default login modal
ModalModule.forRoot(),
BsSearchModule.forRoot({ routes: ['search'] }),
BsFacetModule,
BsActionModule,
PreviewModule,
BsModalModule,
SearchFormComponent,
BsSavedQueriesModule
],
declarations: [
AppComponent,
Preview,
Autocomplete,
HomeComponent,
SearchComponent,
AppSearchFormComponent
],
providers: [
// Provides an APP_INITIALIZER which will fetch application configuration information from the Sinequa
// server automatically at startup using the application name specified in the URL (app[-debug]/).
// This allows an application to avoid hard-coding parameters in the StartConfig but requires that the application
// be served from the an app[-debug]/ URL.
// {provide: APP_INITIALIZER, useFactory: StartConfigInitializer, deps: [StartConfigWebService], multi: true},
// Provides the Angular LocationStrategy to be used for reading route state from the browser's URL. Currently
// only the HashLocationStrategy is supported by Sinequa.
{ provide: LocationStrategy, useClass: HashLocationStrategy },
// Provides an HttpInterceptor to handle user login. The LoginInterceptor handles HTTP 401 responses
// to Sinequa web service requests and initiates the login process.
{ provide: HTTP_INTERCEPTORS, useClass: LoginInterceptor, multi: true },
// Provides an HttpInterceptor that offers a centralized location through which all client-side
// audit records pass. An application can replace AuditInterceptor with a subclass that overrides
```
--------------------------------
### Define Routes in App Module
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/routing.md
Configure the application's routes in app.module.ts using RouterModule.forRoot. This example sets up 'home', 'search', and a wildcard route redirecting to 'home'.
```typescript
@NgModule({
imports: [
...
RouterModule.forRoot([
{path: "home", component: HomeComponent},
{path: "search", component: SearchComponent},
{path: "**", redirectTo: "home"}
]),
```
--------------------------------
### Chat Component with Predefined Messages and Attachments
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/machine-learning.md
Example of how to pre-populate the chat with messages and attachments, such as a summary prompt and document passages. The `chat` object needs to be constructed with `messages` and `attachments`.
```typescript
const passages = this.searchService.results?.topPassages?.passages;
if(passages?.length) {
const attachments = this.chatService.addTopPassages(passages, []);
const prompt = `Please generate a summary of these passages`;
const messages = [
{role: 'system', display: false, content: prompt}
];
this.chat = {messages, attachments};
}
```
```html
```
--------------------------------
### Serve Vanilla-Search Application
Source: https://github.com/sinequa/sba-angular/blob/master/README.md
Build and serve the Vanilla-Search application for testing. Requires a Sinequa account for the demo server and uses SSL and a proxy configuration.
```bash
npm run ng serve vanilla-search -- --ssl=true --proxy-config=./projects/vanilla-search/src/proxy.conf.json
```
--------------------------------
### Build and Serve Vanilla Search App
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/getting-started.md
Build and serve the Vanilla Search application locally. This command also configures the proxy to connect to the Sinequa demo server. Requires a Sinequa account.
```bash
npm run start:vanilla
```
--------------------------------
### sq-facet-heatmap Component Usage
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/heatmap.md
Example of how to use the sq-facet-heatmap component within an sq-facet-card.
```APIDOC
## sq-facet-heatmap Component
### Description
The `sq-facet-heatmap` component displays a heatmap visualization for search results, allowing users to explore data distributions.
### Inputs
- `results` (any): The current search results.
- `aggregation` (string, default: `'Heatmap'`): The name of the aggregation containing the heatmap data.
- `name` (string, optional): An identifier for the facet.
- `fieldX` (string, required for cross-distribution): The field for the X-axis.
- `fieldY` (string, required for cross-distribution): The field for the Y-axis.
- `fieldsX` (array of strings, required for cross-distribution): Available fields for the X-axis.
- `fieldsY` (array of strings, required for cross-distribution): Available fields for the Y-axis.
- `fieldCooc` (string, required for co-occurrence): The co-occurrence field.
- `width` (number, default: `600`): Default width of the chart.
- `height` (number, default: `600`): Default height of the chart.
- `margin` (object, default: `{top: 100, bottom: 20, left: 100, right: 40}`): Margins for the chart.
- `transition` (number, default: `1000`): Transition duration in milliseconds.
- `buckets` (number, default: `9`): Number of quantiles for data splitting.
- `colorScheme` (string, default: `'schemeBlues'`): D3 color scheme for the gradient.
- `maxX` (number, default: `20`): Maximum number of items on the X-axis.
- `maxY` (number, default: `20`): Maximum number of items on the Y-axis.
- `itemsClickable` (boolean, default: `true`): Whether heatmap tiles are clickable.
- `axisClickable` (boolean, default: `true`): Whether axis items are clickable.
- `highlightSelected` (boolean, default: `true`): Whether to highlight selected tiles.
### Usage Example
```html
```
```
--------------------------------
### Build an Application
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/guides/3-development.md
Build an SBA application using the \"npm run buildvanilla\" script, which executes \"ng build\" to create deployable artifacts in the \"dist\" folder.
```bash
npm run buildvanilla
```
--------------------------------
### Configure Help Folder Options
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/startup.md
Provide `APP_HELP_FOLDER_OPTIONS` to specify the help folder, path, index file, and locale usage within the application.
```typescript
@NgModule()({
...
providers: [
{ provide: APP_HELP_FOLDER_OPTIONS, useValue: { folder: 'vanilla-search' } },
```
--------------------------------
### Clone SBA Workspace
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/guides/5-version-control.md
Download the standard SBA framework source code to your local machine. This command initializes a new project directory and fetches the repository.
```bash
git clone https://github.com/sinequa/sba-angular.git my-project
cd my-project
```
--------------------------------
### Migrate Fielded Search to Filter Syntax (Before)
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/releases/release-11-10-0.md
Example of the old fielded search expression syntax using ExprBuilder before migration.
```typescript
expr = this.exprBuilder.concatAndExpr([
this.exprBuilder.makeExpr("docformat", "pdf"),
this.exprBuilder.concatOrExpr([
this.exprBuilder.makeExpr("authors", "John"),
this.exprBuilder.makeNumericalExpr("size", "<", 1024)
])
]);
query.addSelect(expr);
```
--------------------------------
### Build Static Website Content
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/README.md
Generates the static website files into the 'build' directory, ready for hosting.
```bash
yarn build
```
--------------------------------
### Basic Dashboard Usage
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/dashboard.md
Use the sq-dashboard component with a minimal setup to display widgets. Widgets can be dragged and dropped by their header.
```html
```
--------------------------------
### Deploy Website with Git Bash on Windows (npm)
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/README.md
Sets the GIT_USER environment variable and deploys using npm. This is convenient for GitHub Pages hosting.
```bash
export GIT_USER=
npm run deploy
```
--------------------------------
### Get Specific Recent Query
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/user-settings.md
Retrieves a specific recent query by its text identifier. Returns null if the query is not found.
```APIDOC
## GET recentquery(text: string)
### Description
Returns a recent query with the given text or null if it does not exist.
### Method
GET
### Endpoint
/recentquery/{text}
### Parameters
#### Path Parameters
- **text** (string) - Required - The text identifier of the recent query.
```
--------------------------------
### Development StartConfig with Proxy Override
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/login-methods.md
Update the `StartConfig` in development mode to use an alternative SAML provider that points to the proxy URL. This ensures JWT cookies are correctly associated with the proxy, enabling authentication during local development.
```typescript
export const startConfig: StartConfig = {
app: "my-app",
autoSAMLProvider: "identity-dev",
production: environment.production
};
```
--------------------------------
### Get Recent Queries
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/user-settings.md
Retrieves the list of recent queries for the current user. If the list does not exist, it will be initialized as an empty array.
```APIDOC
## GET recentqueries
### Description
Returns the list of this user's recent queries. The list is stored in the user settings.
Using this service creates the list of recent queries if it does not already exist.
### Method
GET
### Endpoint
/recentqueries
### Response
#### Success Response (200)
- **recentqueries** (RecentQuery[]) - The list of recent queries.
```
--------------------------------
### Deploy Website using SSH
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/README.md
Deploys the website using SSH. Ensure the USE_SSH environment variable is set.
```bash
USE_SSH=true yarn deploy
```
--------------------------------
### Get All Advanced Values
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/advanced.md
Retrieves an object containing all currently set advanced search fields and their corresponding values from the query.
```typescript
getAdvancedValues(query?: Query | undefined): Object
```
--------------------------------
### Clone a Remote Repository
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/guides/5-version-control.md
Clone a project from a remote repository, typically used by other developers to get a copy of the shared codebase.
```bash
git clone https://my-internal-git-server/my-project.git
```
--------------------------------
### Import and Configure Selection Module
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/selection.md
Import the BsSelectionModule and configure optional settings like reset behavior and storage. Provide custom options via SELECTION_OPTIONS.
```typescript
import { BsSelectionModule, SelectionOptions, SELECTION_OPTIONS } from '@sinequa/components/selection';
/* These options override the default settings */
export const mySelectionOptions: SelectionOptions = {
resetOnNewQuery: false,
resetOnNewResults: false,
storage: "record"
};
@NgModule({
imports: [
/*....*/
BsSelectionModule,
/*....*/
],
providers: [
/* If you want to the default options of the selection module */
{ provide: SELECTION_OPTIONS, useValue: mySelectionOptions },
/*....*/
],
/*....*/
})
```
--------------------------------
### Migrate Fielded Search to Filter Syntax (After)
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/releases/release-11-10-0.md
Example of the new filter syntax for querying data, replacing the old expression builder.
```typescript
filter = {
operator: "and",
filters: [
{ field: "docformat", value: "pdf" },
{
operator: "or",
filters: [
{ field: "authors", value: "John" },
{ field: "size", operator: "<", value: 1024 }
]
}
]
};
query.addFilter(filter);
```
--------------------------------
### Configure ng serve for Development
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/guides/3-development.md
Customize the \"ng serve\" command for development, enabling HTTPS with \"--ssl=true\" and configuring a proxy for Sinequa server communication using \"--proxy-config\".
```bash
ng serve vanilla-search --ssl=true --proxy-config=./projects/vanilla-search/src/proxy.conf.json
```
--------------------------------
### Build @sinequa/components Library
Source: https://github.com/sinequa/sba-angular/blob/master/README.md
Build the Sinequa components library. This depends on the core library being built first.
```bash
npm run buildcomponents
```
--------------------------------
### Initialize Widget with State and Custom Logic
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/apps/3-pepper.md
Shows how to define a `WidgetOption` including initial state values and an `init` function. The `init` function is called upon widget creation and restoration, ensuring complex objects are correctly generated.
```typescript
option = {
type: "my-custom-type",
icon: "fas fa-chart-bar",
text: "My custom widget",
...defaultOptions,
state: {
param: "Hello world",
},
init: (widget) => widget.otherParam = createComplexObject(widget),
}
```
--------------------------------
### Get App Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/web-services.md
Retrieve the CCApp configuration object from the Sinequa server. The application name is automatically determined from the injected StartConfig.
```typescript
this.appWebService.get().subscribe(
(app) => {
console.log('app:', app);
}
);
```
--------------------------------
### Build SBA Libraries
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/guides/3-development.md
Build the SBA framework libraries using npm scripts. This generates compiled code in the \"/dist\" folder. It is recommended to use \"npm run \" to ensure consistency with the project's Angular version.
```bash
npm run buildcore
npm run buildcomponents
npm run buildanalytics
```
--------------------------------
### Using sq-facet-date in a Facet Card
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/timeline.md
This example shows how to integrate the sq-facet-date component within a facet card to provide date filtering capabilities.
```html
```
--------------------------------
### Apply Theme from Local Storage or OS Preference
Source: https://github.com/sinequa/sba-angular/blob/master/projects/pepper/src/index.html
This script retrieves the theme preference from local storage. If no preference is found, it detects the OS's preferred color scheme. It then applies the 'dark' theme class to the body and updates the logo source if the 'dark' theme is selected. Defaults to light mode.
```javascript
// Get theme from local storage
let theme = localStorage.getItem('sinequa-theme');
// Detect OS theme
if(!theme && window.matchMedia) {
if(window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme = 'dark';
}
}
// Apply theme (defaults to light mode)
if(theme && theme === 'dark'){
document.body.classList.toggle("dark");
document.getElementById("sinequa-logo").setAttribute("src", "assets/sinequa-logo-dark-lg.png")
}
```
--------------------------------
### Implement Custom FormatService
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/app-utils.md
Extend the FormatService to add support for custom formatters. This example adds a formatter for numerical values representing counts.
```typescript
import { Injectable } from '@angular/core/';
import { FormatService, ValueItem } from '@sinequa/core/app-utils';
import { FieldValue } from '@sinequa/core/base';
import { CCColumn } from '@sinequa/core/web-services';
...
@Injectable({
providedIn: 'root'
})
export class MyFormatService extends FormatService {
// Add support for a custom formatter
formatValue: (valueItem: ValueItem | FieldValue, column?: CCColumn): string => {
if (column && column.formatter === 'mycustomformatter') {
let [value, display] = this.getValueAndDisplay(valueItem);
switch (value) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
}
}
return super.formatValue(valueItem, column);
}
};
...
// Provide
@NgModule({
providers: [
{ provide: FormatService, useClass: MyFormatService }
]
})
```
--------------------------------
### Add Simple Equality Filter
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/app-utils.md
Add a filter to the query using the `addFilter` method. This example demonstrates an equality filter on the 'source' field.
```typescript
query.addFilter({
field: "source",
value: "Documentation"
});
```
--------------------------------
### Import Labels Messages
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/labels.md
Import the necessary language-specific messages for the Labels Module to enable internationalization. This example shows how to include English messages.
```typescript
import {enLabels} from "@sinequa/components/labels";
const messages = Utils.merge({}, ..., enLabels, appMessages);
```
--------------------------------
### Initialize Network Providers with Out-of-the-Box Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/network.md
In your component's controller, import `NetworkProvider`, `ProviderFactory`, and `oOTBConfig` to initialize the `providers` variable with a default configuration.
```typescript
import { NetworkProvider, ProviderFactory, oOTBConfig } from '@sinequa/analytics/network';
@Component({
...
})
export class MyComponent {
providers: NetworkProvider[] = [];
constructor(
...,
public providerFactory: ProviderFactory
) {
this.providers = oOTBConfig(providerFactory);
}
```
--------------------------------
### Add Modal Messages for Localization
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/modal.md
Import and merge modal-specific messages for internationalization. This example shows how to add English messages for the modal component.
```typescript
...
import {enModal} from "@sinequa/components/modal";
const messages = Utils.merge({}, ..., enModal, appMessages);
```
--------------------------------
### Custom Input Functions
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/fusioncharts.md
These are examples of custom input functions that can be provided to override default behaviors for filtering, selection, and node initialization in the MultiLevelPieChart.
```typescript
/**
* A function that returns true this component is already filtering the query
*/
@Input()
hasFiltered = () => {
return this.facetService.hasFiltered(this.getName());
}
/**
* A function that returns true the aggregationItem match a selected document
*/
@Input()
isSelected = (item: T) => {
if (this.isTree()) {
return this.selectedValues.has((item as TreeAggregationNode).$path!.toLowerCase()) && this.selectedColor;
}
return this.selectedValues.has(Utils.toSqlValue(item.value).toLowerCase()) && this.selectedColor;
}
/**
* Callback used to apply custom operations (sort, filter ...) on a tree nodes
*/
@Input() initNodes = (nodes: TreeAggregationNode[], level: number, node: TreeAggregationNode) => {}
```
--------------------------------
### SCSS Compilation Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/projects/vanilla-search/src/preview/readme.md
Configuration for compiling the preview.scss file. Note that 'inject: false' means it's not injected into the main SBA index.html.
```json
{
"input": "projects/vanilla-search/src/preview/preview.scss",
"bundleName": "preview",
"inject": false
}
```
--------------------------------
### Load Principal Information
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/web-services.md
Load the Principal object for the authenticated user and set it on the principal property. This is the usual way to get principal data.
```typescript
this.principalWebService.load().subscribe(
(principal) => {
console.log('principal:', principal);
}
);
```
--------------------------------
### Home Component Controller (home.component.ts)
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/completed-app.md
A basic Angular component for the home page. It includes standard OnInit lifecycle hook but no specific logic in this example.
```typescript
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
```
--------------------------------
### Build Analytics Library
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/analytics.md
Run this command at the root of the workspace to build the analytics library. The build output is placed in `dist/analytics/` and aliased as `@sinequa/analytics`.
```bash
npm run buildanalytics
```
--------------------------------
### Configure Results Views
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/startup.md
Use `BsResultsViewModule.forRoot()` to inject the list of views and the default view for displaying search results.
```typescript
@NgModule({
imports: [
BsResultsViewModule.forRoot(allViews, defaultView)
...
```
--------------------------------
### Replacing Default Confirm Component
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/modal.md
Example of how to provide a custom component as the default modal confirmation dialog using the MODAL_CONFIRM injection token in app.module.ts.
```typescript
import { /*...,*/ MODAL_CONFIRM} from "@sinequa/core/modal";
@NgModule({
/*....*/
providers: [
/*....*/
{ provide: MODAL_CONFIRM, useValue: MyConfirmComponent }
/*....*/
],
/*....*/
})
```
--------------------------------
### Create a Basic Preview Component
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/preview.md
Create a simple Angular component that uses sq-modal to display content. This component will serve as the base for our preview popup.
```typescript
import {Component} from "@angular/core";
@Component({
selector: "preview",
template: `
Hello world
`
})
export class Preview {}
```
--------------------------------
### Handling Selection Interactions
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/timeline.md
Use the `selectionChange` event to capture user-selected date ranges. The event payload provides the start and end dates of the selection.
```html
```
--------------------------------
### Apply Theme from Local Storage or OS Preference
Source: https://github.com/sinequa/sba-angular/blob/master/projects/vanilla-search/src/index.html
This script retrieves the theme preference from local storage or detects the OS preference if not found. It then applies the 'dark' theme to the body and updates the logo source if the theme is dark. Defaults to light mode.
```javascript
// Get theme from local storage
let theme = localStorage.getItem('sinequa-theme');
// Detect OS theme if(!theme && window.matchMedia) {
if(window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme = 'dark';
}
}
// Apply theme (defaults to light mode)
if(theme && theme === 'dark'){
document.body.classList.toggle("dark");
document.getElementById("sinequa-logo").setAttribute("src", "assets/sinequa-logo-dark-lg.png")
}
```
--------------------------------
### Define Message Key in en.ts
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tutorial/intl.md
Add message keys and their default English translations to your `en.ts` locale file. This example defines the key for the search button.
```json
{
search: {
button: "Search"
}
}
```
--------------------------------
### Combine Source and Server Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/configuration.md
Implement logic to prioritize server-side configuration fetched via AppService, falling back to source-code defined defaults (like FEATURES) if server data is unavailable.
```typescript
import { AppService } from '@sinequa/core/app-utils';
import { FEATURES } from '../../config';
constructor(
...
private appService: AppService) { }
...
public get features(): string[] {
return this.appService.app?.data?.features as string[] || FEATURES;
}
```
--------------------------------
### RecentQueriesService Constructor and Event Handling
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/user-settings.md
Initializes the service, sets up subscriptions to user settings and search events, and defines event emitters for recent query changes. Handles optional maxQueries injection.
```typescript
@Injectable({
providedIn: 'root',
})
export class RecentQueriesService implements OnDestroy {
private readonly _events = new Subject();
private readonly _changes = new Subject();
constructor(
public userSettingsService: UserSettingsWebService,
public searchService: SearchService,
@Optional() @Inject(MAX_QUERIES) private maxQueries: number,
){
if(!this.maxQueries){
this.maxQueries = 20;
}
// Listen to the user settings
this.userSettingsService.events.subscribe(event => {
// E.g. new login occurs
// ==> Menus need to be rebuilt
this.events.next({type: RecentQueryEventType.Loaded});
});
// Listen to own events, to trigger change events
this._events.subscribe(event => {
if(RECENT_QUERIES_CHANGE_EVENTS.indexOf(event.type) !== -1){
this.changes.next(event);
}
});
// Listen to search service and store queries
this.searchService.queryStream.subscribe({
next: (query: Query) => {
if(query)
this.addRecentQuery({query: query.copy(), date: new Date()});
}
})
}
/**
* Triggers any event among RecentQueryChangeEvent
* (use for fine-grained control of recent queries workflow)
*/
public get events() : Subject {
return this._events;
}
/**
* Triggers when events affect the list of recent queries
* (use to refresh recent queries menus)
* Cf. CHANGE_EVENTS list
*/
public get changes() : Subject {
return this._changes;
}
}
```
--------------------------------
### Server-side Custom Parser Implementation
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/app-utils.md
Example of a server-side custom parser implementation in C# for parsing fielded search expressions. This requires a FunctionPlugin named ParseExpressionValue.
```csharp
public class ParseExpressionValue : FunctionPlugin
{
public override string GetValue(IDocContext ctxt, params string[] values)
{
if (values.Length <= 1) return null;
var parser = values[0];
var value = values[1];
if (parser == "mycustomparser")
{
// return the parsed value here
}
return null;
}
}
```
--------------------------------
### Format Data with FormatService
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/app-utils.md
Use the FormatService to format values from a Sinequa index. This example shows formatting a 'size' and 'documentlanguages' field using default formatters.
```typescript
// The following will display "size: 2.92Kb" when using the en locale
let column = this.appService.getColumn('size');
// Note that this would normally be configured in the Sinequa administration
column.formatter = 'memorysize';
console.log('size:', this.formatService.format(3000, column));
// The following will display "language: French" when using the en locale
column = this.appService.getColumn('documentlanguages');
// Note that this would normally be configured in the Sinequa administration
column.formatter = 'language';
console.log('language:', this.formatService.format('fr', column));
```
--------------------------------
### Initialize WebServicesModule
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/web-services.md
Initialize the WebServicesModule with essential configuration like app name and URL. This makes services available across the application.
```typescript
@NgModule({
imports: [
...
WebServicesModule.forRoot({
app: 'app-name',
url: 'http://localhost', // set for ng serve / CORS
production: environment.production
});
]
...
});
```
--------------------------------
### Emit Custom Notification
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/notification.md
Use the generic `notify` method to emit a notification with custom type and auto-close behavior. This example shows an info notification that does not auto-close.
```typescript
this.notificationsService.notify(NotificationType.Info, 'An info message');
```
--------------------------------
### Development Environment Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/login-methods.md
Configure the SAML provider for the development environment. Ensure 'production' is set to false.
```typescript
export const environment = {
autoSAMLProvider: "identity-dev",
production: false
};
```
--------------------------------
### Dropdown Menu Definition
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/action.md
Define a dropdown menu by creating an `Action` object with a `children` array. This example shows how to construct a menu for managing user alerts.
```typescript
const alertsActions: Action[] = [];
const createAction = new Action({
text: "msg#alerts.createAlert",
title: "msg#alerts.createAlert",
action: () => createAlert();
});
const manageAction = new Action({
text: "msg#alerts.manageAlerts",
title: "msg#alerts.manageAlerts",
action: () => manageAlert();
});
alertsActions.push(createAction);
alertsActions.push(manageAction);
const alertMenu = new Action({
icon: "some-icon-class",
text: "msg#alerts.alerts",
children: alertsActions
});
```
--------------------------------
### Initialize Theme on App Load
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/theme.md
To prevent a flickering effect, activate the theme immediately when the application loads. This is achieved by adding a script to `index.html` that checks `localStorage` and applies the 'dark' class if necessary.
```html
```
--------------------------------
### Internationalization Setup
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/components/facet.md
Include the facet module's messages for the desired language in your application's locale files. This ensures proper display of facet-related text.
```typescript
import {enFacet} from "@sinequa/components/facet";
const messages = Utils.merge({}, ..., enFacet, appMessages);
```
--------------------------------
### Lookup Service for Microfrontend Configuration
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/speed-performance.md
Implement a lookup service to fetch microfrontend configurations at runtime. This enables dynamic route building based on external data, such as user privileges.
```typescript
@Injectable({ providedIn: 'root' })
export class LookupService {
lookup(): Promise {
[...]
}
}
```
--------------------------------
### Get Query Intent using Web Service
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/query-intent.md
Use the `QueryIntentWebService` to retrieve the intent of a given query object. This method returns an observable of `QueryIntentMatch` objects.
```typescript
this.queryIntentWebService.getQueryIntent(this.query);
```
--------------------------------
### Integrate Sample Node and Edge Info Cards
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/analytics/network.md
This HTML snippet shows how to integrate the provided sample components for node and edge info cards (`sq-node-info-card` and `sq-edge-info-card`) into the `sq-network` component using `ng-template`.
```html
```
--------------------------------
### Read User Preference
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/tipstricks/user-preferences.md
Retrieve a user preference value by its key using the `get()` method of the injected `UserPreferences` service. This operation is available after the user has logged in.
```typescript
let value = this.prefs.get("some-parameter");
```
--------------------------------
### Suggest Query Web Service
Source: https://github.com/sinequa/sba-angular/blob/master/docusaurus/docs/libraries/core/web-services.md
Gets query suggestions based on input text for a defined 'Suggest Query'. Optionally limits suggestions to specific fields.
```typescript
// Get suggestions based on the input text for the authors column
this.suggestQueryWebService.get('my-suggest-query', 'input-text', query.name, ['authors']).subscribe(
(suggestions) => {
console.log('suggestions:', suggestions);
}
);
```