@placeholderco/placeholder-ui 3.3.1 → 3.3.3

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
@@ -1,5 +1,8 @@
1
1
  # PlaceholderUI
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@placeholderco/placeholder-ui?style=for-the-badge&logo=npm&color=cb3837)](https://www.npmjs.com/package/@placeholderco/placeholder-ui)
4
+ [![Live preview](https://img.shields.io/badge/preview-live%20demo-ff3e00?style=for-the-badge&logo=svelte&logoColor=white)](https://placeholderui.github.io/placeholder-ui/)
5
+
3
6
  A Svelte 5 component library that you re-brand with a single config object.
4
7
  Forms, overlays, layout, data display, a TipTap rich-text editor and a
5
8
  CodeMirror code editor, all styled through one set of `--ui-*` CSS tokens.
@@ -1,6 +1,7 @@
1
1
  <script lang="ts">
2
- import { onMount, onDestroy } from 'svelte';
2
+ import { onMount, onDestroy, untrack } from 'svelte';
3
3
  import {
4
+ Decoration,
4
5
  EditorView,
5
6
  lineNumbers as lineNumbersGutter,
6
7
  highlightActiveLineGutter,
@@ -10,9 +11,10 @@
10
11
  rectangularSelection,
11
12
  crosshairCursor,
12
13
  highlightActiveLine,
13
- keymap
14
+ keymap,
15
+ placeholder as placeholderText
14
16
  } from '@codemirror/view';
15
- import { EditorState, Compartment } from '@codemirror/state';
17
+ import { EditorState, Compartment, RangeSetBuilder, type Extension } from '@codemirror/state';
16
18
  import {
17
19
  foldGutter,
18
20
  foldKeymap,
@@ -30,27 +32,43 @@
30
32
  completionKeymap
31
33
  } from '@codemirror/autocomplete';
32
34
  import { lintKeymap } from '@codemirror/lint';
33
- import { javascript } from '@codemirror/lang-javascript';
34
- import { html } from '@codemirror/lang-html';
35
- import { css } from '@codemirror/lang-css';
36
- import { json } from '@codemirror/lang-json';
37
- import { markdown } from '@codemirror/lang-markdown';
38
35
  import { oneDark } from '@codemirror/theme-one-dark';
39
36
  import { themeState } from '../theme.svelte.js';
40
37
  import ActionIcon from '../ui/ActionIcon.svelte';
41
- import { iconCopy, iconCheck } from '../icon/index.js';
38
+ import { iconArrowDown, iconCopy, iconCheck } from '../icon/index.js';
39
+ import { resolveCodeLanguage, type CodeLanguageId } from './codemirror/languages.js';
40
+ import { libraryTheme } from './codemirror/theme.js';
42
41
 
43
42
  export interface CodeMirrorProps {
44
- /** Editor content value (bindable) */
43
+ /** Editor content value (bindable). A new value that extends the current one is
44
+ * appended, so a growing log keeps its selection and scroll position. */
45
45
  value?: string;
46
- /** Programming language for syntax highlighting */
47
- language?: 'javascript' | 'html' | 'css' | 'json' | 'typescript' | 'markdown';
48
- /** Color theme for the editor (defaults to app theme) */
46
+ /** Language for syntax highlighting: an id from `codeLanguages` or one of its aliases
47
+ * ('ps1', 'py', 'yml', ...). Anything unrecognised shows as plain text. */
48
+ language?: CodeLanguageId | (string & {});
49
+ /** Color theme. 'auto' (the default) follows the app's mode with the library's own
50
+ * colours; 'light' and 'dark' force CodeMirror's default style and One Dark. */
49
51
  theme?: 'light' | 'dark' | 'auto';
50
52
  /** Disable editing */
51
53
  readOnly?: boolean;
52
54
  /** Show line numbers in the gutter */
53
55
  lineNumbers?: boolean;
56
+ /** Number shown for the first line, when the value is a window into a longer file */
57
+ firstLineNumber?: number;
58
+ /** Wrap long lines instead of scrolling sideways */
59
+ wrap?: boolean;
60
+ /** Keep the last line in view as the value grows, until the user scrolls up; a button
61
+ * then jumps back to the end */
62
+ follow?: boolean;
63
+ /** Line numbers (as shown, so counted from `firstLineNumber`) to highlight, such as
64
+ * search matches */
65
+ markedLines?: number[];
66
+ /** Text shown while the editor is empty */
67
+ placeholder?: string;
68
+ /** Accessible name for the editor */
69
+ ariaLabel?: string;
70
+ /** Extra CodeMirror extensions, added after the built-in ones; changes apply live */
71
+ extensions?: Extension[];
54
72
  /** Show a button that copies the editor contents to the clipboard */
55
73
  copyButton?: boolean;
56
74
  /** Additional CSS classes */
@@ -69,6 +87,13 @@
69
87
  theme = 'auto',
70
88
  readOnly = false,
71
89
  lineNumbers = true,
90
+ firstLineNumber = 1,
91
+ wrap = true,
92
+ follow = false,
93
+ markedLines = [],
94
+ placeholder = '',
95
+ ariaLabel = '',
96
+ extensions = [],
72
97
  copyButton = false,
73
98
  class: className = '',
74
99
  height = '31.25rem',
@@ -80,8 +105,16 @@
80
105
  let view: EditorView | null = $state(null);
81
106
  let themeCompartment = new Compartment();
82
107
  let gutterCompartment = new Compartment();
108
+ let languageCompartment = new Compartment();
109
+ let readOnlyCompartment = new Compartment();
110
+ let wrapCompartment = new Compartment();
111
+ let marksCompartment = new Compartment();
112
+ let attributesCompartment = new Compartment();
113
+ let userCompartment = new Compartment();
83
114
  let copied = $state(false);
84
115
  let copiedTimeout: ReturnType<typeof setTimeout>;
116
+ /** Whether the view is at the last line, so `follow` keeps it there. */
117
+ let pinned = $state(true);
85
118
 
86
119
  // basicSetup minus the gutters, which we swap in via a compartment so the
87
120
  // `lineNumbers` prop can be toggled after the editor is created.
@@ -111,47 +144,63 @@
111
144
  ])
112
145
  ];
113
146
 
114
- const getGutterExtension = (show: boolean) =>
115
- show ? [lineNumbersGutter(), highlightActiveLineGutter(), foldGutter()] : [];
147
+ const getGutterExtension = (show: boolean, first: number) =>
148
+ show
149
+ ? [
150
+ lineNumbersGutter(first === 1 ? {} : { formatNumber: (n) => String(n + first - 1) }),
151
+ highlightActiveLineGutter(),
152
+ foldGutter()
153
+ ]
154
+ : [];
116
155
 
117
156
  // Derive effective dark mode from prop or app theme
118
157
  let isDark = $derived(theme === 'auto' ? themeState.isDarkMode : theme === 'dark');
119
158
 
120
- const getLanguageExtension = (lang: string) => {
121
- switch (lang) {
122
- case 'javascript':
123
- case 'typescript':
124
- return javascript();
125
- case 'html':
126
- return html();
127
- case 'css':
128
- return css();
129
- case 'json':
130
- return json();
131
- case 'markdown':
132
- return markdown();
133
- default:
134
- return javascript();
135
- }
136
- };
159
+ const getThemeExtension = () => (theme === 'auto' ? libraryTheme(isDark) : isDark ? oneDark : []);
160
+
161
+ const getLanguageExtension = (lang: string) => resolveCodeLanguage(lang)?.load() ?? [];
162
+
163
+ const markedLine = Decoration.line({ class: 'cm-marked-line' });
164
+
165
+ function getMarksExtension(lines: number[], first: number): Extension {
166
+ if (lines.length === 0) return [];
167
+ const sorted = [...new Set(lines)].sort((a, b) => a - b);
168
+ // A function, so the marks follow the document as it changes.
169
+ return EditorView.decorations.of((editor) => {
170
+ const doc = editor.state.doc;
171
+ const builder = new RangeSetBuilder<Decoration>();
172
+ for (const shown of sorted) {
173
+ const n = shown - first + 1;
174
+ if (n >= 1 && n <= doc.lines) builder.add(doc.line(n).from, doc.line(n).from, markedLine);
175
+ }
176
+ return builder.finish();
177
+ });
178
+ }
179
+
180
+ const getAttributesExtension = (text: string, label: string): Extension => [
181
+ text ? placeholderText(text) : [],
182
+ label ? EditorView.contentAttributes.of({ 'aria-label': label }) : []
183
+ ];
184
+
185
+ function onScroll() {
186
+ if (!view) return;
187
+ const scroller = view.scrollDOM;
188
+ pinned = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 4;
189
+ }
137
190
 
138
191
  onMount(() => {
139
192
  if (!editorContainer) return;
140
193
 
141
- const extensions = [
142
- gutterCompartment.of(getGutterExtension(lineNumbers)),
194
+ const setup = [
195
+ gutterCompartment.of(getGutterExtension(lineNumbers, firstLineNumber)),
143
196
  baseSetup,
144
- getLanguageExtension(language),
145
- EditorView.lineWrapping,
146
- themeCompartment.of(isDark ? oneDark : [])
147
- ];
148
-
149
- if (readOnly) {
150
- extensions.push(EditorState.readOnly.of(true));
151
- }
152
-
153
- // Always add update listener to sync bindable value
154
- extensions.push(
197
+ languageCompartment.of(getLanguageExtension(language)),
198
+ wrapCompartment.of(wrap ? EditorView.lineWrapping : []),
199
+ themeCompartment.of(getThemeExtension()),
200
+ readOnlyCompartment.of(EditorState.readOnly.of(readOnly)),
201
+ marksCompartment.of(getMarksExtension(markedLines, firstLineNumber)),
202
+ attributesCompartment.of(getAttributesExtension(placeholder, ariaLabel)),
203
+ // Always add update listener to sync bindable value
155
204
  EditorView.updateListener.of((update) => {
156
205
  if (update.docChanged) {
157
206
  const newValue = update.state.doc.toString();
@@ -160,21 +209,25 @@
160
209
  onChange(newValue);
161
210
  }
162
211
  }
163
- })
164
- );
212
+ }),
213
+ userCompartment.of(extensions)
214
+ ];
165
215
 
166
216
  const startState = EditorState.create({
167
217
  doc: value,
168
- extensions
218
+ extensions: setup
169
219
  });
170
220
 
171
221
  view = new EditorView({
172
222
  state: startState,
173
223
  parent: editorContainer
174
224
  });
225
+ view.scrollDOM.addEventListener('scroll', onScroll, { passive: true });
226
+ if (follow) scrollToEnd();
175
227
  });
176
228
 
177
229
  onDestroy(() => {
230
+ view?.scrollDOM.removeEventListener('scroll', onScroll);
178
231
  view?.destroy();
179
232
  clearTimeout(copiedTimeout);
180
233
  });
@@ -198,7 +251,16 @@
198
251
  if (!view) return;
199
252
 
200
253
  view.dispatch({
201
- effects: themeCompartment.reconfigure(isDark ? oneDark : [])
254
+ effects: themeCompartment.reconfigure(getThemeExtension())
255
+ });
256
+ });
257
+
258
+ // Watch for language changes and swap the language support
259
+ $effect(() => {
260
+ if (!view) return;
261
+
262
+ view.dispatch({
263
+ effects: languageCompartment.reconfigure(getLanguageExtension(language))
202
264
  });
203
265
  });
204
266
 
@@ -207,20 +269,54 @@
207
269
  if (!view) return;
208
270
 
209
271
  view.dispatch({
210
- effects: gutterCompartment.reconfigure(getGutterExtension(lineNumbers))
272
+ effects: gutterCompartment.reconfigure(getGutterExtension(lineNumbers, firstLineNumber))
211
273
  });
212
274
  });
213
275
 
276
+ $effect(() => {
277
+ if (!view) return;
278
+
279
+ view.dispatch({
280
+ effects: [
281
+ readOnlyCompartment.reconfigure(EditorState.readOnly.of(readOnly)),
282
+ wrapCompartment.reconfigure(wrap ? EditorView.lineWrapping : []),
283
+ attributesCompartment.reconfigure(getAttributesExtension(placeholder, ariaLabel))
284
+ ]
285
+ });
286
+ });
287
+
288
+ $effect(() => {
289
+ if (!view) return;
290
+
291
+ view.dispatch({
292
+ effects: marksCompartment.reconfigure(getMarksExtension(markedLines, firstLineNumber))
293
+ });
294
+ });
295
+
296
+ $effect(() => {
297
+ if (!view) return;
298
+
299
+ view.dispatch({ effects: userCompartment.reconfigure(extensions) });
300
+ });
301
+
214
302
  // Watch for external value changes and update editor
215
303
  $effect(() => {
216
304
  if (!view) return;
217
305
 
306
+ // The document stores line breaks as \n, so a value with \r\n compares in that form.
307
+ const next = value.replace(/\r\n?/g, '\n');
218
308
  const currentValue = view.state.doc.toString();
219
- if (value !== currentValue) {
220
- view.dispatch({
221
- changes: { from: 0, to: currentValue.length, insert: value }
222
- });
223
- }
309
+ if (next === currentValue) return;
310
+
311
+ const keepAtEnd = untrack(() => follow && pinned);
312
+ view.dispatch({
313
+ changes: next.startsWith(currentValue)
314
+ ? { from: currentValue.length, insert: next.slice(currentValue.length) }
315
+ : { from: 0, to: currentValue.length, insert: next }
316
+ });
317
+ // A transaction of its own: CodeMirror clips a scroll target to the document as it was
318
+ // before the transaction's changes, which would leave the view at the old end.
319
+ if (keepAtEnd) scrollToEnd();
224
320
  });
225
321
 
226
322
  // Public API methods
@@ -242,11 +338,29 @@
242
338
  export function focus() {
243
339
  view?.focus();
244
340
  }
341
+
342
+ /** Scrolls the line with this number (as shown) to the middle of the view. */
343
+ export function scrollToLine(lineNumber: number) {
344
+ if (!view) return;
345
+ const n = Math.min(Math.max(lineNumber - firstLineNumber + 1, 1), view.state.doc.lines);
346
+ view.dispatch({
347
+ effects: EditorView.scrollIntoView(view.state.doc.line(n).from, { y: 'center' })
348
+ });
349
+ }
350
+
351
+ /** Scrolls to the last line, where `follow` keeps the view. */
352
+ export function scrollToEnd() {
353
+ if (!view) return;
354
+ view.dispatch({
355
+ effects: EditorView.scrollIntoView(view.state.doc.length, { y: 'end' })
356
+ });
357
+ pinned = true;
358
+ }
245
359
  </script>
246
360
 
247
361
  <div class="codemirror-container {className}" style="height: {height}">
248
362
  {#if copyButton}
249
- <div class="codemirror-copy" class:copied class:dark={isDark}>
363
+ <div class="codemirror-action codemirror-copy" class:copied class:dark={isDark}>
250
364
  <ActionIcon
251
365
  svg={copied ? iconCheck : iconCopy}
252
366
  size="1rem"
@@ -257,6 +371,17 @@
257
371
  </div>
258
372
  {/if}
259
373
  <div class="codemirror-wrapper" bind:this={editorContainer}></div>
374
+ {#if follow && !pinned}
375
+ <div class="codemirror-action codemirror-end">
376
+ <ActionIcon
377
+ svg={iconArrowDown}
378
+ size="1rem"
379
+ tooltip="Jump to the last line"
380
+ ariaLabel="Jump to the last line"
381
+ onclick={scrollToEnd}
382
+ />
383
+ </div>
384
+ {/if}
260
385
  </div>
261
386
 
262
387
  <style>
@@ -271,17 +396,24 @@
271
396
 
272
397
  /* The ActionIcon supplies the button chrome; this only places it and gives it
273
398
  an opaque backing so it stays readable over the code underneath. */
274
- .codemirror-copy {
399
+ .codemirror-action {
275
400
  position: absolute;
276
- top: 0.375rem;
277
401
  right: 0.375rem;
278
402
  z-index: 2;
279
403
  display: inline-flex;
280
404
  border-radius: var(--ui-radius-sm);
405
+ }
406
+
407
+ .codemirror-copy {
408
+ top: 0.375rem;
281
409
  opacity: 0.65;
282
410
  transition: opacity 0.15s ease;
283
411
  }
284
412
 
413
+ .codemirror-end {
414
+ bottom: 0.375rem;
415
+ }
416
+
285
417
  .codemirror-container:hover .codemirror-copy,
286
418
  .codemirror-copy:hover,
287
419
  .codemirror-copy:focus-within,
@@ -301,4 +433,37 @@
301
433
  .codemirror-wrapper :global(.cm-scroller) {
302
434
  overflow: auto;
303
435
  }
436
+
437
+ /* Syntax colours for theme="auto", overridable per app. Not brand colours: each mode's set
438
+ is picked to read on that mode's input background. */
439
+ .codemirror-container {
440
+ --cm-keyword: #be123c;
441
+ --cm-string: #15803d;
442
+ --cm-number: #b45309;
443
+ --cm-comment: var(--text-muted);
444
+ --cm-function: #1d4ed8;
445
+ --cm-type: #7c3aed;
446
+ --cm-variable: #0e7490;
447
+ --cm-property: #0e7490;
448
+ --cm-tag: #be123c;
449
+ --cm-operator: #495057;
450
+ --cm-invalid: #c92a2a;
451
+ }
452
+
453
+ :global(.dark) .codemirror-container {
454
+ --cm-keyword: #ff8fa3;
455
+ --cm-string: #8ce99a;
456
+ --cm-number: #ffc078;
457
+ --cm-function: #74c0fc;
458
+ --cm-type: #d0bfff;
459
+ --cm-variable: #66d9e8;
460
+ --cm-property: #66d9e8;
461
+ --cm-tag: #ff8fa3;
462
+ --cm-operator: #ced4da;
463
+ --cm-invalid: #ff8787;
464
+ }
465
+
466
+ .codemirror-wrapper :global(.cm-marked-line) {
467
+ background-color: var(--cm-marked-line-bg, rgba(var(--ui-tertiary-rgbc), 0.25));
468
+ }
304
469
  </style>
@@ -1,15 +1,36 @@
1
1
  import { EditorView } from '@codemirror/view';
2
+ import { type Extension } from '@codemirror/state';
3
+ import { type CodeLanguageId } from './codemirror/languages.js';
2
4
  export interface CodeMirrorProps {
3
- /** Editor content value (bindable) */
5
+ /** Editor content value (bindable). A new value that extends the current one is
6
+ * appended, so a growing log keeps its selection and scroll position. */
4
7
  value?: string;
5
- /** Programming language for syntax highlighting */
6
- language?: 'javascript' | 'html' | 'css' | 'json' | 'typescript' | 'markdown';
7
- /** Color theme for the editor (defaults to app theme) */
8
+ /** Language for syntax highlighting: an id from `codeLanguages` or one of its aliases
9
+ * ('ps1', 'py', 'yml', ...). Anything unrecognised shows as plain text. */
10
+ language?: CodeLanguageId | (string & {});
11
+ /** Color theme. 'auto' (the default) follows the app's mode with the library's own
12
+ * colours; 'light' and 'dark' force CodeMirror's default style and One Dark. */
8
13
  theme?: 'light' | 'dark' | 'auto';
9
14
  /** Disable editing */
10
15
  readOnly?: boolean;
11
16
  /** Show line numbers in the gutter */
12
17
  lineNumbers?: boolean;
18
+ /** Number shown for the first line, when the value is a window into a longer file */
19
+ firstLineNumber?: number;
20
+ /** Wrap long lines instead of scrolling sideways */
21
+ wrap?: boolean;
22
+ /** Keep the last line in view as the value grows, until the user scrolls up; a button
23
+ * then jumps back to the end */
24
+ follow?: boolean;
25
+ /** Line numbers (as shown, so counted from `firstLineNumber`) to highlight, such as
26
+ * search matches */
27
+ markedLines?: number[];
28
+ /** Text shown while the editor is empty */
29
+ placeholder?: string;
30
+ /** Accessible name for the editor */
31
+ ariaLabel?: string;
32
+ /** Extra CodeMirror extensions, added after the built-in ones; changes apply live */
33
+ extensions?: Extension[];
13
34
  /** Show a button that copies the editor contents to the clipboard */
14
35
  copyButton?: boolean;
15
36
  /** Additional CSS classes */
@@ -26,6 +47,8 @@ declare const CodeMirror: import("svelte").Component<CodeMirrorProps, {
26
47
  setValue: (newValue: string) => void;
27
48
  getView: () => EditorView | null;
28
49
  focus: () => void;
50
+ scrollToLine: (lineNumber: number) => void;
51
+ scrollToEnd: () => void;
29
52
  }, "value">;
30
53
  type CodeMirror = ReturnType<typeof CodeMirror>;
31
54
  export default CodeMirror;
@@ -0,0 +1,17 @@
1
+ import type { Extension } from '@codemirror/state';
2
+ /** Language identifiers shared by the CodeMirror editor and rich code blocks */
3
+ export type CodeLanguageId = 'plaintext' | 'javascript' | 'typescript' | 'html' | 'css' | 'json' | 'markdown' | 'sql' | 'csharp' | 'powershell' | 'python' | 'shell' | 'yaml' | 'xml' | 'toml' | 'ini' | 'dockerfile' | 'diff' | 'log';
4
+ export interface CodeLanguageDef {
5
+ /** Value stored in a code block's language attribute and `language-` CSS class */
6
+ id: CodeLanguageId;
7
+ /** Human-readable name shown in the language picker */
8
+ label: string;
9
+ /** Alternative names recognised when parsing existing content (e.g. 'cs' for csharp) */
10
+ aliases: string[];
11
+ /** Factory for the CodeMirror language support (highlighting + completions) */
12
+ load: () => Extension;
13
+ }
14
+ /** Every language the CodeMirror editor and rich code blocks can highlight */
15
+ export declare const codeLanguages: CodeLanguageDef[];
16
+ /** Look up a language definition by id or alias (case-insensitive) */
17
+ export declare function resolveCodeLanguage(language: string | null | undefined): CodeLanguageDef | undefined;