@samline/string 0.0.0-stage → 1.5.0

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.
@@ -0,0 +1,716 @@
1
+ import { isConversion, CHAR_MAPS, convert, contains, hashColor, highlight, wordCount, graphemes, template, truncate } from '../chunk-3EFE2B7D.js';
2
+ export { CHAR_MAPS, CONVERSIONS, CYRILLIC, GERMAN, GREEK, camelCase, capitalize, closest, compareNatural, constantCase, contains, convert, distance, dotCase, escapeHtml, fold, graphemes, hashColor, highlight, initials, isConversion, kebabCase, pascalCase, pathCase, pluralize, readingTime, removeAccents, sentenceCase, similarity, slugify, snakeCase, stripTags, template, titleCase, trainCase, truncate, uncapitalize, unescapeHtml, uniqueSlug, wordCount, words } from '../chunk-3EFE2B7D.js';
3
+
4
+ // node_modules/.pnpm/@samline+internal@1.0.0/node_modules/@samline/internal/dist/index.js
5
+ var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
6
+ var noop = () => {
7
+ };
8
+ var isElement = (value) => typeof Element !== "undefined" && value instanceof Element;
9
+ var resolveElements = (target, root = isBrowser() ? document : null) => {
10
+ if (target == null) return [];
11
+ if (isElement(target)) return [target];
12
+ if (typeof target === "string") {
13
+ if (!root) return [];
14
+ return Array.from(root.querySelectorAll(target));
15
+ }
16
+ const source = typeof target[Symbol.iterator] === "function" ? Array.from(target) : Array.from(target);
17
+ return Array.from(new Set(source.filter(isElement)));
18
+ };
19
+ var read = (el, name) => el.hasAttribute(name) ? el.getAttribute(name) : null;
20
+ var readString = (el, name, fallback) => {
21
+ const raw = read(el, name);
22
+ return raw === null || raw.trim() === "" ? fallback : raw.trim();
23
+ };
24
+ var readBoolean = (el, name, fallback) => {
25
+ const raw = read(el, name);
26
+ if (raw === null) return fallback;
27
+ const value = raw.trim().toLowerCase();
28
+ if (value === "" || value === "true" || value === name.toLowerCase()) return true;
29
+ if (value === "false") return false;
30
+ return fallback;
31
+ };
32
+ var readNumber = (el, name, fallback) => {
33
+ const raw = read(el, name);
34
+ if (raw === null || raw.trim() === "") return fallback;
35
+ const value = Number(raw);
36
+ return Number.isFinite(value) ? value : fallback;
37
+ };
38
+ var readEnum = (el, name, allowed, fallback) => {
39
+ const raw = read(el, name)?.trim();
40
+ return raw !== void 0 && allowed.includes(raw) ? raw : fallback;
41
+ };
42
+ var autoInit = ({
43
+ selector,
44
+ init,
45
+ root,
46
+ observe = true
47
+ }) => {
48
+ if (!isBrowser()) return { refresh: noop, destroy: noop };
49
+ const scope = root ?? document;
50
+ const cleanups = /* @__PURE__ */ new Map();
51
+ const initOne = (element) => {
52
+ if (cleanups.has(element)) return;
53
+ cleanups.set(element, init(element) ?? noop);
54
+ };
55
+ const destroyOne = (element) => {
56
+ const cleanup = cleanups.get(element);
57
+ if (!cleanup) return;
58
+ cleanups.delete(element);
59
+ cleanup();
60
+ };
61
+ const forEachMatch = (node, callback) => {
62
+ if (!(node instanceof Element)) return;
63
+ if (node.matches(selector)) callback(node);
64
+ node.querySelectorAll(selector).forEach(callback);
65
+ };
66
+ const refresh = () => scope.querySelectorAll(selector).forEach(initOne);
67
+ let observer = null;
68
+ if (observe && typeof MutationObserver === "function") {
69
+ observer = new MutationObserver((mutations) => {
70
+ for (const mutation of mutations) {
71
+ mutation.removedNodes.forEach(
72
+ (node) => forEachMatch(node, (element) => {
73
+ if (!element.isConnected) destroyOne(element);
74
+ })
75
+ );
76
+ mutation.addedNodes.forEach((node) => forEachMatch(node, initOne));
77
+ }
78
+ });
79
+ const target = scope instanceof Document ? scope.documentElement : scope;
80
+ observer.observe(target, { childList: true, subtree: true });
81
+ }
82
+ refresh();
83
+ return {
84
+ refresh,
85
+ destroy: () => {
86
+ observer?.disconnect();
87
+ observer = null;
88
+ Array.from(cleanups.keys()).forEach(destroyOne);
89
+ }
90
+ };
91
+ };
92
+
93
+ // src/vanilla/string.ts
94
+ var ATTRIBUTE = "data-string";
95
+ var STATE_ATTRIBUTE = "data-string-state";
96
+ var CHANGE_EVENT = "string:change";
97
+ var COLOR_PROPERTY = "--string-color";
98
+ var POSITIONS = ["end", "middle", "start"];
99
+ var TYPING_SEPARATOR = {
100
+ kebab: "-",
101
+ snake: "_",
102
+ dot: ".",
103
+ path: "/",
104
+ constant: "_",
105
+ train: "-",
106
+ camel: " ",
107
+ pascal: " "
108
+ };
109
+ var isField = (element) => element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement;
110
+ var textOf = (element) => isField(element) ? element.value : element.textContent ?? "";
111
+ var parseReplacements = (raw) => {
112
+ try {
113
+ const value = JSON.parse(raw);
114
+ if (value && typeof value === "object" && !Array.isArray(value)) {
115
+ return Object.fromEntries(
116
+ Object.entries(value).filter(
117
+ (entry) => typeof entry[1] === "string"
118
+ )
119
+ );
120
+ }
121
+ } catch {
122
+ }
123
+ return void 0;
124
+ };
125
+ var readConfig = (element, options) => {
126
+ const raw = element.getAttribute(ATTRIBUTE)?.trim();
127
+ const to = isConversion(raw) ? raw : options.to;
128
+ if (!to) return null;
129
+ const { to: _to, source: sourceOption, live, onChange: _onChange, color, ...base } = options;
130
+ const converted = { ...base };
131
+ const attr = (name) => `${ATTRIBUTE}-${name}`;
132
+ const has = (name) => element.hasAttribute(attr(name));
133
+ const locale = readString(element, attr("locale"), "") || base.locale || element.closest("[lang]")?.getAttribute("lang") || "";
134
+ if (locale) converted.locale = locale;
135
+ else delete converted.locale;
136
+ if (has("separator")) converted.separator = element.getAttribute(attr("separator")) ?? "";
137
+ if (has("lower")) converted.lower = readBoolean(element, attr("lower"), base.lower ?? true);
138
+ if (has("max-length")) {
139
+ const maxLength = readNumber(element, attr("max-length"), NaN);
140
+ if (Number.isFinite(maxLength)) converted.maxLength = maxLength;
141
+ }
142
+ if (has("replacements")) {
143
+ const replacements = parseReplacements(element.getAttribute(attr("replacements")) ?? "");
144
+ if (replacements) converted.replacements = replacements;
145
+ }
146
+ if (has("preserve")) converted.preserve = element.getAttribute(attr("preserve")) ?? "";
147
+ if (has("transliterate")) {
148
+ const names = readString(element, attr("transliterate"), "").split(/[\s,]+/);
149
+ const maps = names.filter((name) => name in CHAR_MAPS).map((name) => CHAR_MAPS[name]);
150
+ if (maps.length) converted.charMap = Object.assign({}, base.charMap, ...maps);
151
+ }
152
+ if (has("taken")) {
153
+ const raw2 = element.getAttribute(attr("taken")) ?? "";
154
+ let taken;
155
+ try {
156
+ taken = JSON.parse(raw2);
157
+ } catch {
158
+ taken = raw2.split(/[\s,]+/);
159
+ }
160
+ if (Array.isArray(taken)) {
161
+ converted.taken = taken.filter(
162
+ (slug) => typeof slug === "string" && slug !== ""
163
+ );
164
+ }
165
+ }
166
+ if (has("small-words")) {
167
+ converted.smallWords = readString(element, attr("small-words"), "").split(/[\s,]+/).filter(Boolean);
168
+ }
169
+ if (has("length")) {
170
+ const length = readNumber(element, attr("length"), NaN);
171
+ if (Number.isFinite(length)) converted.length = length;
172
+ }
173
+ if (has("ellipsis")) converted.ellipsis = element.getAttribute(attr("ellipsis")) ?? "";
174
+ if (has("position"))
175
+ converted.position = readEnum(element, attr("position"), POSITIONS, base.position ?? "end");
176
+ if (has("word-boundary"))
177
+ converted.wordBoundary = readBoolean(element, attr("word-boundary"), true);
178
+ if (has("max")) {
179
+ const max = readNumber(element, attr("max"), NaN);
180
+ if (Number.isFinite(max)) converted.max = max;
181
+ }
182
+ const sourceSelector = readString(element, attr("source"), "");
183
+ const source = resolveElements(sourceSelector || sourceOption)[0] ?? null;
184
+ return {
185
+ to,
186
+ options: converted,
187
+ source: source === element ? null : source,
188
+ live: readBoolean(element, attr("live"), live ?? true),
189
+ color: readBoolean(element, attr("color"), Boolean(color)) ? typeof color === "object" ? color : {} : null
190
+ };
191
+ };
192
+ var convertWhileTyping = (value, { to, options }) => {
193
+ if (to === "slug") {
194
+ const { taken: _taken, ...typing } = options;
195
+ return convert(value, to, { ...typing, trim: false });
196
+ }
197
+ const separator = TYPING_SEPARATOR[to];
198
+ const result = convert(value, to, options);
199
+ return separator !== void 0 && result && /[^\p{L}\p{N}]$/u.test(value) ? result + separator : result;
200
+ };
201
+ var bind = (element, options) => {
202
+ let config = readConfig(element, options);
203
+ if (!config) return null;
204
+ const field = isField(element) ? element : null;
205
+ const originalNodes = Array.from(element.childNodes);
206
+ const originalText = textOf(element);
207
+ let detachSource = noop;
208
+ let state = "ready";
209
+ let composing = false;
210
+ const setState = (next) => {
211
+ state = next;
212
+ element.setAttribute(STATE_ATTRIBUTE, next);
213
+ };
214
+ const notify = (value) => {
215
+ options.onChange?.(value, element);
216
+ element.dispatchEvent(
217
+ new CustomEvent(CHANGE_EVENT, { bubbles: true, detail: { value, state } })
218
+ );
219
+ };
220
+ const authored = /* @__PURE__ */ new Map();
221
+ const describe = (name, value) => {
222
+ if (!authored.has(name)) authored.set(name, element.getAttribute(name));
223
+ if (authored.get(name) !== null) return;
224
+ if (value === null) element.removeAttribute(name);
225
+ else element.setAttribute(name, value);
226
+ };
227
+ const setFieldValue = (value) => {
228
+ if (!field || field.value === value) return;
229
+ const focused = field.ownerDocument.activeElement === field;
230
+ let fromEnd = 0;
231
+ try {
232
+ fromEnd = field.value.length - (field.selectionEnd ?? field.value.length);
233
+ } catch {
234
+ }
235
+ field.value = value;
236
+ if (focused) {
237
+ const caret = Math.max(0, value.length - fromEnd);
238
+ try {
239
+ field.setSelectionRange(caret, caret);
240
+ } catch {
241
+ }
242
+ }
243
+ notify(value);
244
+ };
245
+ const render = (text) => {
246
+ const current = config;
247
+ const output = convert(text, current.to, current.options);
248
+ if (field) return setFieldValue(output);
249
+ if (element.textContent !== output) {
250
+ element.textContent = output;
251
+ notify(output);
252
+ }
253
+ describe("title", current.to === "truncate" && output !== text ? text : null);
254
+ const label = current.to === "initials" ? text.trim() : "";
255
+ describe("role", label ? "img" : null);
256
+ describe("aria-label", label || null);
257
+ if (current.color) element.style.setProperty(COLOR_PROPERTY, hashColor(text, current.color));
258
+ else element.style.removeProperty(COLOR_PROPERTY);
259
+ };
260
+ const fromSource = () => config.source && render(textOf(config.source));
261
+ const onSourceInput = () => {
262
+ if (!field || state === "following") fromSource();
263
+ };
264
+ const onFieldInput = () => {
265
+ if (!field || composing) return;
266
+ if (config.source) {
267
+ if (field.value === "") return setState("following");
268
+ if (state !== "edited") setState("edited");
269
+ }
270
+ if (config.live && config.to !== "truncate" && config.to !== "initials") {
271
+ setFieldValue(convertWhileTyping(field.value, config));
272
+ }
273
+ };
274
+ const onFieldBlur = () => {
275
+ if (!field) return;
276
+ if (config.source && state === "following") return fromSource();
277
+ render(field.value);
278
+ };
279
+ const onCompositionStart = () => composing = true;
280
+ const onCompositionEnd = () => {
281
+ composing = false;
282
+ onFieldInput();
283
+ };
284
+ const attachSource = () => {
285
+ detachSource();
286
+ const source = config.source;
287
+ if (!source) return detachSource = noop;
288
+ source.addEventListener("input", onSourceInput);
289
+ source.addEventListener(CHANGE_EVENT, onSourceInput);
290
+ detachSource = () => {
291
+ source.removeEventListener("input", onSourceInput);
292
+ source.removeEventListener(CHANGE_EVENT, onSourceInput);
293
+ };
294
+ };
295
+ const start = () => {
296
+ const current = config;
297
+ attachSource();
298
+ if (field && current.source) {
299
+ const expected = convert(textOf(current.source), current.to, current.options);
300
+ setState(field.value === "" || field.value === expected ? "following" : "edited");
301
+ if (state === "following") fromSource();
302
+ else render(field.value);
303
+ } else {
304
+ setState("ready");
305
+ if (current.source) fromSource();
306
+ else render(field ? field.value : originalText);
307
+ }
308
+ };
309
+ if (field) {
310
+ field.addEventListener("input", onFieldInput);
311
+ field.addEventListener("blur", onFieldBlur);
312
+ field.addEventListener("compositionstart", onCompositionStart);
313
+ field.addEventListener("compositionend", onCompositionEnd);
314
+ }
315
+ start();
316
+ let active = true;
317
+ return {
318
+ refresh: () => {
319
+ if (!active) return;
320
+ const next = readConfig(element, options);
321
+ if (!next) return;
322
+ config = next;
323
+ if (field && config.source && state !== "ready") {
324
+ attachSource();
325
+ return state === "following" ? fromSource() : render(field.value);
326
+ }
327
+ start();
328
+ },
329
+ destroy: () => {
330
+ if (!active) return;
331
+ active = false;
332
+ detachSource();
333
+ if (field) {
334
+ field.removeEventListener("input", onFieldInput);
335
+ field.removeEventListener("blur", onFieldBlur);
336
+ field.removeEventListener("compositionstart", onCompositionStart);
337
+ field.removeEventListener("compositionend", onCompositionEnd);
338
+ } else {
339
+ element.replaceChildren(...originalNodes);
340
+ }
341
+ authored.forEach((before, name) => before === null && element.removeAttribute(name));
342
+ element.style.removeProperty(COLOR_PROPERTY);
343
+ if (element.getAttribute("style") === "") element.removeAttribute("style");
344
+ element.removeAttribute(STATE_ATTRIBUTE);
345
+ }
346
+ };
347
+ };
348
+ var string = (target = `[${ATTRIBUTE}]`, options = {}) => {
349
+ if (!isBrowser()) return { refresh: noop, destroy: noop };
350
+ const controllers = resolveElements(target).filter((element) => element instanceof HTMLElement).map((element) => bind(element, options)).filter((controller) => controller !== null);
351
+ return {
352
+ refresh: () => controllers.forEach((controller) => controller.refresh()),
353
+ destroy: () => controllers.forEach((controller) => controller.destroy())
354
+ };
355
+ };
356
+ var autoString = ({
357
+ selector = `[${ATTRIBUTE}]`,
358
+ scope,
359
+ observe = true,
360
+ ...options
361
+ } = {}) => autoInit({
362
+ selector,
363
+ observe,
364
+ ...scope && { root: scope },
365
+ init: (element) => {
366
+ const controller = string(element, options);
367
+ return controller.destroy;
368
+ }
369
+ });
370
+
371
+ // src/vanilla/search.ts
372
+ var SEARCH_ATTRIBUTE = "data-string-search";
373
+ var SEARCH_STATE_ATTRIBUTE = "data-string-search-state";
374
+ var SEARCH_EMPTY_ATTRIBUTE = "data-string-search-empty";
375
+ var SEARCH_EVENT = "string:search";
376
+ var textNodes = (root) => {
377
+ const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);
378
+ const nodes = [];
379
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) nodes.push(node);
380
+ return nodes;
381
+ };
382
+ var bindSearch = (list, options) => {
383
+ const attr = (name) => `${SEARCH_ATTRIBUTE}-${name}`;
384
+ const selector = readString(list, SEARCH_ATTRIBUTE, "");
385
+ const input = resolveElements(selector || options.input)[0];
386
+ if (!(input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement)) return null;
387
+ const doc = list.ownerDocument;
388
+ const authoredHidden = /* @__PURE__ */ new Map();
389
+ let marks = [];
390
+ let items = [];
391
+ let empty = null;
392
+ const settings = () => {
393
+ const locale = readString(list, attr("locale"), "") || options.locale || list.closest("[lang]")?.getAttribute("lang") || "";
394
+ const match = {
395
+ split: readBoolean(list, attr("split"), options.split ?? true),
396
+ ...locale && { locale }
397
+ };
398
+ return {
399
+ match,
400
+ mark: readBoolean(list, attr("highlight"), options.highlight ?? true),
401
+ min: Math.max(1, readNumber(list, attr("min"), options.min ?? 1)),
402
+ items: readString(list, attr("items"), options.items ?? "")
403
+ };
404
+ };
405
+ const remember = (element) => {
406
+ if (!authoredHidden.has(element)) authoredHidden.set(element, element.hidden);
407
+ };
408
+ const collect = () => {
409
+ const { items: itemSelector } = settings();
410
+ const found = itemSelector ? Array.from(list.querySelectorAll(itemSelector)) : Array.from(list.children);
411
+ const emptyOption = resolveElements(options.empty)[0];
412
+ empty = list.querySelector(`[${SEARCH_EMPTY_ATTRIBUTE}]`) ?? (emptyOption instanceof HTMLElement ? emptyOption : null);
413
+ items = found.filter(
414
+ (item) => item instanceof HTMLElement && item !== empty && !item.contains(empty)
415
+ );
416
+ items.forEach(remember);
417
+ if (empty) remember(empty);
418
+ items = items.filter((item) => !authoredHidden.get(item));
419
+ };
420
+ const clearMarks = () => {
421
+ for (const { original, nodes } of marks) {
422
+ const first = nodes[0];
423
+ if (first?.parentNode) first.parentNode.insertBefore(original, first);
424
+ nodes.forEach((node) => node.parentNode?.removeChild(node));
425
+ }
426
+ marks = [];
427
+ };
428
+ const markItem = (item, query, match) => {
429
+ for (const node of textNodes(item)) {
430
+ const segments = highlight(node.data, query, match);
431
+ if (!segments.some((segment) => segment.match)) continue;
432
+ const nodes = segments.map((segment) => {
433
+ if (!segment.match) return doc.createTextNode(segment.text);
434
+ const mark = doc.createElement("mark");
435
+ mark.textContent = segment.text;
436
+ return mark;
437
+ });
438
+ const parent = node.parentNode;
439
+ nodes.forEach((created) => parent.insertBefore(created, node));
440
+ parent.removeChild(node);
441
+ marks.push({ original: node, nodes });
442
+ }
443
+ };
444
+ const search2 = () => {
445
+ const { match, mark, min } = settings();
446
+ const query = input.value;
447
+ clearMarks();
448
+ const active = Array.from(query.trim()).length >= min;
449
+ const matches = items.filter((item) => {
450
+ const visible = !active || contains(item.textContent ?? "", query, match);
451
+ item.hidden = visible ? authoredHidden.get(item) : true;
452
+ if (visible && active && mark) markItem(item, query, match);
453
+ return visible && active;
454
+ });
455
+ const state = !active ? "idle" : matches.length > 0 ? "results" : "empty";
456
+ list.setAttribute(SEARCH_STATE_ATTRIBUTE, state);
457
+ if (empty) empty.hidden = state !== "empty";
458
+ const result = {
459
+ query,
460
+ matches: active ? matches : [...items],
461
+ total: items.length,
462
+ state
463
+ };
464
+ options.onSearch?.(result, list);
465
+ list.dispatchEvent(new CustomEvent(SEARCH_EVENT, { bubbles: true, detail: result }));
466
+ };
467
+ input.addEventListener("input", search2);
468
+ collect();
469
+ search2();
470
+ let alive = true;
471
+ return {
472
+ refresh: () => {
473
+ if (!alive) return;
474
+ clearMarks();
475
+ collect();
476
+ search2();
477
+ },
478
+ destroy: () => {
479
+ if (!alive) return;
480
+ alive = false;
481
+ input.removeEventListener("input", search2);
482
+ clearMarks();
483
+ authoredHidden.forEach((hidden, element) => element.hidden = hidden);
484
+ list.removeAttribute(SEARCH_STATE_ATTRIBUTE);
485
+ }
486
+ };
487
+ };
488
+ var search = (target = `[${SEARCH_ATTRIBUTE}]`, options = {}) => {
489
+ if (!isBrowser()) return { refresh: noop, destroy: noop };
490
+ const controllers = resolveElements(target).filter((element) => element instanceof HTMLElement).map((element) => bindSearch(element, options)).filter((controller) => controller !== null);
491
+ return {
492
+ refresh: () => controllers.forEach((controller) => controller.refresh()),
493
+ destroy: () => controllers.forEach((controller) => controller.destroy())
494
+ };
495
+ };
496
+ var autoSearch = ({
497
+ selector = `[${SEARCH_ATTRIBUTE}]`,
498
+ scope,
499
+ observe = true,
500
+ ...options
501
+ } = {}) => autoInit({
502
+ selector,
503
+ observe,
504
+ ...scope && { root: scope },
505
+ init: (element) => search(element, options).destroy
506
+ });
507
+
508
+ // src/vanilla/controller.ts
509
+ var bindAll = (selector, bind2) => (target = selector, options = {}) => {
510
+ if (!isBrowser()) return { refresh: noop, destroy: noop };
511
+ const controllers = resolveElements(target).filter((element) => element instanceof HTMLElement).map((element) => bind2(element, options)).filter((controller) => controller !== null);
512
+ return {
513
+ refresh: () => controllers.forEach((controller) => controller.refresh()),
514
+ destroy: () => controllers.forEach((controller) => controller.destroy())
515
+ };
516
+ };
517
+ var autoAll = (selector, run) => ({
518
+ selector: chosen = selector,
519
+ scope,
520
+ observe = true,
521
+ ...options
522
+ } = {}) => autoInit({
523
+ selector: chosen,
524
+ observe,
525
+ ...scope && { root: scope },
526
+ init: (element) => run(element, options).destroy
527
+ });
528
+ var snapshot = (element) => {
529
+ const nodes = Array.from(element.childNodes);
530
+ return () => element.replaceChildren(...nodes);
531
+ };
532
+ var attributes = (element) => {
533
+ const authored = /* @__PURE__ */ new Map();
534
+ return {
535
+ set: (name, value) => {
536
+ if (!authored.has(name)) authored.set(name, element.getAttribute(name));
537
+ if (authored.get(name) !== null) return;
538
+ if (value === null) element.removeAttribute(name);
539
+ else element.setAttribute(name, value);
540
+ },
541
+ restore: () => authored.forEach((before, name) => before === null && element.removeAttribute(name))
542
+ };
543
+ };
544
+ var localeOf = (element, attribute, option) => element.getAttribute(attribute)?.trim() || option || element.closest("[lang]")?.getAttribute("lang") || void 0;
545
+ var textOf2 = (element) => element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement ? element.value : element.textContent ?? "";
546
+
547
+ // src/vanilla/count.ts
548
+ var COUNT_ATTRIBUTE = "data-string-count";
549
+ var COUNT_STATE_ATTRIBUTE = "data-string-count-state";
550
+ var COUNT_EVENT = "string:count";
551
+ var UNITS = ["characters", "words"];
552
+ var bindCount = (output, options) => {
553
+ const attr = (name) => `${COUNT_ATTRIBUTE}-${name}`;
554
+ const field = resolveElements(readString(output, COUNT_ATTRIBUTE, "") || options.field)[0];
555
+ if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) return null;
556
+ const restoreChildren = snapshot(output);
557
+ const update = () => {
558
+ const unit = readEnum(output, attr("unit"), UNITS, options.unit ?? "characters");
559
+ const locale = localeOf(output, attr("locale"), options.locale);
560
+ const count2 = unit === "words" ? wordCount(field.value, locale ? { locale } : {}) : graphemes(field.value).length;
561
+ const fallbackMax = options.max ?? (field.maxLength > 0 ? field.maxLength : NaN);
562
+ const rawMax = readNumber(output, attr("max"), fallbackMax);
563
+ const max = Number.isFinite(rawMax) && rawMax >= 0 ? rawMax : void 0;
564
+ const remaining = max === void 0 ? void 0 : max - count2;
565
+ const near = readNumber(output, attr("near"), options.near ?? Math.ceil((max ?? 0) * 0.1));
566
+ const state = remaining === void 0 ? "ok" : remaining < 0 ? "over" : remaining <= near ? "near" : "ok";
567
+ const info = { count: count2, max, remaining, state };
568
+ const format = output.hasAttribute(attr("format")) ? output.getAttribute(attr("format")) ?? "" : options.format ?? (max === void 0 ? "{count}" : "{remaining}");
569
+ output.textContent = typeof format === "function" ? format(info) : template(format, { count: count2, max, remaining }, { missing: "" });
570
+ output.setAttribute(COUNT_STATE_ATTRIBUTE, state);
571
+ options.onCount?.(info, output);
572
+ output.dispatchEvent(new CustomEvent(COUNT_EVENT, { bubbles: true, detail: info }));
573
+ };
574
+ field.addEventListener("input", update);
575
+ update();
576
+ let alive = true;
577
+ return {
578
+ refresh: () => alive && update(),
579
+ destroy: () => {
580
+ if (!alive) return;
581
+ alive = false;
582
+ field.removeEventListener("input", update);
583
+ restoreChildren();
584
+ output.removeAttribute(COUNT_STATE_ATTRIBUTE);
585
+ }
586
+ };
587
+ };
588
+ var count = bindAll(`[${COUNT_ATTRIBUTE}]`, bindCount);
589
+ var autoCount = autoAll(`[${COUNT_ATTRIBUTE}]`, count);
590
+
591
+ // src/vanilla/fit.ts
592
+ var FIT_ATTRIBUTE = "data-string-fit";
593
+ var FIT_STATE_ATTRIBUTE = "data-string-fit-state";
594
+ var POSITIONS2 = ["end", "middle", "start"];
595
+ var bindFit = (element, options) => {
596
+ const restoreChildren = snapshot(element);
597
+ const managed = attributes(element);
598
+ const text = element.textContent ?? "";
599
+ const styleBefore = element.getAttribute("style");
600
+ let alive = true;
601
+ element.style.whiteSpace = "nowrap";
602
+ element.style.overflow = "hidden";
603
+ const fits = () => element.scrollWidth <= element.clientWidth;
604
+ const fit2 = () => {
605
+ const position = readEnum(element, FIT_ATTRIBUTE, POSITIONS2, options.position ?? "middle");
606
+ const ellipsis = element.hasAttribute(`${FIT_ATTRIBUTE}-ellipsis`) ? element.getAttribute(`${FIT_ATTRIBUTE}-ellipsis`) ?? "" : options.ellipsis ?? "\u2026";
607
+ if (element.textContent !== text) element.textContent = text;
608
+ if (element.clientWidth === 0 || fits()) {
609
+ element.setAttribute(FIT_STATE_ATTRIBUTE, "full");
610
+ managed.set("title", null);
611
+ return;
612
+ }
613
+ let low = 0;
614
+ let high = graphemes(text).length - 1;
615
+ let best = truncate(text, 0, { position, ellipsis, wordBoundary: false });
616
+ while (low <= high) {
617
+ const middle = Math.floor((low + high) / 2);
618
+ const candidate = truncate(text, middle, { position, ellipsis, wordBoundary: false });
619
+ element.textContent = candidate;
620
+ if (fits()) {
621
+ best = candidate;
622
+ low = middle + 1;
623
+ } else high = middle - 1;
624
+ }
625
+ element.textContent = best;
626
+ element.setAttribute(FIT_STATE_ATTRIBUTE, "truncated");
627
+ managed.set("title", text);
628
+ };
629
+ let frame = 0;
630
+ const schedule = () => {
631
+ cancelAnimationFrame(frame);
632
+ frame = requestAnimationFrame(fit2);
633
+ };
634
+ let observer = null;
635
+ if (typeof ResizeObserver === "function") {
636
+ observer = new ResizeObserver(schedule);
637
+ observer.observe(element);
638
+ } else {
639
+ window.addEventListener("resize", schedule);
640
+ }
641
+ void element.ownerDocument.fonts?.ready.then(() => alive && fit2());
642
+ fit2();
643
+ return {
644
+ refresh: () => alive && fit2(),
645
+ destroy: () => {
646
+ if (!alive) return;
647
+ alive = false;
648
+ cancelAnimationFrame(frame);
649
+ observer?.disconnect();
650
+ window.removeEventListener("resize", schedule);
651
+ restoreChildren();
652
+ managed.restore();
653
+ if (styleBefore === null) element.removeAttribute("style");
654
+ else element.setAttribute("style", styleBefore);
655
+ element.removeAttribute(FIT_STATE_ATTRIBUTE);
656
+ }
657
+ };
658
+ };
659
+ var fit = bindAll(`[${FIT_ATTRIBUTE}]`, bindFit);
660
+ var autoFit = autoAll(`[${FIT_ATTRIBUTE}]`, fit);
661
+
662
+ // src/vanilla/copy.ts
663
+ var COPY_ATTRIBUTE = "data-string-copy";
664
+ var COPY_STATE_ATTRIBUTE = "data-string-copy-state";
665
+ var COPY_EVENT = "string:copy";
666
+ var bindCopy = (button, options) => {
667
+ const {
668
+ source: sourceOption,
669
+ as: asOption,
670
+ reset: resetOption,
671
+ onCopy,
672
+ ...convertOptions
673
+ } = options;
674
+ let timer;
675
+ const finish = (detail) => {
676
+ clearTimeout(timer);
677
+ button.setAttribute(COPY_STATE_ATTRIBUTE, detail.ok ? "copied" : "error");
678
+ const reset = readNumber(button, `${COPY_ATTRIBUTE}-reset`, resetOption ?? 2e3);
679
+ timer = setTimeout(() => button.removeAttribute(COPY_STATE_ATTRIBUTE), reset);
680
+ onCopy?.(detail, button);
681
+ button.dispatchEvent(new CustomEvent(COPY_EVENT, { bubbles: true, detail }));
682
+ };
683
+ const onClick = async () => {
684
+ const source = resolveElements(readString(button, COPY_ATTRIBUTE, "") || sourceOption)[0];
685
+ const raw = source ? textOf2(source) : "";
686
+ const name = readString(button, `${COPY_ATTRIBUTE}-as`, "");
687
+ const as = isConversion(name) ? name : asOption;
688
+ const value = as ? convert(raw, as, convertOptions) : raw;
689
+ try {
690
+ if (!source || !navigator.clipboard) throw new Error("No source or clipboard");
691
+ await navigator.clipboard.writeText(value);
692
+ finish({ value, ok: true });
693
+ } catch {
694
+ finish({ value, ok: false });
695
+ }
696
+ };
697
+ button.addEventListener("click", onClick);
698
+ let alive = true;
699
+ return {
700
+ refresh: () => {
701
+ },
702
+ destroy: () => {
703
+ if (!alive) return;
704
+ alive = false;
705
+ clearTimeout(timer);
706
+ button.removeEventListener("click", onClick);
707
+ button.removeAttribute(COPY_STATE_ATTRIBUTE);
708
+ }
709
+ };
710
+ };
711
+ var copy = bindAll(`[${COPY_ATTRIBUTE}]`, bindCopy);
712
+ var autoCopy = autoAll(`[${COPY_ATTRIBUTE}]`, copy);
713
+
714
+ export { ATTRIBUTE, CHANGE_EVENT, COLOR_PROPERTY, COPY_ATTRIBUTE, COPY_EVENT, COPY_STATE_ATTRIBUTE, COUNT_ATTRIBUTE, COUNT_EVENT, COUNT_STATE_ATTRIBUTE, FIT_ATTRIBUTE, FIT_STATE_ATTRIBUTE, SEARCH_ATTRIBUTE, SEARCH_EMPTY_ATTRIBUTE, SEARCH_EVENT, SEARCH_STATE_ATTRIBUTE, STATE_ATTRIBUTE, autoCopy, autoCount, autoFit, autoSearch, autoString, copy, count, fit, search, string };
715
+ //# sourceMappingURL=index.js.map
716
+ //# sourceMappingURL=index.js.map