LDForgeDEVELOPER PREVIEW

FROM DEMO TO YOUR APPLICATION

Your project.
Your SPARQL editor.

Start with a container and a query executor. Add the actions and result views your application needs.

01 / INTEGRATE

Choose how to load LDForge

Use CDN imports for a single static HTML page, or npm with a bundler for an existing application. Both approaches use the same editor and plugin APIs.

CDN: start with a single HTML file

Try the live Wikidata cat grid, then download its HTML or copy the source into your own static site. No npm, framework, API key or Node server is required. Serve the file over HTTP(S).

Three version-pinned esm.sh imports provide the HTTP executor, editor and cards renderer. Load the editor stylesheet separately:

import { createHttpExecutor } from 'https://esm.sh/@ldforge/core@0.1.2?standalone';
import { createEditor } from 'https://esm.sh/@ldforge/editor@0.1.2?standalone';
import { createCardsRenderer } from 'https://esm.sh/@ldforge/renderers@0.1.2?standalone';
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ldforge/editor@0.1.2/dist/styles.css" />

Use ?standalone to bundle the editor’s dependencies into one module: no import map is needed. Keep all LDForge URLs on the same version. CSS is loaded separately from jsDelivr. The example connects to https://query.wikidata.org/sparql using GET and calls editor.run() once on load. Remove that call to wait for a click on Run query. Internet access is required.

The query selects twelve domestic cats with images. Its # view=cards header selects the card grid; card_title, card_text, card_image, card_button and card_button_url map the result columns to each card. Links to Wikidata let visitors find the original images and licenses. The public endpoint may be busy; Run query retries the request.

npm: install in your application

LDForge packages provide ESM JavaScript and TypeScript declarations. Install them in your own application:

npm install @ldforge/core @ldforge/editor @ldforge/renderers @ldforge/prefixes

Use a browser bundler with CSS imports, such as Vite. No framework is required. The editor depends on core and the prefix catalog; the renderer package supplies independent result views. See the configuration reference for every option and default.

02 / EMBED

Mount a working editor

Add a container to your page or host component:

<div id="query-editor"></div>

Then mount the editor from your TypeScript entry point. Replace the example URL with your own SPARQL endpoint:

import { createHttpExecutor } from '@ldforge/core';
import { createEditor } from '@ldforge/editor';
import {
  createTableRenderer,
  createBooleanRenderer,
  createJsonRenderer,
} from '@ldforge/renderers';
import '@ldforge/editor/styles.css';

const container = document.querySelector<HTMLElement>('#query-editor');
if (!container) throw new Error('Missing editor container');

const editor = createEditor(container, {
  query: 'SELECT * WHERE { ?s ?p ?o } LIMIT 10',
  executor: createHttpExecutor({
    endpoint: 'https://your-endpoint.example/sparql',
  }),
  renderers: [
    createTableRenderer(),
    createBooleanRenderer(),
    createJsonRenderer(),
  ],
});

The default toolbar includes Run query and Cancel. Run with the button or Ctrl/Cmd+Enter. SELECT produces bindings; ASK produces a boolean. CONSTRUCT, DESCRIBE and SPARQL Update are not supported by this initial HTTP adapter.

Connecting from a browser

Your endpoint must support the chosen method: direct POST with application/sparql-query, or GET with a query parameter. It must return SPARQL Results JSON and allow your application's origin and extra headers through CORS. If it cannot, route requests through your own backend. Private server credentials belong on that backend.

Configure requests inside the IDE

Open the gear button to see saved endpoints and the local fixture. Select a connection to use it, or choose Add endpoint to open a separate form for its URL, GET/POST method and headers. Save endpoint adds the profile; select it in the list when you want to use it. Edit endpoint opens an existing profile, and Cancel discards your draft. Saving changes to the active profile updates that connection. Editing another profile keeps the current selection. Changing a draft URL clears its headers. URLs and methods are remembered; header values stay in memory for this page only and are kept separate per endpoint. The endpoint URL below the editor is shown in a code font, with a clipboard button that briefly shows a checkmark after copying.

For your own integration, configure the executor directly:

const executor = createHttpExecutor({
  endpoint: 'https://your-endpoint.example/sparql',
  method: 'GET', // Defaults to 'POST'.
  headers: { 'X-Project': 'catalogue' },
});

Use the editor's settings option to register host-owned settings panels. A settings plugin has an id, a label, and a render(container, context) function. Return cleanup when needed. An optional updateLocale(container, context) updates labels without replacing inputs. The demo's src/endpoint-settings.ts is a complete example. The library manages Accept and Content-Type; authentication policy stays with the host.

The status below the query reports completion, for example 3 results in 124 ms. Durations scale to seconds, minutes or hours. This measures execution and result parsing, before rendering.

Configure the IDE and control individual tabs

The demo uses a fixed 15-line query viewport and scrolls longer queries internally. Open Settings and check Show the full query to grow with the query; the demo remembers this preference. In your integration, set editorRows: 15, autoGrow: false. The library defaults to 15 rows with auto-grow enabled; rows are the minimum height when growing. Wrapped lines count as visual rows, and the viewport scales with the query text size.

// In createEditor options:
// editorRows: 15, autoGrow: false,
// onAutoGrowChange: (enabled) => savePreference(enabled),
// controls: { autoGrow: true } // Show the checkbox in Settings.

editor.setEditorRows(20);
editor.setAutoGrow(true);
console.log(editor.getEditorRows(), editor.isAutoGrowEnabled());

Rows must be positive safe integers. The height API resizes the same query editor without changing query text, history or results, and applies across query tabs. JSON and other result views keep their own sizing. Hide the checkbox with controls.autoGrow: false; the API remains available. Use onAutoGrowChange and onEditorRowsChange for host-owned persistence. See the configuration reference.

The right-side icon group contains Prefixes, Format query and Settings. Hide individual built-in controls through the controls object. Project buttons appear in a separate group; hiding a tool does not disable its API.

// In createEditor options:
// controls: { prefixes: true, format: true, settings: true, closeTab: false }

const tabs = editor.getTabs();
const first = tabs[0];
first?.addPrefix('sdo', 'https://schema.org/');
first?.addPrefix('dct');
const other = tabs.addTab({
  name: 'People', query: 'select * where {?s ?p ?o}',
  prefixes: ['sdo', 'dct'], activate: false,
});
await other.formatQuery();
tabs.getByName('People')?.activate();

Queries are formatted locally, with the formatter loaded on first use. Invalid text stays intact. Inactive tabs can be edited without opening another editor. Read the Editor, TabCollection and QueryTabHandle references for return values, callbacks and error behavior.

The demo restores your last applied endpoint and method on refresh. It does not automatically execute a query or store authentication header values.

Shorten share links

URL shortening is optional and supplied by your embedding application. LDForge does not select or operate a provider. Configure the share dialog with a callback; keep credentials and provider-specific response parsing in your application.

import { createEditor } from '@ldforge/editor';
import { createHttpExecutor } from '@ldforge/core';

const host = document.querySelector('#editor');
if (!host) throw new Error('Missing editor container');
const editor = createEditor(host, {
  executor: createHttpExecutor({ endpoint: 'https://example.org/sparql' }),
  query: 'SELECT * WHERE { ?s ?p ?o } LIMIT 10',
  shareBaseUrl: 'https://example.org/editor',
  shortenShareUrl: async (fullUrl, query) => {
    // fullUrl already contains the encoded query and all existing share state.
    // query is the same query before URL encoding, including share metadata.
    const response = await fetch('https://example.org/links', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ url: fullUrl }),
      signal: AbortSignal.timeout(10_000),
    });
    if (!response.ok) throw new Error('Shortening service unavailable');
    const result = await response.json();
    return result.url;
  },
});

// The toolbar opens a dialog and automatically loads short URLs.
// For a custom host action that copies directly:
// await editor.copyShareLink();
// editor.getShareLink() always returns the original full URL.

The callback accepts the complete generated URL and its unencoded query and may return a string or Promise of a string. Return an absolute HTTP(S) URL without whitespace. Without the callback, sharing works as before. The returned short URL is copied and returned by copyShareLink(). Short-link fields fill automatically when the dialog opens; each has independent loading, error and retry feedback. The full URL remains available. Service failures, invalid values and clipboard failures show a recoverable action error and do not change the query; there is no automatic fallback. Retry by clicking again. The API rejects those errors so custom actions can catch them.

If the query, active tab or generated share context changes, the pending result is discarded before copying. Destroying the editor or starting a newer API copy request also invalidates it. Hosts own request timeouts, as shown above.

Share your query panel

The share icon opens an inline panel below the toolbar with separate Copy buttons for the full editor URL, automatically generated short URLs, a SPARQL GET URL, cURL POST/GET commands and an unescaped one-line query. Opening and copying never changes or executes the query. Endpoint examples use the active query endpoint or shareEndpoint; without an endpoint they remain visible with disabled Copy buttons and a placeholder directing users to settings. SELECT/ASK request SPARQL Results JSON; graph queries request N-Triples/Turtle. Connection authentication is excluded from request examples.

The one-line query removes comments and converts multiline literals to quoted strings with escaped newlines while preserving their values. An incomplete literal is shown separately as the original query. Long values remain fully copyable. Escape or the toolbar icon restores focus to the toolbar icon. If the query or connection changes, use Refresh values to rebuild the snapshot before copying.

Explicit automatic execution

Ordinary links never opt into execution. If your host implements execute=true, set shareAutoRun: true. With a shortener configured, the dialog then adds a separately labelled short link that opens and runs the query. Your callback receives that URL with execute=true and must preserve it in the stored destination. The demo supports this parameter; it does not configure a public shortener.

// Recipient host: initialize and restore shared state first.
const params = new URL(location.href).searchParams;
const sharedQuery = params.get('query');
if (sharedQuery !== null) editor.setQuery(sharedQuery);
if (sharedQuery !== null && params.get('execute') === 'true') {
  await editor.run();
}
// In createEditor options, opt in only when the recipient implements this:
// shareAutoRun: true

A simple ORM service

The repository includes a runnable Prisma ORM 6 and SQLite example. Run npm install, set DATABASE_URL=file:./shares.db, run npx prisma db push, then npm start in that directory. POST /links stores the full URL and returns a short URL; GET /s/:id looks up its database row and redirects to the stored URL. The example restricts the recipient origin and path, and documents configuration and deployment responsibilities.

SPARQL-aware editing and prefixes

Press Ctrl+Space for suggestions. The editor uses a Lezer syntax tree to recognize SERVICE, FILTER and triple positions. Predicates are suggested only in predicate positions, including property paths and semicolon shorthand. Variable suggestions use previous syntactic names in the visible query scope. Comments, strings and IRI contents are excluded.

Selecting a predicate such as rdfs:label inserts its missing PREFIX automatically in the same undoable edit. Use the Prefixes button in the toolbar to search common namespaces by prefix or namespace URI and add them directly. Existing aliases are reused; conflicting names get a free suffix.

import { prefixes, prefixEntries, searchPrefixes } from '@ldforge/prefixes';

searchPrefixes('prov');
// In createEditor options:
// sparql: {
//   prefixes: { ...prefixes, ex: 'https://example.org/' },
//   autoPrefixes: false, // Optional: disable automatic declarations while typing.
//   predicates: [
//     { iri: 'https://example.org/name', description: 'Resource name' },
//   ],
// }

The standalone prefix package offers a compact catalog of 32 mappings and an extended catalog of 3,623 mappings, without labels. Neither variant has dependencies or network calls. Import from @ldforge/prefixes/compact or @ldforge/prefixes/extended and pass its prefixes map to the editor. Compact does not load extended data. Omit predicates for the small built-in RDF vocabulary, or provide your own. Syntax errors are marked at parser recovery ranges; known undeclared prefixes offer a quick fix. This checks local syntax and prefix declarations, not whether an endpoint supports or can successfully execute a query.

Group related toolbar plugins with a group identifier, such as group: 'examples'. The IDE combines these into compact button groups. Tab actions appear on hover or keyboard focus; double-clicking a tab name still starts renaming.

03 / ADD ACTIONS

Bring your own buttons

A button plugin receives a typed editor context. Supplying buttons replaces the toolbar, so include the built-in factories to keep Run and Cancel. Add this to your editor options:

import { createRunButton, createCancelButton } from '@ldforge/editor';
import type { ButtonPlugin } from '@ldforge/core';

const loadExample: ButtonPlugin = {
  id: 'my-project.load-example',
  label: 'Load example',
  isDisabled: (context) => context.getState().status === 'running',
  execute(context) {
    context.setQuery('ASK { ?subject ?predicate ?object }');
  },
};

// In createEditor(container, { ... }):
// buttons: [createRunButton(), createCancelButton(), loadExample]

Use getQuery(), setQuery(), getState(), run() and cancel() in your action. Actions may return promises; rejected actions are shown in the status message. Give each button a unique, non-empty identifier.

04 / RENDER RESULTS

Choose how results are presented

Renderers are separate from the editor. Each plugin declares which results it supports. Register your own view alongside the built-in views:

import type { ResultRendererPlugin } from '@ldforge/core';

const countRenderer: ResultRendererPlugin = {
  id: 'my-project.count',
  label: 'Row count',
  wizard: { description: 'Accepts SELECT results.', bindings: [] },
  supports: (result) => result.kind === 'bindings',
  render(container, result) {
    if (result.kind !== 'bindings') return;
    const paragraph = container.ownerDocument.createElement('p');
    paragraph.textContent = `${result.bindings.length} rows`;
    container.replaceChildren(paragraph);
    return () => paragraph.remove();
  },
};

// In createEditor(container, { ... }):
// renderers: [countRenderer, createTableRenderer(), createJsonRenderer()]

Bindings contain ordered variable names and rows of RDF terms; unbound variables are absent from a row. Boolean results contain a value. Use textContent for RDF values. Return a cleanup function when allocating listeners, charts or framework components; it runs before the next render and on destruction.

Registered Table and JSON views stay on the bar by default. Other plugins appear in Choose view, disabled when their result requirements are not met. The active view remains on the bar. Information buttons in the dropdown show each plugin's binding contract. This uses optional wizard.description and wizard.bindings metadata from the plugin, including third-party plugins; supports(result) decides whether a view is enabled. A query header requesting an unavailable view shows a warning, including missing required bindings when declared.

// In createEditor options:
// availablePlugins: true, // Show the dropdown (default).
// visiblePlugins: ['table', 'json', 'geo'], // Explicit registered IDs or objects.

editor.hideAvailablePlugins();
editor.showAvailablePlugins();
editor.showPlugin('geo');
editor.hidePlugin('geo');

Visibility changes preserve the current result and do not execute a query or load visualization libraries. JSON uses a read-only CodeMirror editor with highlighting and a copy button that briefly confirms success. It shows LDForge's normalized result model. CSV download exports the full result independently of the selected view. The Table view's RDF details toggle shows URI notation, quoted literals, and smaller superscript language tags and datatypes in the active theme's muted color. Exact endpoint lexical values, filtering, sorting and scroll position are preserved. Set createTableRenderer({ showRdfDetails: true }) to start with details visible. The share icon copies a query link, including the active renderer and applied endpoint without authentication headers. Registration order determines the initial supported view. For large results, limit your query or supply a paginated or virtualized renderer.

RENDER WITHOUT AN EDITOR

Show a chart without the query editor

Keep the query in your application code and render its result directly into a page container. Result plugins work independently of the editor: no editor, toolbar, tabs or editor stylesheet is required. Install the executor and chart packages:

npm install @ldforge/core @ldforge/charts

Add a container to your page:

<div id="chart"></div>

Run this from your TypeScript entry point with a browser bundler. Replace the endpoint URL with your own CORS-enabled SPARQL endpoint:

import { createHttpExecutor } from '@ldforge/core';
import { createChartRenderer } from '@ldforge/charts';

const container = document.querySelector<HTMLElement>('#chart')!;
const request = new AbortController();
const renderer = createChartRenderer();
let cleanup: void | (() => void);

const query = `
  SELECT ?chart_label ?chart_value WHERE {
    VALUES (?chart_label ?chart_value) {
      ("A" 10)
      ("B" 20)
    }
  }
`;
const executor = createHttpExecutor({
  endpoint: 'https://your-endpoint.example/sparql',
});

async function showChart(): Promise<void> {
  container.textContent = 'Loading chart…';
  try {
    const result = await executor.execute({ query, signal: request.signal });
    if (request.signal.aborted) return;
    if (!renderer.supports(result)) {
      throw new Error('The result does not contain chart bindings.');
    }
    cleanup = renderer.render(container, result, {
      locale: 'en',
      directives: {
        chart: 'bar',
        'chart-title': 'My chart',
      },
    });
  } catch (error) {
    if (!request.signal.aborted) {
      container.textContent = error instanceof Error ? error.message : 'Query failed.';
    }
  }
}

void showChart();

// Call when your host component unmounts, before removing the container.
function destroy(): void {
  request.abort();
  cleanup?.();
}

The chart expects chart_label and numeric chart_value bindings, with optional chart_series. Choose bar, line, pie or doughnut. The chart library loads lazily from the default CDN; see the chart plugin documentation for self-hosted loading and binding requirements. Call destroy() when leaving the page or unmounting your component to cancel a pending query and release the chart.

The same approach works with other result plugins through supports() and render(). Queries executed in the browser are visible in developer tools. Execute the query on your backend if it must remain private, then pass its normalized result to the renderer.

05 / CONNECT YOUR HOST

Own the transport and lifecycle

For a custom backend, implement QueryExecutor and pass it as executor. This example assumes your backend accepts JSON and responds with SPARQL Results JSON:

import { parseSparqlResults } from '@ldforge/core';
import type { QueryExecutor } from '@ldforge/core';

const executor: QueryExecutor = {
  async execute({ query, signal }) {
    const response = await fetch('/api/sparql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query }),
      signal,
    });
    if (!response.ok) throw new Error(`Query failed: ${response.status}`);
    return parseSparqlResults(await response.json());
  },
};

Forward the abort signal. LDForge cancels superseded queries and ignores stale replies. The host manages authentication and endpoint policy.

// Synchronize edits with your host through a createEditor option:
// onQueryChange: (query) => { /* update your host state */ }

editor.getQuery();
editor.setQuery('ASK { ?s ?p ?o }');
await editor.run();
editor.cancel();

// On component unmount, before removing the container:
editor.destroy();

In React, Vue or another framework, mount the editor after the container exists and call destroy() in the component's cleanup hook. Each mount is independent. Plugin registration is static per mount; recreate the editor when changing the plugin set.

Customize the appearance with scoped CSS variables:

.ldforge {
  --ldforge-accent: #075e55;
  --ldforge-border: #d6dedd;
}

06 / TABS AND LANGUAGE

Several queries, one editor

Use + to add a query tab. Double-click its name or use the pencil button to rename it. Enter or leaving the field saves the name; Escape cancels. The demo saves query text, titles and the active tab to localStorage while editing and switching tabs.

LDForge keeps one CodeMirror view and one active editor state. Inactive tabs contain plain text only. Switching cancels pending execution, clears the previous result and resets undo history, so undo cannot cross query boundaries. Your host owns persistence through these options:

import { parseQueryWorkspace } from '@ldforge/editor';
import type { QueryWorkspace } from '@ldforge/editor';

function restoreWorkspace(): QueryWorkspace | undefined {
  try {
    return parseQueryWorkspace(JSON.parse(
      localStorage.getItem('my-project.queries') ?? 'null',
    ));
  } catch {
    return undefined;
  }
}

function saveWorkspace(workspace: QueryWorkspace) {
  try {
    localStorage.setItem('my-project.queries', JSON.stringify(workspace));
  } catch {
    // Editing can continue when storage is unavailable.
  }
}

// Pass the restored value as workspace when present, and use:
// onWorkspaceChange: saveWorkspace
// Read the current snapshot with editor.getWorkspace().

English and Dutch, chosen by your users

The IDE follows the browser's first supported language and falls back to English. A project setting overrides browser detection, and a user choice under the gear button overrides the project. Choosing the default restores the project/browser preference. The demo remembers the user's choice. This integration guide and the demo's surrounding introduction remain in English.

// In createEditor(container, { ... }):
// locale: 'auto',       // Or 'en' / 'nl' as the project default.
// userLocale: 'nl',     // Optional restored user override.
// onLocaleChange: (preference) => { /* persist in your host */ }

editor.setLocale('nl');
editor.setLocale('auto'); // Restore the project/browser default.

Plugin labels accept a string or an object such as { en: 'My action', nl: 'Mijn actie' }. Renderer plugins receive the active locale as their optional third argument. Language changes preserve query text and settings drafts. RDF values and SPARQL code are not translated.

07 / MIGRATE

Migrate from Yasgui

Load @ldforge/yasgui in place of Yasgui. Keep your container, constructor and common query calls. Your users get the native LDForge interface.

Self-hosted files

For a simple HTML embed, copy dist/yasgui.min.js and dist/yasgui.css from the built compatibility package into vendor/ldforge/. Only the two asset paths change:

 <!doctype html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
-  <link rel="stylesheet" href="./vendor/yasgui.min.css">
+  <link rel="stylesheet" href="./vendor/ldforge/yasgui.css">
 </head>
 <body>
   <div id="editor"></div>
-  <script src="./vendor/yasgui.min.js"></script>
+  <script src="./vendor/ldforge/yasgui.min.js"></script>
   <script>
     const editor = new Yasgui(document.getElementById('editor'), {
       requestConfig: { endpoint: 'https://dbpedia.org/sparql' },
       yasqe: { value: 'SELECT * WHERE { ?s ?p ?o } LIMIT 10' },
     });
   </script>
 </body>
 </html>

− Remove + Add · Copy HTML copies the new version.

CDN: replace the URLs

Already loading Yasgui from a CDN? Replace just the stylesheet and script URLs. The constructor and endpoint configuration stay the same. No bundler or local asset copies are needed.

@ldforge/yasgui is not published on npm yet, so the LDForge CDN URLs below will work after publication. They show the current workspace version, 0.1.7; use the published release version when migrating.

 <!doctype html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
-  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@triply/yasgui@4.2.28/build/yasgui.min.css">
+  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ldforge/yasgui@0.1.7/dist/yasgui.css">
 </head>
 <body>
   <div id="editor"></div>
-  <script src="https://cdn.jsdelivr.net/npm/@triply/yasgui@4.2.28/build/yasgui.min.js"></script>
+  <script src="https://cdn.jsdelivr.net/npm/@ldforge/yasgui@0.1.7/dist/yasgui.min.js"></script>
   <script>
     const editor = new Yasgui(document.getElementById('editor'), {
       requestConfig: { endpoint: 'https://dbpedia.org/sparql' },
       yasqe: { value: 'SELECT * WHERE { ?s ?p ?o } LIMIT 10' },
     });
   </script>
 </body>
 </html>

− Remove + Add · Copy HTML copies the new version.

With a bundler, replace your JavaScript import with import Yasgui from '@ldforge/yasgui' and your stylesheet import with import '@ldforge/yasgui/styles.css'.

This module supports common constructor options, request settings, tab methods and events. Yasr plugins and CodeMirror 5 extensions need migration. See the compatibility reference for the supported API and differences.

Explore the complete API

The API reference documents configuration defaults, every built-in control, the editor handle, live tab collections, per-tab methods, prefixes, plugins and transport. Start with Configuration or QueryTabHandle.