@virgo-nsh/highlighter 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ - Add `highlighter.observeElement()` for opt-in, one-time highlighting of existing code blocks as they enter the viewport or a custom scroll container.
6
+ - Support `rootMargin` to start highlighting before the block becomes visible. The default margin is `0px`.
7
+ - Return a cleanup function that stops observation and skips late rendering when a block is removed or reused.
8
+
9
+ ## 0.1.0
10
+
11
+ - Publish the browser highlighter as `@virgo-nsh/highlighter`, with semantic spans, escaped HTML, themes, and on-demand loading of separately hosted models.
package/README.md CHANGED
@@ -21,7 +21,7 @@ The npm package includes the API, HTML renderer, CSS themes and browser runtime.
21
21
  Serve the ONNX models and their JSON metadata from your app or a static host.
22
22
  The browser downloads the files on first use and runs inference locally.
23
23
 
24
- For version 0.1.0, download and unpack the
24
+ For versions 0.1.0 and 0.1.1, download and unpack the
25
25
  [matching model source snapshot](https://github.com/virgo-galaxy/virgo-nsh/archive/7109bac49340b94ad5350778e32ee0d4196c5698.tar.gz).
26
26
  From its root, export the model families you need with Node.js 24 and pnpm 11:
27
27
 
@@ -65,6 +65,24 @@ Use `@virgo-nsh/highlighter/catalog` to list content types. Load all presets wit
65
65
  [theme guide](https://github.com/virgo-galaxy/virgo-nsh/blob/main/docs/themes.md)
66
66
  for light and dark modes and custom CSS.
67
67
 
68
+ ## Highlight on scroll
69
+
70
+ Use `observeElement()` to highlight an existing `<code>` or `<pre><code>` block
71
+ once, when it comes into view.
72
+
73
+ ```ts
74
+ const stop = highlighter.observeElement(codeElement, {
75
+ language: "tsx",
76
+ rootMargin: "128px",
77
+ });
78
+
79
+ // Call stop() when the block is removed or reused.
80
+ ```
81
+
82
+ The default root is the viewport and the default margin is `0px`. Set `root`
83
+ to use a scroll container. Without Intersection Observer, highlighting starts
84
+ immediately. The optional `onError` callback receives inference errors.
85
+
68
86
  ## License
69
87
 
70
88
  The project's code and documentation are licensed under MIT. The package
@@ -16,6 +16,11 @@ export interface HighlightedCode {
16
16
  html: string;
17
17
  result: HighlightResult;
18
18
  }
19
+ export interface ObserveElementOptions extends Pick<IntersectionObserverInit, "root" | "rootMargin"> {
20
+ language?: string;
21
+ /** Called if highlighting fails. The original source stays in the code block. */
22
+ onError?: (error: unknown) => void;
23
+ }
19
24
  export interface BrowserHighlighter {
20
25
  highlight(code: string, options: {
21
26
  language: string;
@@ -24,6 +29,8 @@ export interface BrowserHighlighter {
24
29
  highlightElement(element: HTMLElement, options?: {
25
30
  language?: string;
26
31
  }): Promise<HighlightedCode>;
32
+ /** Highlight once on intersection and return a function that stops observation and rendering. */
33
+ observeElement(element: HTMLElement, options?: ObserveElementOptions): () => void;
27
34
  supports(language: string): boolean;
28
35
  languages(): readonly string[];
29
36
  close(): void;
@@ -8,6 +8,12 @@ import { createCompositeVuePack } from "./internal/core/composition/vue.js";
8
8
  import { renderCodeToHtml, renderToHtml } from "./internal/html/index.js";
9
9
  import { RemoteModelSource } from "./remote.js";
10
10
  export { clearModelCache, ModelAssetError } from "./internal/browser/index.js";
11
+ function applyElementHighlight(element, result) {
12
+ element.innerHTML = result.value;
13
+ const wrapper = element.parentElement?.tagName === "PRE" ? element.parentElement : element;
14
+ wrapper.classList.add("nsh");
15
+ wrapper.dataset.language = result.language;
16
+ }
11
17
  /** Configure selected models explicitly; no Node/Python imports or source uploads. */
12
18
  export function createHighlighter(options = {}) {
13
19
  const runtime = new BrowserRuntime(options);
@@ -77,6 +83,7 @@ export function createHighlighter(options = {}) {
77
83
  const core = createCoreHighlighter({ packs });
78
84
  let closed = false;
79
85
  const pending = new Set();
86
+ const observations = new Set();
80
87
  const infer = (request) => {
81
88
  if (closed)
82
89
  return Promise.reject(new Error("Browser highlighter is closed"));
@@ -103,27 +110,78 @@ export function createHighlighter(options = {}) {
103
110
  html: renderToHtml(request),
104
111
  };
105
112
  };
113
+ const highlightElementSource = async (element, language, source = element.textContent ?? "") => {
114
+ const kind = language ??
115
+ element.dataset.language ??
116
+ [...element.classList].find((name) => name.startsWith("language-"))?.slice(9) ??
117
+ element.parentElement?.dataset.language;
118
+ if (!kind)
119
+ throw new Error("Set a language, for example language-tsx or data-language=tsx");
120
+ return highlight(source, { language: kind });
121
+ };
106
122
  return {
107
123
  highlight,
108
124
  highlightTokens: ({ source, documentKind }) => infer({ source, documentKind: kindFor(documentKind) }),
109
- async highlightElement(element, options = {}) {
110
- const language = options.language ??
111
- element.dataset.language ??
112
- [...element.classList].find((name) => name.startsWith("language-"))?.slice(9) ??
113
- element.parentElement?.dataset.language;
114
- if (!language)
115
- throw new Error("Set a language, for example language-tsx or data-language=tsx");
116
- const result = await highlight(element.textContent ?? "", { language });
117
- element.innerHTML = result.value;
118
- const wrapper = element.parentElement?.tagName === "PRE" ? element.parentElement : element;
119
- wrapper.classList.add("nsh");
120
- wrapper.dataset.language = result.language;
125
+ async highlightElement(element, { language } = {}) {
126
+ const result = await highlightElementSource(element, language);
127
+ applyElementHighlight(element, result);
121
128
  return result;
122
129
  },
130
+ observeElement(element, { language, root, rootMargin, onError } = {}) {
131
+ if (closed)
132
+ throw new Error("Browser highlighter is closed");
133
+ let observer;
134
+ let started = false;
135
+ let stopped = false;
136
+ const stop = () => {
137
+ stopped = true;
138
+ observer?.disconnect();
139
+ observations.delete(stop);
140
+ };
141
+ const highlightOnce = async () => {
142
+ if (started || stopped)
143
+ return;
144
+ started = true;
145
+ observer?.disconnect();
146
+ const code = (element.tagName === "PRE" && element.querySelector(":scope > code")) ||
147
+ element;
148
+ const source = code.textContent ?? "";
149
+ try {
150
+ const result = await highlightElementSource(code, language, source);
151
+ // The consumer can replace the code node or update its text during inference.
152
+ if (!stopped &&
153
+ (code === element || code.parentElement === element) &&
154
+ (code.textContent ?? "") === source) {
155
+ applyElementHighlight(code, result);
156
+ }
157
+ }
158
+ catch (error) {
159
+ if (!stopped)
160
+ onError?.(error);
161
+ }
162
+ finally {
163
+ stop();
164
+ }
165
+ };
166
+ if (typeof IntersectionObserver !== "undefined") {
167
+ observer = new IntersectionObserver((entries) => {
168
+ if (entries.some((entry) => entry.isIntersecting))
169
+ void highlightOnce();
170
+ }, { root, rootMargin });
171
+ }
172
+ observations.add(stop);
173
+ if (observer)
174
+ observer.observe(element);
175
+ else
176
+ void highlightOnce();
177
+ return stop;
178
+ },
123
179
  supports: (language) => core.supports(kindFor(language)),
124
180
  languages: () => core.documentKinds(),
125
181
  close: () => {
126
182
  closed = true;
183
+ for (const stop of observations)
184
+ stop();
127
185
  for (const reject of pending)
128
186
  reject(new Error("Browser highlighter is closed"));
129
187
  pending.clear();
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export { type BrowserHighlighter, type BrowserRuntimeOptions, clearModelCache, createHighlighter, type HighlightedCode, type HighlighterOptions, ModelAssetError, type ModelAssetRequest, type ModelCacheOptions, type RemoteModelOptions, } from "./highlighter.js";
1
+ export { type BrowserHighlighter, type BrowserRuntimeOptions, clearModelCache, createHighlighter, type HighlightedCode, type HighlighterOptions, ModelAssetError, type ModelAssetRequest, type ModelCacheOptions, type ObserveElementOptions, type RemoteModelOptions, } from "./highlighter.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@virgo-nsh/highlighter",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Neural code highlighting directly in the browser",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -33,7 +33,8 @@
33
33
  }
34
34
  },
35
35
  "files": [
36
- "dist"
36
+ "dist",
37
+ "CHANGELOG.md"
37
38
  ],
38
39
  "sideEffects": [
39
40
  "**/*.css"