### Example Metadata Provider Setup Source: https://reactodia.github.io/docs/examples/graph-authoring Sets up a custom metadata provider for Reactodia, defining editable types, relations, and literal languages. Includes asynchronous functions for creating entities and relations with simulated delays. ```typescript const SIMULATED_DELAY: number = 50; /* ms */ export class ExampleMetadataProvider extends Reactodia.BaseMetadataProvider { private readonly propertyTypes = [ owl.AnnotationProperty, owl.DatatypeProperty, owl.ObjectProperty, ]; private readonly editableTypes = new Set([owl.Class, ...this.propertyTypes]); private readonly editableRelations = new Set([ rdfs.domain, rdfs.range, ]); private readonly literalLanguages: ReadonlyArray = ['de', 'en', 'es', 'ru', 'zh']; constructor() { super({ getLiteralLanguages: () => this.literalLanguages, createEntity: async (type, {signal}) => { await Reactodia.delay(SIMULATED_DELAY, {signal}); const random32BitDigits = Math.floor((1 + Math.random()) * 0x100000000) .toString(16).substring(1); const typeLabel = Reactodia.Rdf.getLocalName(type) ?? 'Entity'; return { data: { id: `${type}_${random32BitDigits}`, types: [type], properties: { [Reactodia.rdfs.label]: [ Reactodia.Rdf.DefaultDataFactory.literal(`New ${typeLabel}`) ] }, }, elementState: type === owl.Class ? Reactodia.TemplateState.empty.set( Reactodia.TemplateProperties.Expanded, true ) : undefined, }; }, createRelation: async (source, target, linkType, {signal}) => { await Reactodia.delay(SIMULATED_DELAY, {signal}); return { data: { sourceId: source.id, targetId: target.id, linkTypeId: linkType, properties: {}, }, }; }, }); } } ``` -------------------------------- ### Render Example Component Source: https://reactodia.github.io/docs/components/form-input Standard React rendering call to mount the example component. ```javascript render(); ``` -------------------------------- ### Install @reactodia/workspace Source: https://reactodia.github.io/docs Use this command to add the library to your project dependencies via NPM. ```bash npm install --save @reactodia/workspace ``` -------------------------------- ### Custom Element Template Example Source: https://reactodia.github.io/docs/api/workspace/interfaces/ElementTemplate Example of an Element template that supports being expanded and resized by the user. Ensure renderElement is a pure function. ```typescript const MyTemplate: Reactodia.ElementTemplate = { renderElement: props => { ... }, supports: { [Reactodia.TemplateProperties.Expanded]: true, [Reactodia.TemplateProperties.ElementSize]: true, } } ``` -------------------------------- ### Initialize Workspace and Create Diagram Source: https://reactodia.github.io/docs/components/workspace Use `useLoadedWorkspace` for initial workspace setup, including diagram creation and element addition. It handles cleanup and aborts async operations on unmount. ```javascript function Example() { const {defaultLayout} = Reactodia.useWorker(Layouts); const {onMount} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, view} = context; const dataProvider = new Reactodia.EmptyDataProvider(); await model.createNewDiagram({dataProvider, signal}); model.createElement('http://example.com/entity'); const canvas = view.findAnyCanvas(); canvas.zoomToFit(); }, []); return (
); } ``` -------------------------------- ### startTask() Source: https://reactodia.github.io/docs/api/workspace/classes/OverlayController Starts a foreground task that blocks canvas interaction and displays a loading indicator. ```APIDOC ## startTask() ### Description Starts a new foreground task which blocks canvas interaction and displays a loading indicator until the task has ended. ### Parameters - **params** (object) - Required - **delay** (number) - Optional - Delay in milliseconds before displaying loading indicator. Default: 0. - **title** (string) - Optional - Task title to display. ### Returns - **OverlayTask** ``` -------------------------------- ### Create Example Toolbar Menu Source: https://reactodia.github.io/docs/examples/classic-workspace Provides a reusable toolbar menu component that supports importing layout files and managing workspace tasks. ```typescript import * as React from 'react'; import { HashMap } from '@reactodia/hashmap'; import * as Reactodia from '@reactodia/workspace'; export function ExampleToolbarMenu() { const {model, editor, overlay} = Reactodia.useWorkspace(); return ( <> { const preloadedElements = new Map(); for (const element of model.elements) { for (const entity of Reactodia.iterateEntitiesOf(element)) { preloadedElements.set(entity.id, entity); } } const preloadedLinks = new HashMap( Reactodia.hashLink, Reactodia.equalLinks ); for (const link of model.links) { for (const relation of Reactodia.iterateRelationsOf(link)) { preloadedLinks.set(relation, relation); } } const task = overlay.startTask({title: 'Importing a layout from file'}); try { const json = await file.text(); const diagramLayout = JSON.parse(json); await model.importLayout({ dataProvider: model.dataProvider, diagram: diagramLayout, preloadedElements, preloadedLinks, validateLinks: true, }); } catch (err) { ``` -------------------------------- ### PropertyConfiguration Path Examples Source: https://reactodia.github.io/docs/api/workspace/interfaces/PropertyConfiguration Illustrates direct and pattern-based configurations for the 'path' property within PropertyConfiguration. Use direct configuration for simple IRI predicates and pattern configuration for more complex SPARQL patterns. ```plaintext Direct configuration: `ex:firstName` ``` ```plaintext Pattern configuration: ` ?inst ex:hasAddress ?addr . ?addr ex:hasApartmentNumber ?value ` ``` -------------------------------- ### Initialize Workspace with Annotations and Links Source: https://reactodia.github.io/docs/components/annotation-support This example demonstrates how to set up a Reactodia workspace with initial entities, annotations, and links. It uses `useWorker` for layout, `useLoadedWorkspace` to manage the workspace context, and `model.createElement`, `model.addElement`, and `model.addLink` to populate the workspace. Ensure `AnnotationSupport` is rendered within the `Canvas` to enable annotation UI. ```javascript function Example() { const {defaultLayout} = Reactodia.useWorker(Layouts); const {onMount} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, view, performLayout} = context; const entity = model.createElement('http://example.com/entity1'); const annotation1 = new Reactodia.AnnotationElement({ elementState: Reactodia.TemplateState.empty .set(Reactodia.TemplateProperties.AnnotationContent, { type: 'plaintext', text: 'Double-click to edit\nnote about "entity1"', }), }); const annotation2 = new Reactodia.AnnotationElement({ elementState: Reactodia.TemplateState.empty .set(Reactodia.TemplateProperties.AnnotationContent, { type: 'plaintext', text: 'Note about entity AND annotation', }) .set(Reactodia.TemplateProperties.ColorVariant, 'primary'), }); model.addElement(annotation1); model.addElement(annotation2); model.addLink(new Reactodia.AnnotationLink({ sourceId: annotation1.id, targetId: entity.id, })); model.addLink(new Reactodia.AnnotationLink({ sourceId: annotation2.id, targetId: entity.id, })); model.addLink(new Reactodia.AnnotationLink({ sourceId: annotation2.id, targetId: annotation1.id, linkState: Reactodia.TemplateState.empty .set( Reactodia.TemplateProperties.CustomLabel, 'note about another note' ), })); await performLayout({signal}); }, []); return (
); } render(); ``` -------------------------------- ### Reactodia Instances Search Component Example Source: https://reactodia.github.io/docs/components/instances-search Demonstrates how to use the InstancesSearch component within a Reactodia workspace. It loads graph data, sets up a data provider, and triggers a search for organizations. ```javascript function Example() { const GRAPH_DATA = 'https://reactodia.github.io/resources/orgOntology.ttl'; const {defaultLayout} = Reactodia.useWorker(Layouts); const {onMount} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, getCommandBus, performLayout} = context; const response = await fetch(GRAPH_DATA, {signal}); const graphData = new N3.Parser().parse(await response.text()); const dataProvider = new Reactodia.RdfDataProvider({acceptBlankNodes: false}); dataProvider.addGraph(graphData); await model.createNewDiagram({dataProvider, signal}); getCommandBus(Reactodia.InstancesSearchTopic) .trigger('setCriteria', { criteria: { refElement: 'http://www.w3.org/ns/org#Organization', refElementLink: 'http://www.w3.org/2000/01/rdf-schema#domain', } }); }, []); return (
); } ``` -------------------------------- ### Implement Classic Workspace with RDF Data Source: https://reactodia.github.io/docs/examples/classic-workspace Demonstrates the setup of a classic workspace using a layout worker and an RDF data provider to load Turtle-formatted data. ```typescript import * as React from 'react'; import * as Reactodia from '@reactodia/workspace'; import { SemanticTypeStyles, makeOntologyLinkTemplates } from '@reactodia/workspace/legacy-styles'; import * as N3 from 'n3'; import { ExampleToolbarMenu } from './ExampleCommon'; const OntologyLinkTemplates = makeOntologyLinkTemplates(Reactodia); const Layouts = Reactodia.defineLayoutWorker(() => new Worker( new URL('@reactodia/workspace/layout.worker', import.meta.url) )); type TurtleDataSource = | { type: 'url'; url: string } | { type: 'data'; data: string }; export function PlaygroundClassicWorkspace() { const {defaultLayout} = Reactodia.useWorker(Layouts); const [dataSource, setDataSource] = React.useState({ type: 'url', url: 'https://reactodia.github.io/resources/orgOntology.ttl', }); const {onMount} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, editor, getCommandBus} = context; editor.setAuthoringMode(true); let turtleData: string; if (dataSource.type === 'url') { const response = await fetch(dataSource.url, {signal}); turtleData = await response.text(); } else { turtleData = dataSource.data; } const dataProvider = new Reactodia.RdfDataProvider(); try { dataProvider.addGraph(new N3.Parser().parse(turtleData)); } catch (err) { throw new Error('Error parsing RDF graph data', {cause: err}); } await model.importLayout({dataProvider, signal}); getCommandBus(Reactodia.UnifiedSearchTopic) .trigger('focus', {sectionKey: 'elementTypes'}); }, [dataSource]); return ( { if (types.includes('http://www.w3.org/2002/07/owl#DatatypeProperty')) { return Reactodia.ClassicTemplate; } return undefined; }, linkTemplateResolver: (linkType, link) => { if (linkType === 'http://www.w3.org/2000/01/rdf-schema#subClassOf') { return Reactodia.StandardLinkTemplate; } return OntologyLinkTemplates(linkType); }, }} toolbar={{ menu: ( <> ) }} /> ); } function ToolbarActionOpenTurtleGraph(props: { onOpen: (dataSource: TurtleDataSource) => void; }) { const {onOpen} = props; return ( { const turtleText = await file.text(); onOpen({type: 'data', data: turtleText}); }}> Load RDF (Turtle) data ); } ``` -------------------------------- ### HaloLink Children Example Source: https://reactodia.github.io/docs/api/workspace/interfaces/HaloLinkProps Provides an example of LinkAction items that can be passed as children to the HaloLink component, representing available actions on a selected link. ```typescript <> ``` -------------------------------- ### Example Toolbar Menu Component Source: https://reactodia.github.io/docs/examples/stress-test Provides a reusable toolbar menu for file operations within the workspace, including preloading logic for entities and links. ```typescript import * as React from 'react'; import { HashMap } from '@reactodia/hashmap'; import * as Reactodia from '@reactodia/workspace'; export function ExampleToolbarMenu() { const {model, editor, overlay} = Reactodia.useWorkspace(); return ( <> { const preloadedElements = new Map(); for (const element of model.elements) { for (const entity of Reactodia.iterateEntitiesOf(element)) { preloadedElements.set(entity.id, entity); } } const preloadedLinks = new HashMap( Reactodia.hashLink, Reactodia.equalLinks ); for (const link of model.links) { for (const relation of Reactodia.iterateRelationsOf(link)) { preloadedLinks.set(relation, relation); } } ``` -------------------------------- ### Example Metadata Provider Source: https://reactodia.github.io/docs/examples/rdf-explorer Extends Reactodia's BaseMetadataProvider to define custom vocabulary, property types, and entity creation logic with simulated delays. Useful for customizing how RDF data is interpreted and manipulated within the workspace. ```typescript import * as Reactodia from '@reactodia/workspace'; const owl = vocabulary('http://www.w3.org/2002/07/owl#', [ 'Class', 'AnnotationProperty', 'DatatypeProperty', 'ObjectProperty', ]); export const rdfs = vocabulary('http://www.w3.org/2000/01/rdf-schema#', [ 'comment', 'domain', 'range', 'seeAlso', 'subClassOf', 'subPropertyOf', ]); export const example = vocabulary('http://www.example.com/', [ 'workflowStatus', ]); const SIMULATED_DELAY: number = 50; /* ms */ export class ExampleMetadataProvider extends Reactodia.BaseMetadataProvider { private readonly propertyTypes = [ owl.AnnotationProperty, owl.DatatypeProperty, owl.ObjectProperty, ]; private readonly editableTypes = new Set([owl.Class, ...this.propertyTypes]); private readonly editableRelations = new Set([ rdfs.domain, rdfs.range, ]); private readonly literalLanguages: ReadonlyArray = ['de', 'en', 'es', 'ru', 'zh']; constructor() { super({ getLiteralLanguages: () => this.literalLanguages, createEntity: async (type, {signal}) => { await Reactodia.delay(SIMULATED_DELAY, {signal}); const random32BitDigits = Math.floor((1 + Math.random()) * 0x100000000) .toString(16).substring(1); const typeLabel = Reactodia.Rdf.getLocalName(type) ?? 'Entity'; return { data: { id: `${type}_${random32BitDigits}`, types: [type], properties: { [Reactodia.rdfs.label]: [ Reactodia.Rdf.DefaultDataFactory.literal(`New ${typeLabel}`) ] }, }, elementState: type === owl.Class ? Reactodia.TemplateState.empty.set( Reactodia.TemplateProperties.Expanded, true ) : undefined, }; }, }); } } ``` -------------------------------- ### Initialize and Use Reactodia Workspace Source: https://reactodia.github.io/docs/examples/basic This snippet demonstrates the basic setup for Reactodia Workspace. It fetches graph data, processes it using N3.js, creates a new diagram with OWL:Class entities, and then lays out the elements on the canvas. Use this for exploring graph data within a React application. ```typescript import * as React from 'react'; import * as Reactodia from '@reactodia/workspace'; import * as N3 from 'n3'; const Layouts = Reactodia.defineLayoutWorker(() => new Worker( new URL('@reactodia/workspace/layout.worker', import.meta.url) )); export function PlaygroundBasic() { const GRAPH_DATA = 'https://reactodia.github.io/resources/orgOntology.ttl'; const {defaultLayout} = Reactodia.useWorker(Layouts); const {onMount} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, performLayout} = context; // Fetch graph data to use as underlying data source const response = await fetch(GRAPH_DATA, {signal}); const graphData = new N3.Parser().parse(await response.text()); const dataProvider = new Reactodia.RdfDataProvider({acceptBlankNodes: false}); dataProvider.addGraph(graphData); // Create empty diagram and put owl:Class entities with links between them await model.createNewDiagram({dataProvider, signal}); const elementTypeId = 'http://www.w3.org/2002/07/owl#Class'; for (const {element} of await dataProvider.lookup({elementTypeId})) { model.createElement(element.id); } await model.requestData(); // Layout elements on canvas await performLayout({signal}); }, []); return ( ); } ``` -------------------------------- ### Create Example Toolbar Menu Source: https://reactodia.github.io/docs/examples/sparql Defines a toolbar menu component with file import functionality for diagram layouts. Uses Reactodia workspace hooks to manage model state and overlay tasks. ```typescript import * as React from 'react'; import { HashMap } from '@reactodia/hashmap'; import * as Reactodia from '@reactodia/workspace'; export function ExampleToolbarMenu() { const {model, editor, overlay} = Reactodia.useWorkspace(); return ( <> { const preloadedElements = new Map(); for (const element of model.elements) { for (const entity of Reactodia.iterateEntitiesOf(element)) { preloadedElements.set(entity.id, entity); } } const preloadedLinks = new HashMap( Reactodia.hashLink, Reactodia.equalLinks ); for (const link of model.links) { for (const relation of Reactodia.iterateRelationsOf(link)) { preloadedLinks.set(relation, relation); } } const task = overlay.startTask({title: 'Importing a layout from file'}); try { const json = await file.text(); const diagramLayout = JSON.parse(json); await model.importLayout({ dataProvider: model.dataProvider, diagram: diagramLayout, preloadedElements, preloadedLinks, validateLinks: true, }); } catch (err) { task.setError(new Error( 'Failed to load specified file with a diagram layout.', {cause: err} )); } finally { task.end(); } }}> Open diagram from file { ``` -------------------------------- ### Example File Metadata Resolution Source: https://reactodia.github.io/docs/api/forms/interfaces/InputFileProps Demonstrates how to resolve file metadata using useEntityData hook. This is useful for displaying information about existing files from a dataset. ```typescript const {data: fileMetadata} = Reactodia.useEntityData( model.dataProvider, props.values.filter(v => v.termType === 'NamedNode').map(v => v.value) ); ``` -------------------------------- ### Implement Zoom Control in Reactodia Workspace Source: https://reactodia.github.io/docs/components/zoom-control This example demonstrates how to integrate the ZoomControl component into a Reactodia Workspace. It shows how to set up a basic workspace with a default layout and enables the pointer mode toggle within the zoom controls. ```javascript function Example() { const {defaultLayout} = Reactodia.useWorker(Layouts); const {onMount} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, view, performLayout} = context; const alice = model.createElement('urn:example:Alice'); const bob = model.createElement('urn:example:Bob'); model.createLinks({ sourceId: alice.iri, targetId: bob.iri, linkTypeId: 'urn:example:knows', properties: {}, }); await performLayout({signal}); }, []); return (
); } ``` -------------------------------- ### Hotkey String Examples Source: https://reactodia.github.io/docs/api/workspace/type-aliases/HotkeyString Illustrates valid keyboard shortcut expressions using modifiers and keys. Note that Shift-specific special keys require exact specification, e.g., 'Shift+%' instead of 'Shift+5'. ```plaintext Ctrl+Alt+K ``` ```plaintext Alt+Meta+Q ``` ```plaintext Ctrl+/ ``` -------------------------------- ### Implement DropOnCanvas with a custom palette Source: https://reactodia.github.io/docs/components/drop-on-canvas This example demonstrates creating a draggable palette of annotations and configuring the DropOnCanvas component to handle the drop events and transform them into AnnotationElements. ```javascript function Palette() { const {model} = Reactodia.useWorkspace(); const variants = ['default', 'primary', 'success', 'info', 'warning', 'danger']; return (
{variants.map(variant => { e.preventDefault(); }} /> )}
); } function Example() { const {defaultLayout} = Reactodia.useWorker(Layouts); const getDroppedItems = React.useCallback( (e: Reactodia.CanvasDropEvent): Reactodia.DropOnCanvasItem[] => { return Reactodia.defaultGetDroppedOnCanvasItems(e).map(item => { if ( item.type === 'element' && item.element instanceof Reactodia.EntityElement ) { const match = /^urn:my:annotation:([a-z]+)$/.exec(item.element.iri); if (match) { const element = new Reactodia.AnnotationElement({ elementState: Reactodia.TemplateState.empty .set(Reactodia.TemplateProperties.ColorVariant, match[1]), }); return {...item, element}; } return item; } }); } ); return (
); } render(); ``` -------------------------------- ### useLoadedWorkspace() Hook Source: https://reactodia.github.io/docs/api/workspace/functions/useLoadedWorkspace This hook performs asynchronous initialization of the workspace, allowing for setup of data providers, fetching initial data, or importing existing diagram layouts. The command history is automatically reset upon completion. ```APIDOC ## Function: useLoadedWorkspace() > **useLoadedWorkspace**(`onLoad`, `deps`): `LoadedWorkspace` Defined in: src/workspace/workspace.tsx:538 React hook to perform asynchronous initialization of the workspace. This function could be used to setup data provider, fetch initial data or import existing diagram layout. The command history is automatically reset when the initialization is done. ### Parameters Parameter| Type ---|--- `onLoad`| (`params`) => `Promise`<`void`> `deps`| `unknown`[] ### Returns `LoadedWorkspace` ### Example ```javascript const {getContext, onMount} = useLoadedWorkspace(); return ( ... ); ``` ``` -------------------------------- ### Manipulating Diagram Model in Reactodia Source: https://reactodia.github.io/docs/concepts/graph-model Demonstrates how to use the diagram model from WorkspaceContext to create, add, remove, and query elements and links on the canvas. Includes examples of creating elements with different identifiers and properties, creating links between elements, and iterating over diagram components. ```javascript function WorkingWithDiagramModel() { const {model} = Reactodia.useWorkspace(); // Different ways to place entities to the canvas const element1 = model.createElement('http://example.com/element1'); const element2 = model.createElement('urn:my:element2'); const element3 = model.createElement({ id: 'my-schema:element3', types: ['urn:my:MyElement'], properties: { [Reactodia.rdfs.label]: [model.factory.literal('Element3')], }, }); // Place relations between specified entities (must exist on the diagram) const [link1] = model.createLinks({ sourceId: element1.iri, targetId: element2.iri, linkTypeId: 'urn:my:linkTypeA', properties: {}, }); // Remove and place element again to the canvas model.removeElement(element3.id); model.addElement(element3); // Remove and place link again to the canvas model.removeLink(link1.id); model.addLink(link1); // Get source and target of a link model.getSource(link1) === model.getElement(link1.sourceId); model.getTarget(link1) === mode.getElement(link1.targetId); for (const link of model.getElementLinks(element1)) { // Enumerate all links connected to an element } for (const element of model.elements) { // Enumerate all elements on the diagram } for (const link of model.links) { // Enumerate all links on the diagram } } ``` -------------------------------- ### Subscribe to Property Types with useKeyedSyncStore Source: https://reactodia.github.io/docs/concepts/data-provider The `useKeyedSyncStore` hook subscribes to a set of targets and fetches data for each. This example shows how to subscribe and fetch property types for an element template, filtering for properties with at least one value. ```typescript function MyElement(props: Reactodia.TemplateProps) { const {model} = Reactodia.useWorkspace(); const t = Reactodia.useTranslation(); const language = Reactodia.useObservedProperty( model.events, 'changeLanguage', () => model.language ); const data = props.element instanceof Reactodia.EntityElement ? props.element.data : undefined; // Select only properties with at least one value const properties = Object.entries(data?.properties ?? {}) .filter(([iri, values]) => values.length > 0); // Subscribe and fetch property types Reactodia.useKeyedSyncStore( Reactodia.subscribePropertyTypes, properties.map(([iri]) => iri), model ); return (
    {properties.map(([iri, values])) => { // Get property type to display const property = model.getPropertyType(iri); return (
  • {t.formatLabel(property?.data?.label, iri, language)}{': '} {values.map(v => v.value).join(', ')}
  • ); }}
); } ``` -------------------------------- ### targetOf Source: https://reactodia.github.io/docs/api/workspace/classes/DiagramModel Gets the target element of a link. ```APIDOC ## targetOf ### Description Gets a target element for the specified link in the graph. ### Parameters #### Path Parameters - **link** (Link) - Required - The link to query. ### Response - **Returns** (undefined | Element) - The target element or undefined if not found. ``` -------------------------------- ### sourceOf Source: https://reactodia.github.io/docs/api/workspace/classes/DiagramModel Gets the source element of a link. ```APIDOC ## sourceOf ### Description Gets a source element for the specified link in the graph. ### Parameters #### Path Parameters - **link** (Link) - Required - The link to query. ### Response - **Returns** (undefined | Element) - The source element or undefined if not found. ``` -------------------------------- ### elements Source: https://reactodia.github.io/docs/api/workspace/classes/DecoratedDataProvider Gets the data for the specified elements. ```APIDOC ## elements ### Description Gets the data for the specified elements. ### Parameters #### Request Body - **elementIds** (readonly ElementIri[]) - Required - List of element IDs to retrieve. - **signal** (AbortSignal) - Optional - Abort signal for the request. ### Response #### Success Response (200) - **result** (Promise>) - A map of element IDs to their models. ``` -------------------------------- ### KeyedObserver Constructor Source: https://reactodia.github.io/docs/api/workspace/classes/KeyedObserver Initializes a new instance of the KeyedObserver class. ```APIDOC ## new KeyedObserver(subscribe) ### Description Initializes a new instance of the KeyedObserver class. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **KeyedObserver** - An instance of KeyedObserver. #### Response Example None ### Type Parameters - **Key** (`string`) - The type of the key used for observation. ``` -------------------------------- ### Implement Reactodia Toolbar Actions Source: https://reactodia.github.io/docs/examples/stress-test Demonstrates how to use Reactodia toolbar components to handle file I/O for diagram layouts and authoring state persistence. ```javascript const task = overlay.startTask({title: 'Importing a layout from file'}); try { const json = await file.text(); const diagramLayout = JSON.parse(json); await model.importLayout({ dataProvider: model.dataProvider, diagram: diagramLayout, preloadedElements, preloadedLinks, validateLinks: true, }); } catch (err) { task.setError(new Error( 'Failed to load specified file with a diagram layout.', {cause: err} )); } finally { task.end(); } }}> Open diagram from file
{ const diagramLayout = model.exportLayout(); const layoutString = JSON.stringify(diagramLayout); const blob = new Blob([layoutString], {type: 'application/json'}); const blobUrl = URL.createObjectURL(blob); const timestamp = new Date().toISOString().replaceAll(/[Z\s:-]/g, ''); try { const downloadLink = document.createElement('a'); downloadLink.href = blobUrl; downloadLink.download = `reactodia-diagram-${timestamp}.json`; downloadLink.click(); } finally { URL.revokeObjectURL(blobUrl); } }}> Save diagram to file {editor.inAuthoringMode ? ( { const state = editor.authoringState; console.log('Authoring state:', state); alert('Please check browser console for result'); }}> Persist changes to data ) : null} ); } ``` -------------------------------- ### targetOf() Source: https://reactodia.github.io/docs/api/workspace/classes/DataDiagramModel Gets the target element for a specified link in the graph. ```APIDOC ## GET /api/diagramModel/targetOf ### Description Gets the target element for the specified `link` in the graph. If the link is not in the graph, `undefined` will be returned. ### Method GET ### Endpoint /api/diagramModel/targetOf ### Parameters #### Query Parameters - **link** (Link) - Required - The link for which to find the target element. ### Response #### Success Response (200) - **undefined | Element** - The target element of the link, or undefined if the link is not found. #### Response Example ```json { "id": "element2", "type": "element" } ``` ``` -------------------------------- ### Open Connections Menu on Load Source: https://reactodia.github.io/docs/components/connections-menu Initializes a workspace with RDF data and triggers the ConnectionsMenu for a specific organization entity upon mounting. ```javascript function Example() { const GRAPH_DATA = 'https://reactodia.github.io/resources/orgOntology.ttl'; const {defaultLayout} = Reactodia.useWorker(Layouts); const {onMount} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, view, getCommandBus, performLayout} = context; const response = await fetch(GRAPH_DATA, {signal}); const graphData = new N3.Parser().parse(await response.text()); const dataProvider = new Reactodia.RdfDataProvider({acceptBlankNodes: false}); dataProvider.addGraph(graphData); await model.importLayout({dataProvider, signal}); const target = model.createElement('http://www.w3.org/ns/org#Organization'); await model.requestElementData([target.iri]); await performLayout({signal}); model.setSelection([target]); getCommandBus(Reactodia.ConnectionsMenuTopic) .trigger('show', {targets: [target]}); }, []); return (
); } ``` -------------------------------- ### sourceOf() Source: https://reactodia.github.io/docs/api/workspace/classes/DataDiagramModel Gets the source element for a specified link in the graph. ```APIDOC ## GET /api/diagramModel/sourceOf ### Description Gets the source element for the specified `link` in the graph. If the link is not in the graph, `undefined` will be returned. ### Method GET ### Endpoint /api/diagramModel/sourceOf ### Parameters #### Query Parameters - **link** (Link) - Required - The link for which to find the source element. ### Response #### Success Response (200) - **undefined | Element** - The source element of the link, or undefined if the link is not found. #### Response Example ```json { "id": "element1", "type": "element" } ``` ``` -------------------------------- ### links() Source: https://reactodia.github.io/docs/api/workspace/classes/SparqlDataProvider Get all links between two specified sets of entities. ```APIDOC ## links() ### Description Get all links between two specified sets of entities (bipartite graph links). ### Parameters #### Request Body - **primary** (readonly ElementIri[]) - Required - The primary set of elements. - **secondary** (readonly ElementIri[]) - Required - The secondary set of elements. - **linkTypeIds** (readonly LinkTypeIri[]) - Optional - Filter by specific link type IDs. - **signal** (AbortSignal) - Optional - Signal to abort the request. ### Response #### Success Response (200) - **Promise** - A list of links found between the specified sets. ``` -------------------------------- ### Implement custom toolbars Source: https://reactodia.github.io/docs/components/toolbar Demonstrates how to configure multiple toolbars with specific actions, dialogs, and language selectors within a Reactodia workspace. ```javascript function Example() { const {defaultLayout} = Reactodia.useWorker(Layouts); const {onMount, getContext} = Reactodia.useLoadedWorkspace(async ({context, signal}) => { const {model, view, performLayout} = context; model.createElement('http://example.com/entity1'); model.createElement('http://example.com/entity2'); model.createLinks({ sourceId: 'http://example.com/entity1', targetId: 'http://example.com/entity2', linkTypeId: 'http://example.com/connectedTo', properties: {}, }); await performLayout({signal}); }, []); return (
}> { const {overlay} = getContext(); overlay.showDialog({content:
🎉
}); }}> Show a dialog
); } ``` -------------------------------- ### GET /propertyTypes Source: https://reactodia.github.io/docs/api/workspace/classes/IndexedDbCachedProvider Retrieves data for specified property types. ```APIDOC ## GET /propertyTypes ### Description Gets the data for the specified property types. ### Method GET ### Endpoint /propertyTypes ### Parameters #### Query Parameters - **propertyIds** (readonly PropertyTypeIri[]) - Required - List of property type IRIs to retrieve. - **signal** (AbortSignal) - Optional - An AbortSignal to cancel the request. ### Response #### Success Response (200) - **data** (Promise>) - A map of property type IRIs to their corresponding models. ``` -------------------------------- ### connectedLinkStats Source: https://reactodia.github.io/docs/api/workspace/classes/DecoratedDataProvider Gets connected link types of an element for exploration. ```APIDOC ## connectedLinkStats ### Description Gets connected link types of an element for exploration. ### Parameters #### Request Body - **elementId** (ElementIri) - Required - The ID of the element. - **inexactCount** (boolean) - Optional - Whether to allow inexact counts. - **signal** (AbortSignal) - Optional - Abort signal for the request. ### Response #### Success Response (200) - **result** (Promise) - A list of connected link types. ``` -------------------------------- ### Initialize and use EventSource Source: https://reactodia.github.io/docs/api/workspace/classes/EventSource Demonstrates defining event types, creating an instance, subscribing to events, and triggering them. ```typescript interface CollectionEvents { addItem: AddItemEvent; removeItem: RemoveItemEvent; } const source = new EventSource(); const events: Events = source; events.on('addItem', e => { ... }); source.trigger('addItem', { item: someItem }); ``` -------------------------------- ### TemplateState.get() Method Source: https://reactodia.github.io/docs/api/workspace/classes/TemplateState Gets a typed template property value from a template state. ```APIDOC ### get() > **get** <`V`>(`property`): `undefined` | `V` Defined in: src/data/schema.ts:71 Gets typed template property value from a template state. #### Type Parameters Type Parameter --- `V` #### Parameters Parameter| Type ---|--- `property`| `TemplateProperty`<`string`, `V`> #### Returns `undefined` | `V` ``` -------------------------------- ### Implement SerializableLinkCell Source: https://reactodia.github.io/docs/api/workspace/interfaces/SerializableLinkCell Example implementation of a custom link class satisfying the SerializableLinkCell interface. ```typescript class MyLink extends Reactodia.Link { ... static readonly fromJSONType = 'MyLink'; static fromJSON(state: SerializedMyLink): MyLink | undefined { ... } toJSON(): SerializedMyLink { ... } } interface SerializedMyLink extends Reactodia.SerializedLink { '@type': 'MyLink'; ... } MyLink satisfies SerializableLinkCell; ``` -------------------------------- ### links Source: https://reactodia.github.io/docs/api/workspace/classes/DecoratedDataProvider Get all links between two specified sets of entities (bipartite graph links). ```APIDOC ## links ### Description Get all links between two specified sets of entities (bipartite graph links). To get all links between all entities in the set, it is possible to pass the same set to both primary and secondary sets of elements. ### Parameters #### Request Body - **primary** (readonly ElementIri[]) - Required - Primary set of elements. - **secondary** (readonly ElementIri[]) - Required - Secondary set of elements. - **linkTypeIds** (readonly LinkTypeIri[]) - Optional - Filter by specific link types. - **signal** (AbortSignal) - Optional - Abort signal for the request. ### Response #### Success Response (200) - **result** (Promise) - A list of links between the specified sets. ``` -------------------------------- ### Perform Layout with Options Source: https://reactodia.github.io/docs/concepts/graph-layout Demonstrates how to use the `performLayout` function from the workspace context to apply a graph layout. It shows options for specifying a custom layout function, selecting elements, and enabling animation and zoom-to-fit. ```javascript const { view, performLayout } = Reactodia.useWorkspace(); const onClick = async () => { await performLayout({ // Pass custom layout function or use the default one layoutFunction: myGraphLayout ?? view.defaultLayout, // Compute layout only for specific subset of elements selectedElements: new Set([...]), // Animate graph content movement when applying the layout animate: true, // Whether to fit the graph into viewport after the layout zoomToFit: true, }); }; ``` -------------------------------- ### Implement Text Component Source: https://reactodia.github.io/docs/concepts/design-system Example usage of typography CSS variables within a React component. ```jsx function Text() { return (

Normal: The quick brown fox jumps over the lazy dog.

Monospace: The quick brown fox jumps over the lazy dog.

Inverse: The quick brown fox jumps over the lazy dog.

); } ``` -------------------------------- ### XML Header Example Source: https://reactodia.github.io/docs/api/workspace/interfaces/ExportSvgOptions The XML encoding header prepended to the SVG string when addXmlHeader is enabled. ```xml ```