### Discovery.js NPM Package Source: https://github.com/discoveryjs/discovery/blob/master/README.md This snippet shows how to install the Discovery.js framework using npm. It's the primary way to integrate Discovery.js into your projects. ```bash npm install @discoveryjs/discovery ``` -------------------------------- ### Discovery.js Usage Example Source: https://github.com/discoveryjs/discovery/blob/master/README.md This snippet demonstrates a basic usage of Discovery.js, likely for setting up a data analysis or reporting environment. It highlights the core functionality of the framework. ```javascript import { Discovery } from '@discoveryjs/discovery'; const discovery = new Discovery({ // configuration options }); discovery.render(document.getElementById('root')); ``` -------------------------------- ### Example Custom Encoding: Line Counter Source: https://github.com/discoveryjs/discovery/blob/master/docs/encodings.md An example of a custom encoding named 'lines/counter' that counts the number of lines in a payload. It's configured to be non-streaming and always applicable. ```javascript new App({ encodings: [ { name: 'lines/counter', test: () => true, // Always applicable streaming: false, decode: (payload) => new TextDecoder().decode(payload).split('\n').length } ] }); ``` -------------------------------- ### Embed Preinit API Reference Source: https://github.com/discoveryjs/discovery/blob/master/docs/embed.md Provides a reference for the Embed Preinit API, detailing available events like `loadingStateChanged` and methods for event handling, action definition, and location management. ```APIDOC Embed Preinit API: - Events: * loadingStateChanged({ stage, progress, error }) - Methods: * on(eventName, fn) * once(eventName, fn) * off(eventName, fn) * defineAction(name, fn) * setPageHash(hash, replace) * setRouterPreventLocationUpdate(allow) ``` -------------------------------- ### Main Application Container Styling Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS styles the main application container, '#discoveryApp', setting its flex properties, position, and z-index to ensure it occupies available space and is layered correctly within the layout. ```css #discoveryApp { flex: 1; position: relative; z-index: 1; } ``` -------------------------------- ### Layout and Preloader Styling Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS targets the main layout and preloader elements. It sets up a flexbox layout for the main container and styles pseudo-elements for displaying connection status messages. It also handles the visibility and opacity transitions for preloader and toolbar elements. ```css #layout { display: flex; flex-direction: column; height: 100vh; margin-left: 3px; } #layout::before { content: 'Discovery.js app is not connected'; position: absolute; font-size: 12px; top: 32px; left: 50%; color: #222; transform: translateX(-50%); padding: 2px 8px; border-radius: 2px; background-color: #fff6; opacity: 0; transition: ease-out .5s; transition-property: opacity; } #discoveryApp { width: 100%; height: calc(100vh - 3.2em); background: #fff; border: none; } #layout:not(.preloader, .ready)::before { top: 6px; opacity: .8; transition: ease-in-out .35s .25s; transition-property: opacity, top; } #preloader-toolbar, #toolbar { display: flex; padding: 4px; gap: 4px; opacity: 1; transition: ease-in .25s .1s; transition-property: opacity, visibility; } #toolbar { position: relative; z-index: 1; } #preloader-toolbar { position: absolute; } #layout:not(.preloader) #preloader-toolbar, #layout:not(.ready) #toolbar { pointer-events: none; visibility: hidden; opacity: 0; transition-delay: .25s; } #layout:not(.preloader) #preloader-toolbar { transition-delay: 0s; } ``` -------------------------------- ### Embed App API Reference Source: https://github.com/discoveryjs/discovery/blob/master/docs/embed.md Details the Embed App API, including events for hash changes, color scheme, and loading state. It also lists reactive observers for page state and methods for navigation, data management, and UI configuration. ```APIDOC Embed App API: - Events: * pageHashChanged(hash, replace) * colorSchemeChanged({ state: ColorSchemeState, value: SerializedColorSchemeValue }) * loadingStateChanged({ stage, progress, error }) * data() * unloadData() - Observers (reactive values): * pageHash: string * pageId: string * pageRef: string * pageParams: Record * colorScheme: { state: ColorSchemeState, value: SerializedColorSchemeValue } - Methods: * on(eventName, fn) * once(eventName, fn) * off(eventName, fn) * defineAction(name, fn) * setPageHash(hash, replace) * setPage(id, ref, params, replace) * setPageRef(ref, replace) * setPageParams(params, replace) * setColorSchemeState(value) * setRouterPreventLocationUpdate(allow) * setLocationSync(enabled) * unloadData() * loadData(dataLoader) * nav {primary, secondary, menu} * insert(config, position, name) * prepend(config) * append(config) * before(name, config) * after(name, config) * replace(name, config) * remove(name) ``` -------------------------------- ### Connecting with Pre-init and App Callbacks Source: https://github.com/discoveryjs/discovery/blob/master/docs/embed.md Connects to an embedded Discovery app, allowing for callbacks during both the pre-initialization phase (e.g., for preloaders) and after the app is fully connected and ready. It also provides cleanup functions for both stages. ```javascript import { connectToEmbedApp } from "@discoveryjs/discovery/dist/discovery-embed.js"; const disconnect = connectToEmbedApp(iframe, (embedPpreinit) => { // do something when app's preloader is connected and ready return () => { // do something on preloader destroy }; }, (embedApp) => { // do something when app is connected and ready return () => { // do something on app destroy (unload) }; } ); ``` -------------------------------- ### Enable Upload Data with Default Settings Source: https://github.com/discoveryjs/discovery/blob/master/docs/upload.md Demonstrates how to enable the upload data feature with default configurations for both the App and Widget instances in DiscoveryJS. ```js import { App, Widget, upload, navButtons } from '@discoveryjs/discovery'; // App const myapp = new App({ upload: true }); // or the same as for Widget via "extensions" option // Widget const myapp = new Widget({ extensions: [ upload, navButtons.uploadFile ] }); ``` -------------------------------- ### Embed Host Connection and Preloader Management Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html Connects to an embedded application using a provided selector and manages the preloader's loading state. It updates the UI based on the loading progress and stage, and handles disconnection events. ```javascript import { connectToEmbedApp, decodeStageProgress } from "./embed-host.js"; connectToEmbedApp($('#discoveryApp'), (preloader) => { $('#layout').classList.add('preloader'); logMsg('App preloader connected'); preloader.on('loadingStateChanged', ({ stage, progress }) => { const { title, progressValue } = decodeStageProgress(stage, progress); $('#preloader-data-loading-state .title').textContent = title; $('#preloader-data-loading-state .progressbar').classList.toggle('visible', true); $('#preloader-data-loading-state .progressbar').style.setProperty('--progress', progressValue); logMsg('Loading data state', { stage, progress }); }); preloader.setRouterPreventLocationUpdate(true); return () => { $('#layout').classList.remove('preloader'); logMsg('App preloader disconnected'); } }, (app) => { app.pageHash.subscribeSync((hash) => $('#location').textContent = hash || ''); app.pageId.subscribeSync((pageId) => $('#location-nav').dataset.pageId = pageId); app.on('pageHashChanged', (pageHash, replace) => { logMsg('Change location to', { replace, pageHash }); }); app.darkmode.subscribeSync(({ value }) => { $('#darkmode-buttons').dataset.value = value; }); app.on('darkmodeChanged', (data) => { logMsg('Change darkmode to', data); }); app.on('data', () => logMsg('Set new data')); app.on('unloadData', () => logMsg('Data unloaded')); app.on('loadingStateChanged', (state) => logMsg('Loading data state', state)); $('#darkmode-buttons').addEventListener('click', onDarkmodeClick); $('#upload-buttons').addEventListener('click', onDataUpload); $('#location-nav').addEventListener('click', onPageNav); $('#unload-data').addEventListener('click', app.unloadData); logMsg('App connected'); $('#layout').classList.add('ready'); app.nav.primary.append({ data: { text: 'alert!' }, onClick: () => logMsg('Command "alert!" from nav') || setTimeout(() => alert('hello world!')) }); app.nav.secondary.before('inspect', { name: 'before', data: '{ text: "test: goto wiki", href: "https://www.wikipedia.org/" }' }); app.nav.menu.insert({ view: 'block', className: 'toggle-menu-item', content: [ 'text:"Test complex: "', { view: 'link', content: 'text:"One"', onClick: () => { logMsg('Command "One" from nav menu'); alert('One!'); } }, 'text:" "', { view: 'link', content: 'text:"Two"', onClick: () => { logMsg('Command "Two" from nav menu'); alert('Two!'); } } ] }, 1); return () => { $('#darkmode-buttons').removeEventListener('click', onDarkmodeClick); $('#upload-buttons').removeEventListener('click', onDataUpload); $('#location-nav').removeEventListener('click', onPageNav); $('#unload-data').removeEventListener('click', app.unloadData); $('#layout').classList.remove('ready'); logMsg('App disconnected'); }; function onDarkmodeClick({ target }) { if (target.parentNode === $('#darkmode-buttons')) { app.setDarkmode(target.dataset.value); } } function onDataUpload({ target }) { switch (target.dataset.value) { case 'raw': uploadData(JSON.stringify({ test: 'raw' })); break; case 'file': { const fileInput = document.createElement('input'); fileInput.setAttribute('type', 'file'); fileInput.addEventListener('change', event => { uploadData(event.target.files[0]); }); fileInput.click(); break; } case 'url': uploadData(fetch('data:text/plain,{"test":"url"}')) break; } function uploadData(from) { app.uploadData(from).catch((err) => { console.error('Data upload failed:', err); logMsg('Data upload failed:', err.message); }); } } function onPageNav({ target }) { const pageId = target.dataset.pageId; if (pageId) { app.setPage(pageId); } } }); function $(selector) { return document.querySelector(selector); } function d2(num) { return String(num).padStart(2, '0'); } function logMsg(msg, ...args) { const time = new Date(); const itemEl = document.createElement('div'); itemEl.className = 'msg'; itemEl.textContent = ``` -------------------------------- ### Enabling Embed Feature in Discovery App Source: https://github.com/discoveryjs/discovery/blob/master/docs/embed.md Demonstrates how to enable the 'embed' feature for a Discovery.js application, either during App initialization or by including the `embed` extension in the ViewModel. ```javascript import { App, ViewModel, embed } from '@discoveryjs/discovery'; // App const myapp = new App({ embed: true }); // or the same as for ViewModel // ViewModel const myapp = new ViewModel({ extensions: [ embed ] }); ``` -------------------------------- ### Using Upload Actions Source: https://github.com/discoveryjs/discovery/blob/master/docs/upload.md Shows how to utilize the `unloadData` and `uploadFile` actions provided by the upload extension in DiscoveryJS, including displaying supported file types. ```js [ { view: 'button', onClick: '=#.actions.unloadData', content: 'text:"Reset data"' }, { view: 'button', onClick: '=#.actions.uploadFile', content: 'text:"Load data"' }, 'h2:"Supported file extensions & mime types"', 'ul:#.actions.uploadFile | fileExtensions + mimeTypes' ] ``` -------------------------------- ### Global CSS Styles and Animations Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS code defines global styles for the HTML document, including background gradients, font settings, and animations. It styles the body, keyframes for animations, and specific elements like '#pulse', '#layout', and '#discoveryApp'. ```css html, body { padding: 0; margin: 0; font-family: Helvetica, sans-serif; background-color: #4158D0; background-image: linear-gradient(50deg, #4158D0 0%, #C850C0 46%, #FFCC70 100%); } @keyframes foo { 0% { top: 0px } 100% { top: calc(100% - 10vh) } } #pulse { position: absolute; top: 0; left: 0; bottom: 0; width: 3px; } #pulse::before { content: ''; position: absolute; display: block; background: black; width: 100%; height: 10vh; animation: infinite alternate linear 2s foo; } ``` -------------------------------- ### Data Loading State and Progress Bar Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS styles the state of data loading, including a progress bar. It defines the positioning and appearance of the loading state text and the progress bar itself, including its visibility and the styling of the progress indicator using CSS variables. ```css #preloader-data-loading-state { position: relative; width: 260px; box-sizing: border-box; padding: 0 2px 7px; font-size: 13px; color: #fffb; } #preloader-data-loading-state .progressbar { display: inline-block; position: absolute; left: 0; bottom: 0; min-width: 300px; height: 3px; background: rgba(0, 0, 0, .1); background: white; opacity: 0; } #preloader-data-loading-state .progressbar.visible { opacity: 1; } #preloader-data-loading-state .progressbar::before { content: ''; position: absolute; background: #6f259599; top: 0; left: 0; bottom: 0; right: calc(100% * (1 - var(--progress))); } ``` -------------------------------- ### Configure Upload Data Extension Source: https://github.com/discoveryjs/discovery/blob/master/docs/upload.md Illustrates how to configure the upload data extension with custom settings for both App and Widget instances, including options like `accept` and `dragdrop`. ```js import { App, Widget, upload, navButtons } from '@discoveryjs/discovery'; // App const myapp = new App({ upload: { /* options */ } }); // or the same as for Widget via "extensions" option // Widget const myapp = new Widget({ extensions: [ upload.setup({ /* options */ }) ] }); ``` -------------------------------- ### Connecting to an Embedded Discovery App Source: https://github.com/discoveryjs/discovery/blob/master/docs/embed.md Establishes a connection with a Discovery.js app embedded within an iframe using the `connectToEmbedApp` function. It handles the connection and provides a callback for app readiness and cleanup. ```html ``` ```javascript import { connectToEmbedApp } from "@discoveryjs/discovery/dist/discovery-embed.js"; const disconnect = connectToEmbedApp(document.getElementById('discovery-iframe'), (app) => { // do something when app is connected and ready return () => { // do something on app destroy (unload) }; }); // stop any communication disconnect() ``` -------------------------------- ### Log Message Formatting and Display Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This JavaScript snippet demonstrates how to format and display log messages. It appends a new log item to an element with the ID 'logs', including a timestamp and potentially other arguments. It also ensures the logs are scrolled to the bottom. ```javascript t = [msg, ...args.map(value => JSON.stringify(value))].join(' '); itemEl.dataset.time = `${time.toLocaleTimeString()}.${String(time % 1000).padStart(3, 0)}`; $('#logs').append(itemEl); $('#logs').scrollTop = 1e6; ``` -------------------------------- ### Discovery.js Data Loading Functions Source: https://github.com/discoveryjs/discovery/blob/master/docs/load-data.md Provides methods to load data into Discovery.js applications from different sources like streams, events, files, URLs, and pushes. Each function accepts an options object for customization. ```APIDOC loadDataFromStream(stream, options) loadDataFromEvent(event, options) loadDataFromFile(file, options) loadDataFromUrl(url, options) loadDataFromPush(options) Common Options: - size (Number): Optional total size of the data in bytes for accurate progress reporting. - resource (Object): Optional meta information about the loading resource (name, creation timestamp, etc.). loadDataFromUrl Specific Options: - isResponseOk (Function): Optional function to validate response success. Defaults to (response) => response.ok. - getContentSize (Function): Optional function to get content size from response headers (e.g., 'x-file-size', 'content-length'). - getContentCreatedAt (Function): Optional function to get content creation timestamp from response headers (e.g., 'x-file-created-at', 'last-modified'). - fetch (Object): Optional object for additional fetch function options (method, headers, mode, etc.). Resource Structure: - type (string): Type of the resource. - name (string): Name of the resource. - encoding (string): Encoding of the resource ('json', 'jsonxl/snapshot9'). - size (number): Size of the resource in bytes or UTF8 characters. - encodedSize (number): Encoded size of the resource before decoding. - createdAt (Date | string | number): Timestamp of resource creation. ``` -------------------------------- ### Location Navigation Styling Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS styles a navigation component for different pages or locations within the application. It uses flexbox and applies styles to buttons and a display area for the current location, including conditional display logic based on a data attribute. ```css #location-nav { flex: 1; display: flex; gap: 1px; border-radius: 2px; overflow: hidden; } #location-nav[data-page-id="default"] > [data-page-id="default"], #location-nav[data-page-id="report"] > [data-page-id="report"] { display: none; } #location-nav button { border: none; box-sizing: border-box; background-color: #fffa; cursor: pointer; padding: 0 8px; font-size: 12px; } #location-nav button:hover { background-color: #fffd; } #location { flex: 1; overflow: hidden; padding: 4px; font-size: 12px; background-color: #fffc; background-clip: padding-box; } #location::before { content: 'pageHash:'; color: #666; padding-right: .5ex; } ``` -------------------------------- ### Logs Display Area Styling Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS styles the logs display area, controlling its maximum height, font size, overflow behavior, padding, and background. It also styles individual log messages ('msg') for padding, background, margin, and a left border. ```css #logs { max-height: 25%; font-size: 12px; overflow: auto; padding: 1px; background-color: #fff6; } #logs .msg { padding: 4px 8px; background-color: #fff6; margin-bottom: 1px; border-left: 3px solid #8e2f467d; } #logs .msg::before { content: attr(data-time); margin-right: 1ex; opacity: .5; font-size: 11px; } ``` -------------------------------- ### Upload and Unload Data Button Styling Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS styles buttons for uploading and unloading data. It uses flexbox for the upload buttons and applies consistent styling for background, font size, padding, and hover effects. A separate style is provided for the 'unload-data' button. ```css #upload-buttons { display: flex; gap: 1px; border-radius: 3px; overflow: hidden; } /* #upload-buttons::before { content: 'Upload data:'; color: #333; padding-right: .5ex; font-size: 12px; } */ #upload-buttons button, #unload-data { border: none; background-color: #fffa; font-size: 12px; padding: 0 8px; cursor: pointer; } #unload-data { border-radius: 3px; } #upload-buttons button:hover, #unload-data:hover { background-color: #fffd; } ``` -------------------------------- ### Syncing Host Location with Embed App Source: https://github.com/discoveryjs/discovery/blob/master/docs/embed.md Configures the communication to synchronize the host's location state with the embedded Discovery app. It prevents the app from updating the host's location automatically and sets the initial hash and location sync. ```javascript import { connectToEmbedApp } from "@discoveryjs/discovery/dist/discovery-embed.js"; const disconnect = connectToEmbedApp(iframe, (embedApp) => { // ... any other setup // recomended order of API calls to sync location state with embed app embedApp.setRouterPreventLocationUpdate(true); embedApp.setPageHash(location.hash); embedApp.setLocationSync(true); }); ``` -------------------------------- ### Dark Mode Button Styling Source: https://github.com/discoveryjs/discovery/blob/master/models/embed.html This CSS styles a set of buttons for controlling dark mode. It uses flexbox for layout and applies styles for hover effects and active states based on a data attribute indicating the current mode. ```css #darkmode-buttons { display: flex; gap: 1px; border-radius: 3px; overflow: hidden; } #darkmode-buttons button { border: none; box-sizing: border-box; opacity: .65; cursor: pointer; padding: 0 8px; font-size: 12px; } #darkmode-buttons button:hover { opacity: .85; } #darkmode-buttons[data-value="light"] > [data-value="light"], #darkmode-buttons[data-value="dark"] > [data-value="dark"], #darkmode-buttons[data-value="auto"] > [data-value="auto"] { background: white; opacity: 1; cursor: default; } ``` -------------------------------- ### Custom Encoding Type Definition Source: https://github.com/discoveryjs/discovery/blob/master/docs/encodings.md Defines the TypeScript structure for a custom encoding, including its name, test function, streaming capability, and decoding logic. ```typescript type Encoding = { name: string; test(chunk: Uint8Array): boolean; } & ({ streaming: true; decode(iterator: AsyncIterableIterator): Promise; } | { streaming: false; decode(payload: Uint8Array): any; }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.