@nesso-how/ui 1.0.0-alpha.32 → 1.0.0-alpha.33

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/README.md CHANGED
@@ -39,7 +39,7 @@ Your build must compile this CSS; it is not a precompiled stylesheet. Supply the
39
39
 
40
40
  | Area | Exports |
41
41
  | ---------------------- | ------------------------------------------------------------------------------------------------------------------------- |
42
- | Buttons and inputs | `Button`, `IconButton`, `Input`, `Label`, `PreferenceSelect`, `ColorPicker` |
42
+ | Buttons and inputs | `Button`, `IconButton`, `Input`, `MarkdownInput`, `Label`, `PreferenceSelect`, `ColorPicker` |
43
43
  | Forms and rows | `Field`, `FieldHint`, `ListRow`, `ListRowButton`, `ListRowDetail`, `ListRowTitle`, `RevealActions`, `PromptForm` |
44
44
  | Menus and popovers | `Menu`, `MenuItem`, `MenuPopup`, `MenuRadioItem`, `Popover`, `PopoverPopup` |
45
45
  | Search and suggestions | `Combobox`, `ComboboxItem`, `ComboboxPopup`, `Autocomplete`, `AutocompleteClear`, `AutocompleteItem`, `AutocompletePopup` |
@@ -50,4 +50,6 @@ Your build must compile this CSS; it is not a precompiled stylesheet. Supply the
50
50
 
51
51
  `Button` supports `default`, `outline`, and `ghost` variants. `SidePanel` supports controlled resizing and collapse. `Spinner` accepts an accessible `label` and respects reduced motion. State, content, and event handling remain yours to provide.
52
52
 
53
+ `MarkdownInput` provides a live preview of bold, italic, links, and bullet or numbered lists in one field without a toolbar. Markdown delimiters reappear when the cursor or selection enters formatted text, including link destinations and list markers. Enter continues a list, incrementing the current number for numbered lists; Enter on an empty nested item returns to the parent level, and on an empty top-level item ends the list. Tab nests the current item under the previous one; Shift+Tab moves it up a level. Both move the item's continuation lines and children together, leaving unrelated text alone. At level boundaries they leave content and focus unchanged; outside lists they retain normal focus navigation. Shift+Enter inserts a plain line break. Existing items are not renumbered, and there are no checklists. It accepts the unchanged Markdown source through `value` and `onChange`, supports Cmd/Ctrl+B/I on selections, and preserves line breaks. Set `history={false}` when the host owns undo/redo and its shortcuts. Cmd/Ctrl-click requests `onOpenLink`; read-only fields request it on a regular click. The host is responsible for validating and opening destinations.
54
+
53
55
  The package also exports `useMediaQuery`, `contrastColor`, `presetColors`, and the `ActionIconName` and `ToastItem` types. See the [public exports](https://github.com/nesso-how/nesso/blob/main/packages/ui/src/index.ts) and component source files for prop definitions; published TypeScript declarations provide editor completion.
package/dist/index.d.ts CHANGED
@@ -50,6 +50,16 @@ export declare function useMediaQuery(query: string): boolean;
50
50
  //#region src/input.d.ts
51
51
  declare function Input({ className, type, ...props }: ComponentProps<'input'>): import("react").JSX.Element;
52
52
  //#endregion
53
+ //#region src/markdown-input.d.ts
54
+ type MarkdownInputProps = Omit<ComponentProps<'div'>, 'onChange' | 'children' | 'defaultValue'> & {
55
+ value: string;
56
+ onChange: (value: string) => void;
57
+ readOnly?: boolean;
58
+ history?: boolean;
59
+ onOpenLink?: (url: string) => void;
60
+ };
61
+ export declare function MarkdownInput({ value, onChange, readOnly, history, onOpenLink, className, id, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, ...props }: MarkdownInputProps): import("react").JSX.Element;
62
+ //#endregion
53
63
  //#region src/label.d.ts
54
64
  declare function Label({ className, ...props }: ComponentProps<'label'>): import("react").JSX.Element;
55
65
  //#endregion
package/dist/index.js CHANGED
@@ -5,6 +5,10 @@ import { jsx, jsxs } from "react/jsx-runtime";
5
5
  import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
6
6
  import { ArrowRight, BookOpen, Check, ChevronDown, ChevronLeft, ChevronRight, CircleHelp, ClipboardPaste, Copy, Download, FileDown, FileUp, Folder, Glasses, Globe, Info, Layers, Minus, Pencil, Play, Plus, RefreshCw, RotateCcw, Scissors, Search, Share2, Sparkles, TriangleAlert, Upload, X, Zap } from "lucide-react";
7
7
  import { Input as Input$1 } from "@base-ui/react/input";
8
+ import { Annotation, Compartment, EditorSelection, EditorState, Transaction } from "@codemirror/state";
9
+ import { Decoration, EditorView, ViewPlugin, WidgetType, keymap } from "@codemirror/view";
10
+ import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
11
+ import { parser } from "@lezer/markdown";
8
12
  import { Dialog, Dialog as Dialog$1 } from "@base-ui/react/dialog";
9
13
  import { Combobox } from "@base-ui/react/combobox";
10
14
  import { Menu } from "@base-ui/react/menu";
@@ -216,6 +220,338 @@ function Input({ className, type, ...props }) {
216
220
  });
217
221
  }
218
222
  //#endregion
223
+ //#region src/markdown.ts
224
+ const listPrefix = /^(\s*)([-+*]|(\d{1,9})([.)]))([\t ]+|$)/;
225
+ var ListMarker = class extends WidgetType {
226
+ label;
227
+ constructor(label) {
228
+ super();
229
+ this.label = label;
230
+ }
231
+ eq(other) {
232
+ return this.label === other.label;
233
+ }
234
+ toDOM(view) {
235
+ const marker = view.dom.ownerDocument.createElement("span");
236
+ marker.className = "nesso-markdown-list-marker";
237
+ marker.textContent = this.label;
238
+ return marker;
239
+ }
240
+ ignoreEvent() {
241
+ return false;
242
+ }
243
+ };
244
+ function markdownDecorations(state, focused) {
245
+ const source = state.doc.toString();
246
+ const decorations = [];
247
+ const syntax = (from, to, active) => {
248
+ if (from >= to || source.slice(from, to).includes("\n")) return;
249
+ const decoration = active ? Decoration.mark({ class: "nesso-markdown-syntax" }) : Decoration.replace({});
250
+ decorations.push(decoration.range(from, to));
251
+ };
252
+ parser.parse(source).iterate({ enter(node) {
253
+ if ([
254
+ "Image",
255
+ "InlineCode",
256
+ "FencedCode",
257
+ "CodeBlock",
258
+ "HTMLBlock"
259
+ ].includes(node.name)) return false;
260
+ const active = focused && state.selection.ranges.some((range) => range.from <= node.to && range.to >= node.from);
261
+ if (node.name === "ListItem") {
262
+ const marker = node.node.getChild("ListMark");
263
+ const line = state.doc.lineAt(marker.from);
264
+ const end = marker.to + (source.slice(marker.to, line.to).match(/^[\t ]*/)?.[0].length ?? 0);
265
+ const label = node.node.parent?.name === "BulletList" ? "•" : source.slice(marker.from, marker.to);
266
+ const width = Math.max(3, end - marker.from);
267
+ decorations.push(Decoration.line({
268
+ class: "nesso-markdown-list-item",
269
+ attributes: { style: `--nesso-list-indent: ${width}ch; --nesso-list-padding: ${marker.from - line.from + width}ch` }
270
+ }).range(line.from), (active ? Decoration.mark({ class: "nesso-markdown-syntax nesso-markdown-list-marker" }) : Decoration.replace({ widget: new ListMarker(`${label} `) })).range(marker.from, end));
271
+ }
272
+ if (node.name === "StrongEmphasis" || node.name === "Emphasis") {
273
+ const [open, close] = node.node.getChildren("EmphasisMark");
274
+ decorations.push(Decoration.mark({ class: node.name === "StrongEmphasis" ? "nesso-markdown-bold" : "nesso-markdown-italic" }).range(open.to, close.from));
275
+ syntax(open.from, open.to, active);
276
+ syntax(close.from, close.to, active);
277
+ }
278
+ if (node.name === "Link") {
279
+ const url = node.node.getChild("URL");
280
+ if (!url) return;
281
+ const [open, close] = node.node.getChildren("LinkMark");
282
+ decorations.push(Decoration.mark({
283
+ class: "nesso-markdown-link",
284
+ attributes: { "data-markdown-link": source.slice(url.from, url.to).replace(/^<|>$/g, "") }
285
+ }).range(open.to, close.from));
286
+ syntax(open.from, open.to, active);
287
+ syntax(close.from, node.to, active);
288
+ }
289
+ } });
290
+ return Decoration.set(decorations, true);
291
+ }
292
+ function markdownListItem(state) {
293
+ if (state.readOnly || state.selection.ranges.length !== 1) return null;
294
+ const { from, to } = state.selection.main;
295
+ if (to > state.doc.lineAt(from).to) return null;
296
+ let node = parser.parse(state.doc.toString()).resolveInner(from, -1);
297
+ while (node.name !== "ListItem") {
298
+ if ([
299
+ "FencedCode",
300
+ "CodeBlock",
301
+ "HTMLBlock"
302
+ ].includes(node.name) || !node.parent) return null;
303
+ node = node.parent;
304
+ }
305
+ const firstLine = state.doc.lineAt(node.from);
306
+ const prefix = firstLine.text.match(listPrefix);
307
+ if (!prefix || to > node.to) return null;
308
+ return {
309
+ node,
310
+ firstLine,
311
+ prefix
312
+ };
313
+ }
314
+ function nextListPrefix(prefix) {
315
+ const number = prefix[3] ? Number(prefix[3]) + 1 : null;
316
+ if (number !== null && number > 999999999) return null;
317
+ const marker = number === null ? prefix[2] : `${number}${prefix[4]}`;
318
+ return `${prefix[1]}${marker}${prefix[5] || " "}`;
319
+ }
320
+ function indentMarkdownList(state, outdent = false) {
321
+ const item = markdownListItem(state);
322
+ if (!item) return null;
323
+ const { node, firstLine, prefix } = item;
324
+ const parent = node.parent?.parent;
325
+ let indentation = "";
326
+ if (outdent) {
327
+ if (!prefix[1]) return {};
328
+ if (parent?.name === "ListItem") {
329
+ const parentPrefix = state.doc.lineAt(parent.from).text.match(listPrefix);
330
+ if (!parentPrefix) return {};
331
+ indentation = parentPrefix[1];
332
+ }
333
+ } else {
334
+ const previous = node.prevSibling ?? node.parent?.prevSibling?.lastChild;
335
+ if (previous?.name !== "ListItem") return {};
336
+ const previousPrefix = state.doc.lineAt(previous.from).text.match(listPrefix);
337
+ if (!previousPrefix) return {};
338
+ indentation = previousPrefix[1] + " ".repeat(previousPrefix[0].length - previousPrefix[1].length);
339
+ }
340
+ const difference = indentation.length - prefix[1].length;
341
+ if (difference === 0) return {};
342
+ const edits = [];
343
+ for (let number = firstLine.number; number <= state.doc.lineAt(node.to).number; number++) {
344
+ const line = state.doc.line(number);
345
+ if (!line.text) continue;
346
+ edits.push({
347
+ from: line.from,
348
+ to: line.from + (difference < 0 ? Math.min(-difference, line.text.match(/^\s*/)[0].length) : 0),
349
+ insert: difference > 0 ? " ".repeat(difference) : ""
350
+ });
351
+ }
352
+ const changes = state.changes(edits);
353
+ return {
354
+ changes,
355
+ selection: state.selection.map(changes, 1),
356
+ userEvent: "input.indent"
357
+ };
358
+ }
359
+ function continueMarkdownList(state) {
360
+ const item = markdownListItem(state);
361
+ if (!item) return null;
362
+ const { node, firstLine, prefix } = item;
363
+ let { from, to } = state.selection.main;
364
+ if (from < firstLine.from + prefix[0].length) return null;
365
+ let insert = nextListPrefix(prefix);
366
+ if (state.doc.lineAt(from).from === firstLine.from && !firstLine.text.slice(prefix[0].length).trim()) {
367
+ const parent = node.parent?.parent;
368
+ const parentPrefix = parent?.name === "ListItem" ? state.doc.lineAt(parent.from).text.match(listPrefix) : null;
369
+ insert = parentPrefix ? nextListPrefix(parentPrefix) : "";
370
+ from = firstLine.from;
371
+ to = firstLine.to;
372
+ } else if (insert !== null) insert = `\n${insert}`;
373
+ if (insert === null) return null;
374
+ return {
375
+ changes: {
376
+ from,
377
+ to,
378
+ insert
379
+ },
380
+ selection: EditorSelection.cursor(from + insert.length),
381
+ userEvent: "input"
382
+ };
383
+ }
384
+ function toggleMarkdownFormat(state, marker) {
385
+ if (state.readOnly) return null;
386
+ const { from, to } = state.selection.main;
387
+ const selected = state.sliceDoc(from, to);
388
+ let delimiters;
389
+ parser.parse(state.doc.toString()).iterate({ enter(node) {
390
+ if (node.name !== (marker === "**" ? "StrongEmphasis" : "Emphasis")) return;
391
+ const [open, close] = node.node.getChildren("EmphasisMark");
392
+ if (from === node.from && to === node.to || from >= open.to && to <= close.from) delimiters = [open, close].map(({ from, to }) => ({
393
+ from,
394
+ to
395
+ }));
396
+ } });
397
+ if (delimiters) {
398
+ const changes = state.changes(delimiters);
399
+ return {
400
+ changes,
401
+ selection: state.selection.map(changes),
402
+ userEvent: "input.format"
403
+ };
404
+ }
405
+ return {
406
+ changes: {
407
+ from,
408
+ to,
409
+ insert: `${marker}${selected}${marker}`
410
+ },
411
+ selection: EditorSelection.range(from + marker.length, to + marker.length),
412
+ userEvent: "input.format"
413
+ };
414
+ }
415
+ //#endregion
416
+ //#region src/markdown-input.tsx
417
+ const externalChange = Annotation.define();
418
+ const livePreview = ViewPlugin.define((view) => ({
419
+ decorations: markdownDecorations(view.state, view.hasFocus && !view.state.readOnly),
420
+ update(update) {
421
+ if (update.docChanged || update.selectionSet || update.focusChanged || update.startState.readOnly !== update.state.readOnly) this.decorations = markdownDecorations(update.state, update.view.hasFocus && !update.state.readOnly);
422
+ }
423
+ }), { decorations: (plugin) => plugin.decorations });
424
+ function MarkdownInput({ value, onChange, readOnly = false, history: history$1 = true, onOpenLink, className, id, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, ...props }) {
425
+ const container = useRef(null);
426
+ const editor = useRef(null);
427
+ const callbacks = useRef({
428
+ onChange,
429
+ onOpenLink
430
+ });
431
+ const [configuration] = useState(() => new Compartment());
432
+ const [initialValue] = useState(value);
433
+ useLayoutEffect(() => {
434
+ callbacks.current = {
435
+ onChange,
436
+ onOpenLink
437
+ };
438
+ }, [onChange, onOpenLink]);
439
+ useLayoutEffect(() => {
440
+ const view = new EditorView({
441
+ parent: container.current,
442
+ doc: initialValue,
443
+ extensions: [
444
+ EditorView.lineWrapping,
445
+ EditorView.theme({
446
+ "&.cm-focused": { outline: "none" },
447
+ ".cm-scroller": {
448
+ fontFamily: "inherit",
449
+ lineHeight: "inherit",
450
+ overflow: "visible"
451
+ },
452
+ ".cm-content, .cm-line": { padding: "0" },
453
+ ".cm-line.nesso-markdown-list-item": {
454
+ paddingInlineStart: "var(--nesso-list-padding)",
455
+ textIndent: "calc(-1 * var(--nesso-list-padding))"
456
+ }
457
+ }),
458
+ livePreview,
459
+ configuration.of([]),
460
+ keymap.of([
461
+ ...["Tab", "Shift-Tab"].map((key) => ({
462
+ key,
463
+ run: (view) => {
464
+ const transaction = indentMarkdownList(view.state, key === "Shift-Tab");
465
+ if (!transaction) return false;
466
+ view.dispatch({
467
+ ...transaction,
468
+ scrollIntoView: true
469
+ });
470
+ return true;
471
+ }
472
+ })),
473
+ {
474
+ key: "Enter",
475
+ run: (view) => {
476
+ const transaction = continueMarkdownList(view.state);
477
+ if (!transaction) return false;
478
+ view.dispatch({
479
+ ...transaction,
480
+ scrollIntoView: true
481
+ });
482
+ return true;
483
+ }
484
+ },
485
+ ...["**", "*"].map((marker) => ({
486
+ key: marker === "**" ? "Mod-b" : "Mod-i",
487
+ run: (view) => {
488
+ const transaction = toggleMarkdownFormat(view.state, marker);
489
+ if (!transaction) return false;
490
+ view.dispatch(transaction);
491
+ return true;
492
+ }
493
+ })),
494
+ ...defaultKeymap
495
+ ]),
496
+ EditorView.updateListener.of((update) => {
497
+ if (update.docChanged && !update.transactions.some((t) => t.annotation(externalChange))) callbacks.current.onChange(update.state.doc.toString());
498
+ }),
499
+ EditorView.domEventHandlers({ click(event, view) {
500
+ const url = event.target.closest("[data-markdown-link]")?.getAttribute("data-markdown-link");
501
+ if (!url || !(event.metaKey || event.ctrlKey || view.state.readOnly)) return false;
502
+ event.preventDefault();
503
+ callbacks.current.onOpenLink?.(url);
504
+ return true;
505
+ } })
506
+ ]
507
+ });
508
+ editor.current = view;
509
+ return () => {
510
+ editor.current = null;
511
+ view.destroy();
512
+ };
513
+ }, [configuration, initialValue]);
514
+ useLayoutEffect(() => {
515
+ editor.current?.dispatch({ effects: configuration.reconfigure([
516
+ EditorState.readOnly.of(readOnly),
517
+ EditorView.editable.of(!readOnly),
518
+ EditorView.contentAttributes.of({
519
+ ...id ? { id } : {},
520
+ ...ariaLabel ? { "aria-label": ariaLabel } : {},
521
+ ...ariaLabelledBy ? { "aria-labelledby": ariaLabelledBy } : {},
522
+ "aria-multiline": "true",
523
+ "aria-readonly": String(readOnly),
524
+ spellcheck: "true"
525
+ }),
526
+ ...history$1 ? [history(), keymap.of(historyKeymap)] : []
527
+ ]) });
528
+ }, [
529
+ configuration,
530
+ readOnly,
531
+ history$1,
532
+ id,
533
+ ariaLabel,
534
+ ariaLabelledBy
535
+ ]);
536
+ useLayoutEffect(() => {
537
+ const view = editor.current;
538
+ if (!view || value === view.state.doc.toString()) return;
539
+ view.dispatch({
540
+ changes: {
541
+ from: 0,
542
+ to: view.state.doc.length,
543
+ insert: value
544
+ },
545
+ annotations: [externalChange.of(true), Transaction.addToHistory.of(false)]
546
+ });
547
+ }, [value]);
548
+ return /* @__PURE__ */ jsx("div", {
549
+ ...props,
550
+ ref: container,
551
+ className: cn("nesso-input nesso-markdown-input min-h-24 w-full overflow-y-auto border border-input bg-background px-2.5 py-2 focus-within:border-muted-foreground", className)
552
+ });
553
+ }
554
+ //#endregion
219
555
  //#region src/label.tsx
220
556
  function Label({ className, ...props }) {
221
557
  return /* @__PURE__ */ jsx("label", {
@@ -1086,4 +1422,4 @@ function ActionIcon({ name, ...props }) {
1086
1422
  });
1087
1423
  }
1088
1424
  //#endregion
1089
- export { ActionIcon, Autocomplete, AutocompleteClear, AutocompleteItem, AutocompletePopup, Banner, Button, Collapsible, ColorPicker, Combobox, ComboboxItem, ComboboxPopup, ConfirmDialog, ContextLabel, Dialog, DialogActions, DialogPopup, Field, FieldHint, IconButton, Input, Kbd, Label, ListRow, ListRowButton, ListRowDetail, ListRowTitle, Menu, MenuItem, MenuPopup, MenuRadioItem, PanelHeader, Popover, PopoverPopup, PreferenceSelect, PromptForm, RevealActions, SectionHeading, SidePanel, Spinner, Tabs, TextPromptDialog, ToastViewport, contrastColor, presetColors, useMediaQuery };
1425
+ export { ActionIcon, Autocomplete, AutocompleteClear, AutocompleteItem, AutocompletePopup, Banner, Button, Collapsible, ColorPicker, Combobox, ComboboxItem, ComboboxPopup, ConfirmDialog, ContextLabel, Dialog, DialogActions, DialogPopup, Field, FieldHint, IconButton, Input, Kbd, Label, ListRow, ListRowButton, ListRowDetail, ListRowTitle, MarkdownInput, Menu, MenuItem, MenuPopup, MenuRadioItem, PanelHeader, Popover, PopoverPopup, PreferenceSelect, PromptForm, RevealActions, SectionHeading, SidePanel, Spinner, Tabs, TextPromptDialog, ToastViewport, contrastColor, presetColors, useMediaQuery };
package/dist/styles.css CHANGED
@@ -44,6 +44,38 @@
44
44
  outline: none;
45
45
  }
46
46
 
47
+ .nesso-markdown-input {
48
+ display: flex;
49
+ }
50
+
51
+ .nesso-markdown-input .cm-editor {
52
+ flex: 1;
53
+ min-width: 0;
54
+ }
55
+
56
+ .nesso-markdown-bold {
57
+ font-weight: 700;
58
+ }
59
+
60
+ .nesso-markdown-italic {
61
+ font-style: italic;
62
+ }
63
+
64
+ .nesso-markdown-link {
65
+ color: var(--primary);
66
+ text-decoration: underline;
67
+ }
68
+
69
+ .nesso-markdown-syntax {
70
+ color: var(--muted-foreground);
71
+ }
72
+
73
+ .nesso-markdown-list-marker {
74
+ display: inline-block;
75
+ min-width: var(--nesso-list-indent);
76
+ text-indent: 0;
77
+ }
78
+
47
79
  .nesso-popup {
48
80
  border: 1px solid var(--border);
49
81
  border-radius: var(--radius-object);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nesso-how/ui",
3
- "version": "1.0.0-alpha.32",
3
+ "version": "1.0.0-alpha.33",
4
4
  "description": "Reusable React primitives and shared styles for Nesso, usable in the app and in isolated plugin panels",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -26,6 +26,10 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@base-ui/react": "^1.8.0",
29
+ "@codemirror/commands": "^6.11.1",
30
+ "@codemirror/state": "^6.7.6",
31
+ "@codemirror/view": "^6.43.15",
32
+ "@lezer/markdown": "^1.8.1",
29
33
  "class-variance-authority": "^0.7.1",
30
34
  "cn": "^0.4.0",
31
35
  "lucide-react": "^1.48.0"