@akin2unde/flowui-core 0.2.1 → 1.0.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.
package/dist/index.cjs CHANGED
@@ -20,10 +20,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ AsyncLabelStore: () => AsyncLabelStore,
23
24
  clampNumber: () => clampNumber,
25
+ createAsyncLabelStore: () => createAsyncLabelStore,
24
26
  createTheme: () => createTheme,
25
27
  defaultTheme: () => defaultTheme,
26
28
  enabledSelectableDescendants: () => enabledSelectableDescendants,
29
+ exportTableToCsv: () => exportTableToCsv,
27
30
  exportTableToExcel: () => exportTableToExcel,
28
31
  exportTableToPdf: () => exportTableToPdf,
29
32
  filterTree: () => filterTree,
@@ -32,10 +35,12 @@ __export(index_exports, {
32
35
  formatLocalDateTime: () => formatLocalDateTime,
33
36
  resolveColorValue: () => resolveColorValue,
34
37
  resolveFlowStyle: () => resolveFlowStyle,
38
+ resolveTooltipLocation: () => resolveTooltipLocation,
35
39
  responsiveCSS: () => responsiveCSS,
36
40
  sanitizeInputValue: () => sanitizeInputValue,
37
41
  selectedTreeModels: () => selectedTreeModels,
38
42
  setLocalDayBoundary: () => setLocalDayBoundary,
43
+ tableToCsv: () => tableToCsv,
39
44
  themeToCSS: () => themeToCSS
40
45
  });
41
46
  module.exports = __toCommonJS(index_exports);
@@ -495,6 +500,17 @@ function resolveFlowStyle(props, theme) {
495
500
  style.WebkitBoxOrient = "vertical";
496
501
  style.WebkitLineClamp = lines;
497
502
  }
503
+ const focusStyle = props.focusStyle ?? theme.focusStyle;
504
+ if (focusStyle === "ring") {
505
+ style["--fui-field-focus-border"] = "var(--fui-color-borderStrong)";
506
+ style["--fui-field-focus-shadow"] = "0 0 0 2px color-mix(in srgb, var(--fui-color-focus) 22%, transparent)";
507
+ } else if (focusStyle === "none") {
508
+ style["--fui-field-focus-border"] = "var(--fui-color-border)";
509
+ style["--fui-field-focus-shadow"] = "none";
510
+ } else if (focusStyle === "border") {
511
+ style["--fui-field-focus-border"] = "var(--fui-color-borderStrong)";
512
+ style["--fui-field-focus-shadow"] = "none";
513
+ }
498
514
  Object.assign(style, userStyle);
499
515
  return { classNames, style };
500
516
  }
@@ -547,10 +563,24 @@ function download(content, type, fileName) {
547
563
  anchor.href = url;
548
564
  anchor.download = fileName;
549
565
  anchor.click();
550
- URL.revokeObjectURL(url);
566
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
567
+ }
568
+ function tableToCsv(data, columns) {
569
+ const escape = (value) => '"' + value.replaceAll('"', '""') + '"';
570
+ return [
571
+ columns.map((column) => column.header),
572
+ ...data.map((item) => columns.map((column) => cellText(item, column)))
573
+ ].map((row) => row.map(escape).join(",")).join("\r\n");
574
+ }
575
+ function exportTableToCsv(data, columns, fileName = "table") {
576
+ download(
577
+ "\uFEFF" + tableToCsv(data, columns),
578
+ "text/csv;charset=utf-8",
579
+ `${fileName}.csv`
580
+ );
551
581
  }
552
582
  function xml(value) {
553
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
583
+ return value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
554
584
  }
555
585
  function exportTableToExcel(data, columns, fileName = "table") {
556
586
  const row = (values) => `<Row>${values.map((value) => `<Cell><Data ss:Type="String">${xml(value)}</Data></Cell>`).join("")}</Row>`;
@@ -559,21 +589,24 @@ function exportTableToExcel(data, columns, fileName = "table") {
559
589
  ...data.map((item) => row(columns.map((column) => cellText(item, column))))
560
590
  ].join("");
561
591
  const workbook = `<?xml version="1.0"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"><Worksheet ss:Name="Data"><Table>${rows}</Table></Worksheet></Workbook>`;
562
- download(workbook, "application/vnd.ms-excel", `${fileName}.xls`);
592
+ download(workbook, "application/vnd.ms-excel", `${fileName}.xml`);
563
593
  }
564
594
  function pdfEscape(value) {
565
595
  return value.replaceAll("\\", "\\\\").replaceAll("(", "\\(").replaceAll(")", "\\)").replace(/[^\x20-\x7e]/g, "?");
566
596
  }
567
597
  function exportTableToPdf(data, columns, fileName = "table") {
568
- const lines = [
569
- columns.map((column) => column.header).join(" | "),
570
- ...data.map(
571
- (item) => columns.map((column) => cellText(item, column)).join(" | ")
572
- )
573
- ];
598
+ const wrap = (line) => line.replace(/\r?\n/g, " ").match(/.{1,82}/gu) ?? [""];
599
+ const header = wrap(columns.map((column) => column.header).join(" | "));
600
+ const lines = data.flatMap(
601
+ (item) => wrap(columns.map((column) => cellText(item, column)).join(" | "))
602
+ );
603
+ const pageLength = Math.max(1, 48 - header.length);
574
604
  const pages = Array.from(
575
- { length: Math.max(1, Math.ceil(lines.length / 48)) },
576
- (_, index) => lines.slice(index * 48, (index + 1) * 48)
605
+ { length: Math.max(1, Math.ceil(lines.length / pageLength)) },
606
+ (_, index) => [
607
+ ...header,
608
+ ...lines.slice(index * pageLength, (index + 1) * pageLength)
609
+ ]
577
610
  );
578
611
  const fontObject = 3 + pages.length * 2;
579
612
  const pageObjects = pages.map((_, index) => 3 + index * 2);
@@ -588,7 +621,7 @@ function exportTableToPdf(data, columns, fileName = "table") {
588
621
  "BT /F1 10 Tf 40 800 Td",
589
622
  ...page.flatMap((line, lineIndex) => [
590
623
  lineIndex ? "0 -15 Td" : "",
591
- `(${pdfEscape(line).slice(0, 115)}) Tj`
624
+ `(${pdfEscape(line)}) Tj`
592
625
  ]),
593
626
  "ET"
594
627
  ].filter(Boolean).join("\n");
@@ -648,12 +681,327 @@ function selectedTreeModels(nodes, values) {
648
681
  const selected = new Set(values);
649
682
  return flattenTree(nodes).filter((node) => selected.has(node.value));
650
683
  }
684
+
685
+ // src/async-label.ts
686
+ var idle = Object.freeze({ status: "idle" });
687
+ var loading = Object.freeze({ status: "loading" });
688
+ var defaults = {
689
+ batchWindowMs: 10,
690
+ maxBatchSize: 100,
691
+ maxConcurrentBatches: 4,
692
+ cacheTtlMs: 3e5,
693
+ missingTtlMs: 3e4,
694
+ maxCacheEntries: 1e3,
695
+ requestTimeoutMs: 3e4
696
+ };
697
+ var AsyncLabelStore = class {
698
+ constructor(config) {
699
+ this.config = config;
700
+ this.scope = config.scopeKey ?? "default";
701
+ this.options = { ...defaults, ...config.options };
702
+ for (const [name, value] of Object.entries(this.options)) {
703
+ const minimum = [
704
+ "batchWindowMs",
705
+ "cacheTtlMs",
706
+ "missingTtlMs",
707
+ "maxCacheEntries"
708
+ ].includes(name) ? 0 : 1;
709
+ if (!Number.isInteger(value) || value < minimum)
710
+ throw new RangeError(`Invalid AsyncLabel option: ${name}`);
711
+ }
712
+ for (const lookup of Object.values(config.lookups)) {
713
+ if (lookup.cacheTtlMs !== void 0 && (!Number.isFinite(lookup.cacheTtlMs) || lookup.cacheTtlMs < 0)) {
714
+ throw new RangeError("Invalid lookup cacheTtlMs");
715
+ }
716
+ }
717
+ }
718
+ config;
719
+ options;
720
+ entries = /* @__PURE__ */ new Map();
721
+ cache = /* @__PURE__ */ new Map();
722
+ queue = /* @__PURE__ */ new Map();
723
+ controllers = /* @__PURE__ */ new Set();
724
+ timer;
725
+ active = 0;
726
+ generation = 0;
727
+ disposed = false;
728
+ scope;
729
+ get scopeKey() {
730
+ return this.scope;
731
+ }
732
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
733
+ get cacheSize() {
734
+ return this.cache.size;
735
+ }
736
+ key(lookup, code) {
737
+ if (code === void 0 || code === null || String(code).trim() === "")
738
+ return void 0;
739
+ return JSON.stringify([lookup, String(code)]);
740
+ }
741
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
742
+ getSnapshot(lookup, code) {
743
+ const key = this.key(lookup, code);
744
+ if (!key || this.disposed) return idle;
745
+ const entry = this.entries.get(key);
746
+ if (entry) return entry.state;
747
+ const cached = this.cache.get(key);
748
+ return cached && cached.expiresAt > Date.now() ? cached.state : idle;
749
+ }
750
+ subscribe(lookup, code, listener) {
751
+ const key = this.key(lookup, code);
752
+ if (!key || this.disposed) return () => {
753
+ };
754
+ let entry = this.entries.get(key);
755
+ if (!entry) {
756
+ entry = {
757
+ key,
758
+ lookup,
759
+ code: String(code),
760
+ state: idle,
761
+ listeners: /* @__PURE__ */ new Set(),
762
+ version: 0,
763
+ pending: false
764
+ };
765
+ this.entries.set(key, entry);
766
+ }
767
+ entry.listeners.add(listener);
768
+ this.request(entry);
769
+ return () => {
770
+ entry.listeners.delete(listener);
771
+ if (!entry.listeners.size) {
772
+ if (this.queue.delete(key)) entry.pending = false;
773
+ if (!entry.pending) this.entries.delete(key);
774
+ }
775
+ };
776
+ }
777
+ emit(entry) {
778
+ for (const listener of [...entry.listeners]) listener();
779
+ }
780
+ request(entry) {
781
+ if (entry.pending || this.disposed) return;
782
+ const cached = this.cache.get(entry.key);
783
+ if (cached && cached.expiresAt > Date.now()) {
784
+ this.cache.delete(entry.key);
785
+ this.cache.set(entry.key, cached);
786
+ entry.state = cached.state;
787
+ this.emit(entry);
788
+ return;
789
+ }
790
+ this.cache.delete(entry.key);
791
+ if (!Object.hasOwn(this.config.lookups, entry.lookup)) {
792
+ entry.state = {
793
+ status: "error",
794
+ error: new Error(`Unknown lookup: ${entry.lookup}`)
795
+ };
796
+ this.emit(entry);
797
+ return;
798
+ }
799
+ entry.pending = true;
800
+ entry.state = loading;
801
+ this.queue.set(entry.key, entry);
802
+ this.emit(entry);
803
+ this.schedule();
804
+ }
805
+ schedule() {
806
+ if (this.timer !== void 0 || this.disposed || !this.queue.size) return;
807
+ this.timer = setTimeout(() => {
808
+ this.timer = void 0;
809
+ this.flush();
810
+ }, this.options.batchWindowMs);
811
+ }
812
+ flush() {
813
+ while (!this.disposed && this.active < this.options.maxConcurrentBatches && this.queue.size) {
814
+ const first = this.queue.values().next().value;
815
+ const batch = [];
816
+ for (const entry of this.queue.values()) {
817
+ if (entry.lookup === first.lookup) {
818
+ batch.push(entry);
819
+ this.queue.delete(entry.key);
820
+ if (batch.length === this.options.maxBatchSize) break;
821
+ }
822
+ }
823
+ void this.runBatch(first.lookup, batch);
824
+ }
825
+ }
826
+ cacheResult(entry, state) {
827
+ const ttl = state.status === "missing" ? this.options.missingTtlMs : this.config.lookups[entry.lookup].cacheTtlMs ?? this.options.cacheTtlMs;
828
+ if (!ttl || !this.options.maxCacheEntries) return;
829
+ this.cache.delete(entry.key);
830
+ this.cache.set(entry.key, { state, expiresAt: Date.now() + ttl });
831
+ while (this.cache.size > this.options.maxCacheEntries)
832
+ this.cache.delete(this.cache.keys().next().value);
833
+ }
834
+ async runBatch(lookup, batch) {
835
+ const generation = this.generation;
836
+ const scopeKey = this.scope;
837
+ const versions = batch.map((entry) => entry.version);
838
+ const controller = new AbortController();
839
+ this.controllers.add(controller);
840
+ this.active++;
841
+ let timeout;
842
+ const cancelled = new Promise((_, reject) => {
843
+ controller.signal.addEventListener(
844
+ "abort",
845
+ () => reject(controller.signal.reason ?? new Error("Lookup cancelled")),
846
+ { once: true }
847
+ );
848
+ timeout = setTimeout(
849
+ () => controller.abort(new Error("Lookup request timed out")),
850
+ this.options.requestTimeoutMs
851
+ );
852
+ });
853
+ try {
854
+ const result = await Promise.race([
855
+ Promise.resolve().then(() => {
856
+ if (controller.signal.aborted) throw controller.signal.reason;
857
+ return this.config.lookups[lookup].resolve(
858
+ batch.map((entry) => entry.code),
859
+ { scopeKey, signal: controller.signal }
860
+ );
861
+ }),
862
+ cancelled
863
+ ]);
864
+ if (this.disposed || generation !== this.generation) return;
865
+ batch.forEach((entry, index) => {
866
+ if (entry.version !== versions[index]) return;
867
+ const valid = result && Object.hasOwn(result, entry.code) && (typeof result[entry.code] === "string" || result[entry.code] === null);
868
+ entry.state = !valid ? {
869
+ status: "error",
870
+ error: new Error(`Incomplete lookup response for ${entry.code}`)
871
+ } : result[entry.code] === null ? { status: "missing" } : { status: "ready", label: result[entry.code] };
872
+ entry.pending = false;
873
+ if (entry.state.status !== "error")
874
+ this.cacheResult(entry, entry.state);
875
+ this.emit(entry);
876
+ if (!entry.listeners.size) this.entries.delete(entry.key);
877
+ });
878
+ } catch (error) {
879
+ if (this.disposed || generation !== this.generation) return;
880
+ batch.forEach((entry, index) => {
881
+ if (entry.version !== versions[index]) return;
882
+ entry.pending = false;
883
+ entry.state = { status: "error", error };
884
+ this.emit(entry);
885
+ if (!entry.listeners.size) this.entries.delete(entry.key);
886
+ });
887
+ } finally {
888
+ clearTimeout(timeout);
889
+ this.controllers.delete(controller);
890
+ if (generation === this.generation) {
891
+ this.active--;
892
+ this.flush();
893
+ }
894
+ }
895
+ }
896
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
897
+ invalidate(lookup, code) {
898
+ const key = code === void 0 ? void 0 : this.key(lookup ?? "", code);
899
+ const matches = (entryKey, name) => key ? entryKey === key : !lookup || name === lookup;
900
+ for (const cachedKey of this.cache.keys()) {
901
+ const name = JSON.parse(cachedKey)[0];
902
+ if (matches(cachedKey, name)) this.cache.delete(cachedKey);
903
+ }
904
+ for (const entry of this.entries.values()) {
905
+ if (!matches(entry.key, entry.lookup)) continue;
906
+ entry.version++;
907
+ entry.pending = false;
908
+ this.queue.delete(entry.key);
909
+ entry.state = idle;
910
+ if (entry.listeners.size) this.request(entry);
911
+ else this.entries.delete(entry.key);
912
+ }
913
+ }
914
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
915
+ prime(lookup, code, label) {
916
+ const key = this.key(lookup, code);
917
+ if (!key || this.disposed) return;
918
+ if (!Object.hasOwn(this.config.lookups, lookup))
919
+ throw new Error(`Unknown lookup: ${lookup}`);
920
+ const entry = this.entries.get(key) ?? {
921
+ key,
922
+ lookup,
923
+ code: String(code),
924
+ state: idle,
925
+ listeners: /* @__PURE__ */ new Set(),
926
+ version: 0,
927
+ pending: false
928
+ };
929
+ entry.version++;
930
+ entry.pending = false;
931
+ this.queue.delete(key);
932
+ entry.state = label === null ? { status: "missing" } : { status: "ready", label };
933
+ this.cacheResult(entry, entry.state);
934
+ this.emit(entry);
935
+ }
936
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
937
+ setScope(scopeKey) {
938
+ if (scopeKey === this.scope || this.disposed) return;
939
+ this.scope = scopeKey;
940
+ this.reset();
941
+ }
942
+ clear() {
943
+ if (!this.disposed) this.reset();
944
+ }
945
+ reset() {
946
+ this.generation++;
947
+ this.active = 0;
948
+ clearTimeout(this.timer);
949
+ this.timer = void 0;
950
+ for (const controller of this.controllers) controller.abort();
951
+ this.controllers.clear();
952
+ this.queue.clear();
953
+ this.cache.clear();
954
+ for (const entry of this.entries.values()) {
955
+ entry.version++;
956
+ entry.pending = false;
957
+ entry.state = idle;
958
+ if (entry.listeners.size) this.request(entry);
959
+ else this.entries.delete(entry.key);
960
+ }
961
+ }
962
+ dispose() {
963
+ if (this.disposed) return;
964
+ this.disposed = true;
965
+ this.generation++;
966
+ clearTimeout(this.timer);
967
+ this.timer = void 0;
968
+ for (const controller of this.controllers) controller.abort();
969
+ this.controllers.clear();
970
+ this.queue.clear();
971
+ this.cache.clear();
972
+ this.entries.clear();
973
+ }
974
+ };
975
+ function createAsyncLabelStore(config) {
976
+ return new AsyncLabelStore(config);
977
+ }
978
+
979
+ // src/tooltip.ts
980
+ function resolveTooltipLocation(preferred, anchor, tooltip, viewport, gap = 6) {
981
+ const available = {
982
+ top: anchor.top,
983
+ right: viewport.width - anchor.right,
984
+ bottom: viewport.height - anchor.bottom,
985
+ left: anchor.left
986
+ };
987
+ const opposite = {
988
+ top: "bottom",
989
+ bottom: "top",
990
+ left: "right",
991
+ right: "left"
992
+ };
993
+ const required = preferred === "top" || preferred === "bottom" ? tooltip.height + gap : tooltip.width + gap;
994
+ return available[preferred] < required && available[opposite[preferred]] > available[preferred] ? opposite[preferred] : preferred;
995
+ }
651
996
  // Annotate the CommonJS export names for ESM import in node:
652
997
  0 && (module.exports = {
998
+ AsyncLabelStore,
653
999
  clampNumber,
1000
+ createAsyncLabelStore,
654
1001
  createTheme,
655
1002
  defaultTheme,
656
1003
  enabledSelectableDescendants,
1004
+ exportTableToCsv,
657
1005
  exportTableToExcel,
658
1006
  exportTableToPdf,
659
1007
  filterTree,
@@ -662,9 +1010,11 @@ function selectedTreeModels(nodes, values) {
662
1010
  formatLocalDateTime,
663
1011
  resolveColorValue,
664
1012
  resolveFlowStyle,
1013
+ resolveTooltipLocation,
665
1014
  responsiveCSS,
666
1015
  sanitizeInputValue,
667
1016
  selectedTreeModels,
668
1017
  setLocalDayBoundary,
1018
+ tableToCsv,
669
1019
  themeToCSS
670
1020
  });
package/dist/index.d.cts CHANGED
@@ -109,10 +109,12 @@ interface TypographyProps {
109
109
  textTransform?: ResponsiveValue<"none" | "uppercase" | "lowercase" | "capitalize">;
110
110
  lines?: ResponsiveValue<number>;
111
111
  }
112
+ type FieldFocusStyle = "border" | "ring" | "none";
112
113
  interface BaseUIProps extends SpacingProps, LayoutProps, PositionProps, FlexItemProps, BorderProps, VisualProps {
113
114
  id?: string;
114
115
  hidden?: boolean;
115
116
  testId?: string;
117
+ focusStyle?: FieldFocusStyle;
116
118
  className?: string;
117
119
  style?: Readonly<FlowUIStyle>;
118
120
  }
@@ -151,6 +153,7 @@ interface ThemeColorScheme {
151
153
  overlay: string;
152
154
  }
153
155
  interface FlowUITheme {
156
+ focusStyle?: FieldFocusStyle;
154
157
  palette: ColorPalette;
155
158
  schemes: {
156
159
  light: ThemeColorScheme;
@@ -266,6 +269,7 @@ interface TreeModel extends DropdownModel {
266
269
  hasChildren?: boolean;
267
270
  }
268
271
  interface DropdownBehaviorProps extends BaseUIProps, DisableableProps {
272
+ clearable?: boolean;
269
273
  options: DropdownModel[];
270
274
  searchable?: boolean;
271
275
  searchPlaceholder?: string;
@@ -285,6 +289,7 @@ interface MultiSelectProps extends DropdownBehaviorProps {
285
289
  chipCloseIconColor?: ColorValue;
286
290
  }
287
291
  interface TreeMultiSelectProps extends BaseUIProps, DisableableProps {
292
+ clearable?: boolean;
288
293
  nodes: TreeModel[];
289
294
  value?: Array<string | number>;
290
295
  expandedValues?: Array<string | number>;
@@ -298,6 +303,7 @@ interface TreeMultiSelectProps extends BaseUIProps, DisableableProps {
298
303
  chipBackgroundColor?: ColorValue;
299
304
  chipCloseIconColor?: ColorValue;
300
305
  }
306
+ type TabSelectedStyle = "underline" | "fill";
301
307
  interface TabItem {
302
308
  id: string;
303
309
  label: string;
@@ -319,6 +325,13 @@ interface TableColumn<T> {
319
325
  align?: "left" | "center" | "right";
320
326
  format?: (value: unknown, row: T) => string | number;
321
327
  }
328
+ interface TableLoadMoreContext {
329
+ loadedCount: number;
330
+ totalCount?: number;
331
+ loading: boolean;
332
+ hasMore: boolean;
333
+ loadMore: () => void;
334
+ }
322
335
  type DialogPosition = "center" | "left" | "right" | "top" | "bottom";
323
336
  type TooltipLocation = "top" | "right" | "bottom" | "left";
324
337
  interface CardProps extends BaseUIProps {
@@ -346,6 +359,7 @@ interface TreeProps extends BaseUIProps {
346
359
  defaultExpanded?: boolean;
347
360
  }
348
361
  interface TreeDropdownProps extends BaseUIProps, DisableableProps {
362
+ clearable?: boolean;
349
363
  nodes: TreeModel[];
350
364
  value?: string | number;
351
365
  placeholder?: string;
@@ -424,6 +438,7 @@ interface BreadcrumbItem {
424
438
  other?: any;
425
439
  }
426
440
  interface BreadcrumbProps extends BaseUIProps {
441
+ separator?: string;
427
442
  items: BreadcrumbItem[];
428
443
  separatorIcon?: string;
429
444
  }
@@ -503,6 +518,8 @@ type FlowInputMode = NonNullable<InputProps["inputMode"]>;
503
518
  declare function sanitizeInputValue(value: string, mode?: FlowInputMode): string;
504
519
  declare function clampNumber(value: number, min: number, max: number): number;
505
520
 
521
+ declare function tableToCsv<T>(data: readonly T[], columns: readonly TableColumn<T>[]): string;
522
+ declare function exportTableToCsv<T>(data: T[], columns: TableColumn<T>[], fileName?: string): void;
506
523
  /** Downloads an Excel-compatible SpreadsheetML workbook without a runtime dependency. */
507
524
  declare function exportTableToExcel<T>(data: T[], columns: TableColumn<T>[], fileName?: string): void;
508
525
  /** Downloads a compact PDF containing the currently visible table data. */
@@ -514,4 +531,96 @@ declare function enabledSelectableDescendants(node: TreeModel): TreeModel[];
514
531
  declare function filterTree(nodes: TreeModel[], query: string): TreeModel[];
515
532
  declare function selectedTreeModels(nodes: TreeModel[], values: SelectionValue[]): TreeModel[];
516
533
 
517
- export { type AlignValue, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelProps, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TableColumn, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, themeToCSS };
534
+ /** Code-to-text results. null is a confirmed missing value; absent keys are errors. */
535
+ type LabelResults = Readonly<Record<string, string | null>>;
536
+ interface LabelResolverContext {
537
+ readonly scopeKey: string;
538
+ readonly signal: AbortSignal;
539
+ }
540
+ interface LabelLookup {
541
+ resolve(codes: readonly string[], context: LabelResolverContext): Promise<LabelResults>;
542
+ cacheTtlMs?: number;
543
+ }
544
+ interface AsyncLabelOptions {
545
+ batchWindowMs?: number;
546
+ maxBatchSize?: number;
547
+ maxConcurrentBatches?: number;
548
+ cacheTtlMs?: number;
549
+ missingTtlMs?: number;
550
+ /** Maximum completed results across all lookups in this store. */
551
+ maxCacheEntries?: number;
552
+ requestTimeoutMs?: number;
553
+ }
554
+ interface AsyncLabelConfig {
555
+ lookups: Readonly<Record<string, LabelLookup>>;
556
+ scopeKey?: string;
557
+ options?: AsyncLabelOptions;
558
+ }
559
+ type AsyncLabelState = {
560
+ readonly status: "idle";
561
+ } | {
562
+ readonly status: "loading";
563
+ } | {
564
+ readonly status: "ready";
565
+ readonly label: string;
566
+ } | {
567
+ readonly status: "missing";
568
+ } | {
569
+ readonly status: "error";
570
+ readonly error: unknown;
571
+ };
572
+ type AsyncLabelCode = string | number | null | undefined;
573
+ type Listener = () => void;
574
+ /** Framework-neutral, provider-owned lookup store. Never create a global user cache. */
575
+ declare class AsyncLabelStore {
576
+ private readonly config;
577
+ private readonly options;
578
+ private readonly entries;
579
+ private readonly cache;
580
+ private readonly queue;
581
+ private readonly controllers;
582
+ private timer?;
583
+ private active;
584
+ private generation;
585
+ private disposed;
586
+ private scope;
587
+ constructor(config: AsyncLabelConfig);
588
+ get scopeKey(): string;
589
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
590
+ get cacheSize(): number;
591
+ private key;
592
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
593
+ getSnapshot(lookup: string, code: AsyncLabelCode): AsyncLabelState;
594
+ subscribe(lookup: string, code: AsyncLabelCode, listener: Listener): () => void;
595
+ private emit;
596
+ private request;
597
+ private schedule;
598
+ private flush;
599
+ private cacheResult;
600
+ private runBatch;
601
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
602
+ invalidate(lookup?: string, code?: AsyncLabelCode): void;
603
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
604
+ prime(lookup: string, code: AsyncLabelCode, label: string | null): void;
605
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
606
+ setScope(scopeKey: string): void;
607
+ clear(): void;
608
+ private reset;
609
+ dispose(): void;
610
+ }
611
+ declare function createAsyncLabelStore(config: AsyncLabelConfig): AsyncLabelStore;
612
+
613
+ declare function resolveTooltipLocation(preferred: TooltipLocation, anchor: {
614
+ top: number;
615
+ right: number;
616
+ bottom: number;
617
+ left: number;
618
+ }, tooltip: {
619
+ width: number;
620
+ height: number;
621
+ }, viewport: {
622
+ width: number;
623
+ height: number;
624
+ }, gap?: number): TooltipLocation;
625
+
626
+ export { type AlignValue, type AsyncLabelCode, type AsyncLabelConfig, type AsyncLabelOptions, type AsyncLabelState, AsyncLabelStore, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FieldFocusStyle, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelLookup, type LabelProps, type LabelResolverContext, type LabelResults, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TabSelectedStyle, type TableColumn, type TableLoadMoreContext, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createAsyncLabelStore, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToCsv, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, resolveTooltipLocation, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, tableToCsv, themeToCSS };
package/dist/index.d.ts CHANGED
@@ -109,10 +109,12 @@ interface TypographyProps {
109
109
  textTransform?: ResponsiveValue<"none" | "uppercase" | "lowercase" | "capitalize">;
110
110
  lines?: ResponsiveValue<number>;
111
111
  }
112
+ type FieldFocusStyle = "border" | "ring" | "none";
112
113
  interface BaseUIProps extends SpacingProps, LayoutProps, PositionProps, FlexItemProps, BorderProps, VisualProps {
113
114
  id?: string;
114
115
  hidden?: boolean;
115
116
  testId?: string;
117
+ focusStyle?: FieldFocusStyle;
116
118
  className?: string;
117
119
  style?: Readonly<FlowUIStyle>;
118
120
  }
@@ -151,6 +153,7 @@ interface ThemeColorScheme {
151
153
  overlay: string;
152
154
  }
153
155
  interface FlowUITheme {
156
+ focusStyle?: FieldFocusStyle;
154
157
  palette: ColorPalette;
155
158
  schemes: {
156
159
  light: ThemeColorScheme;
@@ -266,6 +269,7 @@ interface TreeModel extends DropdownModel {
266
269
  hasChildren?: boolean;
267
270
  }
268
271
  interface DropdownBehaviorProps extends BaseUIProps, DisableableProps {
272
+ clearable?: boolean;
269
273
  options: DropdownModel[];
270
274
  searchable?: boolean;
271
275
  searchPlaceholder?: string;
@@ -285,6 +289,7 @@ interface MultiSelectProps extends DropdownBehaviorProps {
285
289
  chipCloseIconColor?: ColorValue;
286
290
  }
287
291
  interface TreeMultiSelectProps extends BaseUIProps, DisableableProps {
292
+ clearable?: boolean;
288
293
  nodes: TreeModel[];
289
294
  value?: Array<string | number>;
290
295
  expandedValues?: Array<string | number>;
@@ -298,6 +303,7 @@ interface TreeMultiSelectProps extends BaseUIProps, DisableableProps {
298
303
  chipBackgroundColor?: ColorValue;
299
304
  chipCloseIconColor?: ColorValue;
300
305
  }
306
+ type TabSelectedStyle = "underline" | "fill";
301
307
  interface TabItem {
302
308
  id: string;
303
309
  label: string;
@@ -319,6 +325,13 @@ interface TableColumn<T> {
319
325
  align?: "left" | "center" | "right";
320
326
  format?: (value: unknown, row: T) => string | number;
321
327
  }
328
+ interface TableLoadMoreContext {
329
+ loadedCount: number;
330
+ totalCount?: number;
331
+ loading: boolean;
332
+ hasMore: boolean;
333
+ loadMore: () => void;
334
+ }
322
335
  type DialogPosition = "center" | "left" | "right" | "top" | "bottom";
323
336
  type TooltipLocation = "top" | "right" | "bottom" | "left";
324
337
  interface CardProps extends BaseUIProps {
@@ -346,6 +359,7 @@ interface TreeProps extends BaseUIProps {
346
359
  defaultExpanded?: boolean;
347
360
  }
348
361
  interface TreeDropdownProps extends BaseUIProps, DisableableProps {
362
+ clearable?: boolean;
349
363
  nodes: TreeModel[];
350
364
  value?: string | number;
351
365
  placeholder?: string;
@@ -424,6 +438,7 @@ interface BreadcrumbItem {
424
438
  other?: any;
425
439
  }
426
440
  interface BreadcrumbProps extends BaseUIProps {
441
+ separator?: string;
427
442
  items: BreadcrumbItem[];
428
443
  separatorIcon?: string;
429
444
  }
@@ -503,6 +518,8 @@ type FlowInputMode = NonNullable<InputProps["inputMode"]>;
503
518
  declare function sanitizeInputValue(value: string, mode?: FlowInputMode): string;
504
519
  declare function clampNumber(value: number, min: number, max: number): number;
505
520
 
521
+ declare function tableToCsv<T>(data: readonly T[], columns: readonly TableColumn<T>[]): string;
522
+ declare function exportTableToCsv<T>(data: T[], columns: TableColumn<T>[], fileName?: string): void;
506
523
  /** Downloads an Excel-compatible SpreadsheetML workbook without a runtime dependency. */
507
524
  declare function exportTableToExcel<T>(data: T[], columns: TableColumn<T>[], fileName?: string): void;
508
525
  /** Downloads a compact PDF containing the currently visible table data. */
@@ -514,4 +531,96 @@ declare function enabledSelectableDescendants(node: TreeModel): TreeModel[];
514
531
  declare function filterTree(nodes: TreeModel[], query: string): TreeModel[];
515
532
  declare function selectedTreeModels(nodes: TreeModel[], values: SelectionValue[]): TreeModel[];
516
533
 
517
- export { type AlignValue, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelProps, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TableColumn, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, themeToCSS };
534
+ /** Code-to-text results. null is a confirmed missing value; absent keys are errors. */
535
+ type LabelResults = Readonly<Record<string, string | null>>;
536
+ interface LabelResolverContext {
537
+ readonly scopeKey: string;
538
+ readonly signal: AbortSignal;
539
+ }
540
+ interface LabelLookup {
541
+ resolve(codes: readonly string[], context: LabelResolverContext): Promise<LabelResults>;
542
+ cacheTtlMs?: number;
543
+ }
544
+ interface AsyncLabelOptions {
545
+ batchWindowMs?: number;
546
+ maxBatchSize?: number;
547
+ maxConcurrentBatches?: number;
548
+ cacheTtlMs?: number;
549
+ missingTtlMs?: number;
550
+ /** Maximum completed results across all lookups in this store. */
551
+ maxCacheEntries?: number;
552
+ requestTimeoutMs?: number;
553
+ }
554
+ interface AsyncLabelConfig {
555
+ lookups: Readonly<Record<string, LabelLookup>>;
556
+ scopeKey?: string;
557
+ options?: AsyncLabelOptions;
558
+ }
559
+ type AsyncLabelState = {
560
+ readonly status: "idle";
561
+ } | {
562
+ readonly status: "loading";
563
+ } | {
564
+ readonly status: "ready";
565
+ readonly label: string;
566
+ } | {
567
+ readonly status: "missing";
568
+ } | {
569
+ readonly status: "error";
570
+ readonly error: unknown;
571
+ };
572
+ type AsyncLabelCode = string | number | null | undefined;
573
+ type Listener = () => void;
574
+ /** Framework-neutral, provider-owned lookup store. Never create a global user cache. */
575
+ declare class AsyncLabelStore {
576
+ private readonly config;
577
+ private readonly options;
578
+ private readonly entries;
579
+ private readonly cache;
580
+ private readonly queue;
581
+ private readonly controllers;
582
+ private timer?;
583
+ private active;
584
+ private generation;
585
+ private disposed;
586
+ private scope;
587
+ constructor(config: AsyncLabelConfig);
588
+ get scopeKey(): string;
589
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
590
+ get cacheSize(): number;
591
+ private key;
592
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
593
+ getSnapshot(lookup: string, code: AsyncLabelCode): AsyncLabelState;
594
+ subscribe(lookup: string, code: AsyncLabelCode, listener: Listener): () => void;
595
+ private emit;
596
+ private request;
597
+ private schedule;
598
+ private flush;
599
+ private cacheResult;
600
+ private runBatch;
601
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
602
+ invalidate(lookup?: string, code?: AsyncLabelCode): void;
603
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
604
+ prime(lookup: string, code: AsyncLabelCode, label: string | null): void;
605
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
606
+ setScope(scopeKey: string): void;
607
+ clear(): void;
608
+ private reset;
609
+ dispose(): void;
610
+ }
611
+ declare function createAsyncLabelStore(config: AsyncLabelConfig): AsyncLabelStore;
612
+
613
+ declare function resolveTooltipLocation(preferred: TooltipLocation, anchor: {
614
+ top: number;
615
+ right: number;
616
+ bottom: number;
617
+ left: number;
618
+ }, tooltip: {
619
+ width: number;
620
+ height: number;
621
+ }, viewport: {
622
+ width: number;
623
+ height: number;
624
+ }, gap?: number): TooltipLocation;
625
+
626
+ export { type AlignValue, type AsyncLabelCode, type AsyncLabelConfig, type AsyncLabelOptions, type AsyncLabelState, AsyncLabelStore, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FieldFocusStyle, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelLookup, type LabelProps, type LabelResolverContext, type LabelResults, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TabSelectedStyle, type TableColumn, type TableLoadMoreContext, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createAsyncLabelStore, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToCsv, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, resolveTooltipLocation, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, tableToCsv, themeToCSS };
package/dist/index.js CHANGED
@@ -453,6 +453,17 @@ function resolveFlowStyle(props, theme) {
453
453
  style.WebkitBoxOrient = "vertical";
454
454
  style.WebkitLineClamp = lines;
455
455
  }
456
+ const focusStyle = props.focusStyle ?? theme.focusStyle;
457
+ if (focusStyle === "ring") {
458
+ style["--fui-field-focus-border"] = "var(--fui-color-borderStrong)";
459
+ style["--fui-field-focus-shadow"] = "0 0 0 2px color-mix(in srgb, var(--fui-color-focus) 22%, transparent)";
460
+ } else if (focusStyle === "none") {
461
+ style["--fui-field-focus-border"] = "var(--fui-color-border)";
462
+ style["--fui-field-focus-shadow"] = "none";
463
+ } else if (focusStyle === "border") {
464
+ style["--fui-field-focus-border"] = "var(--fui-color-borderStrong)";
465
+ style["--fui-field-focus-shadow"] = "none";
466
+ }
456
467
  Object.assign(style, userStyle);
457
468
  return { classNames, style };
458
469
  }
@@ -505,10 +516,24 @@ function download(content, type, fileName) {
505
516
  anchor.href = url;
506
517
  anchor.download = fileName;
507
518
  anchor.click();
508
- URL.revokeObjectURL(url);
519
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
520
+ }
521
+ function tableToCsv(data, columns) {
522
+ const escape = (value) => '"' + value.replaceAll('"', '""') + '"';
523
+ return [
524
+ columns.map((column) => column.header),
525
+ ...data.map((item) => columns.map((column) => cellText(item, column)))
526
+ ].map((row) => row.map(escape).join(",")).join("\r\n");
527
+ }
528
+ function exportTableToCsv(data, columns, fileName = "table") {
529
+ download(
530
+ "\uFEFF" + tableToCsv(data, columns),
531
+ "text/csv;charset=utf-8",
532
+ `${fileName}.csv`
533
+ );
509
534
  }
510
535
  function xml(value) {
511
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
536
+ return value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
512
537
  }
513
538
  function exportTableToExcel(data, columns, fileName = "table") {
514
539
  const row = (values) => `<Row>${values.map((value) => `<Cell><Data ss:Type="String">${xml(value)}</Data></Cell>`).join("")}</Row>`;
@@ -517,21 +542,24 @@ function exportTableToExcel(data, columns, fileName = "table") {
517
542
  ...data.map((item) => row(columns.map((column) => cellText(item, column))))
518
543
  ].join("");
519
544
  const workbook = `<?xml version="1.0"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"><Worksheet ss:Name="Data"><Table>${rows}</Table></Worksheet></Workbook>`;
520
- download(workbook, "application/vnd.ms-excel", `${fileName}.xls`);
545
+ download(workbook, "application/vnd.ms-excel", `${fileName}.xml`);
521
546
  }
522
547
  function pdfEscape(value) {
523
548
  return value.replaceAll("\\", "\\\\").replaceAll("(", "\\(").replaceAll(")", "\\)").replace(/[^\x20-\x7e]/g, "?");
524
549
  }
525
550
  function exportTableToPdf(data, columns, fileName = "table") {
526
- const lines = [
527
- columns.map((column) => column.header).join(" | "),
528
- ...data.map(
529
- (item) => columns.map((column) => cellText(item, column)).join(" | ")
530
- )
531
- ];
551
+ const wrap = (line) => line.replace(/\r?\n/g, " ").match(/.{1,82}/gu) ?? [""];
552
+ const header = wrap(columns.map((column) => column.header).join(" | "));
553
+ const lines = data.flatMap(
554
+ (item) => wrap(columns.map((column) => cellText(item, column)).join(" | "))
555
+ );
556
+ const pageLength = Math.max(1, 48 - header.length);
532
557
  const pages = Array.from(
533
- { length: Math.max(1, Math.ceil(lines.length / 48)) },
534
- (_, index) => lines.slice(index * 48, (index + 1) * 48)
558
+ { length: Math.max(1, Math.ceil(lines.length / pageLength)) },
559
+ (_, index) => [
560
+ ...header,
561
+ ...lines.slice(index * pageLength, (index + 1) * pageLength)
562
+ ]
535
563
  );
536
564
  const fontObject = 3 + pages.length * 2;
537
565
  const pageObjects = pages.map((_, index) => 3 + index * 2);
@@ -546,7 +574,7 @@ function exportTableToPdf(data, columns, fileName = "table") {
546
574
  "BT /F1 10 Tf 40 800 Td",
547
575
  ...page.flatMap((line, lineIndex) => [
548
576
  lineIndex ? "0 -15 Td" : "",
549
- `(${pdfEscape(line).slice(0, 115)}) Tj`
577
+ `(${pdfEscape(line)}) Tj`
550
578
  ]),
551
579
  "ET"
552
580
  ].filter(Boolean).join("\n");
@@ -606,11 +634,326 @@ function selectedTreeModels(nodes, values) {
606
634
  const selected = new Set(values);
607
635
  return flattenTree(nodes).filter((node) => selected.has(node.value));
608
636
  }
637
+
638
+ // src/async-label.ts
639
+ var idle = Object.freeze({ status: "idle" });
640
+ var loading = Object.freeze({ status: "loading" });
641
+ var defaults = {
642
+ batchWindowMs: 10,
643
+ maxBatchSize: 100,
644
+ maxConcurrentBatches: 4,
645
+ cacheTtlMs: 3e5,
646
+ missingTtlMs: 3e4,
647
+ maxCacheEntries: 1e3,
648
+ requestTimeoutMs: 3e4
649
+ };
650
+ var AsyncLabelStore = class {
651
+ constructor(config) {
652
+ this.config = config;
653
+ this.scope = config.scopeKey ?? "default";
654
+ this.options = { ...defaults, ...config.options };
655
+ for (const [name, value] of Object.entries(this.options)) {
656
+ const minimum = [
657
+ "batchWindowMs",
658
+ "cacheTtlMs",
659
+ "missingTtlMs",
660
+ "maxCacheEntries"
661
+ ].includes(name) ? 0 : 1;
662
+ if (!Number.isInteger(value) || value < minimum)
663
+ throw new RangeError(`Invalid AsyncLabel option: ${name}`);
664
+ }
665
+ for (const lookup of Object.values(config.lookups)) {
666
+ if (lookup.cacheTtlMs !== void 0 && (!Number.isFinite(lookup.cacheTtlMs) || lookup.cacheTtlMs < 0)) {
667
+ throw new RangeError("Invalid lookup cacheTtlMs");
668
+ }
669
+ }
670
+ }
671
+ config;
672
+ options;
673
+ entries = /* @__PURE__ */ new Map();
674
+ cache = /* @__PURE__ */ new Map();
675
+ queue = /* @__PURE__ */ new Map();
676
+ controllers = /* @__PURE__ */ new Set();
677
+ timer;
678
+ active = 0;
679
+ generation = 0;
680
+ disposed = false;
681
+ scope;
682
+ get scopeKey() {
683
+ return this.scope;
684
+ }
685
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
686
+ get cacheSize() {
687
+ return this.cache.size;
688
+ }
689
+ key(lookup, code) {
690
+ if (code === void 0 || code === null || String(code).trim() === "")
691
+ return void 0;
692
+ return JSON.stringify([lookup, String(code)]);
693
+ }
694
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
695
+ getSnapshot(lookup, code) {
696
+ const key = this.key(lookup, code);
697
+ if (!key || this.disposed) return idle;
698
+ const entry = this.entries.get(key);
699
+ if (entry) return entry.state;
700
+ const cached = this.cache.get(key);
701
+ return cached && cached.expiresAt > Date.now() ? cached.state : idle;
702
+ }
703
+ subscribe(lookup, code, listener) {
704
+ const key = this.key(lookup, code);
705
+ if (!key || this.disposed) return () => {
706
+ };
707
+ let entry = this.entries.get(key);
708
+ if (!entry) {
709
+ entry = {
710
+ key,
711
+ lookup,
712
+ code: String(code),
713
+ state: idle,
714
+ listeners: /* @__PURE__ */ new Set(),
715
+ version: 0,
716
+ pending: false
717
+ };
718
+ this.entries.set(key, entry);
719
+ }
720
+ entry.listeners.add(listener);
721
+ this.request(entry);
722
+ return () => {
723
+ entry.listeners.delete(listener);
724
+ if (!entry.listeners.size) {
725
+ if (this.queue.delete(key)) entry.pending = false;
726
+ if (!entry.pending) this.entries.delete(key);
727
+ }
728
+ };
729
+ }
730
+ emit(entry) {
731
+ for (const listener of [...entry.listeners]) listener();
732
+ }
733
+ request(entry) {
734
+ if (entry.pending || this.disposed) return;
735
+ const cached = this.cache.get(entry.key);
736
+ if (cached && cached.expiresAt > Date.now()) {
737
+ this.cache.delete(entry.key);
738
+ this.cache.set(entry.key, cached);
739
+ entry.state = cached.state;
740
+ this.emit(entry);
741
+ return;
742
+ }
743
+ this.cache.delete(entry.key);
744
+ if (!Object.hasOwn(this.config.lookups, entry.lookup)) {
745
+ entry.state = {
746
+ status: "error",
747
+ error: new Error(`Unknown lookup: ${entry.lookup}`)
748
+ };
749
+ this.emit(entry);
750
+ return;
751
+ }
752
+ entry.pending = true;
753
+ entry.state = loading;
754
+ this.queue.set(entry.key, entry);
755
+ this.emit(entry);
756
+ this.schedule();
757
+ }
758
+ schedule() {
759
+ if (this.timer !== void 0 || this.disposed || !this.queue.size) return;
760
+ this.timer = setTimeout(() => {
761
+ this.timer = void 0;
762
+ this.flush();
763
+ }, this.options.batchWindowMs);
764
+ }
765
+ flush() {
766
+ while (!this.disposed && this.active < this.options.maxConcurrentBatches && this.queue.size) {
767
+ const first = this.queue.values().next().value;
768
+ const batch = [];
769
+ for (const entry of this.queue.values()) {
770
+ if (entry.lookup === first.lookup) {
771
+ batch.push(entry);
772
+ this.queue.delete(entry.key);
773
+ if (batch.length === this.options.maxBatchSize) break;
774
+ }
775
+ }
776
+ void this.runBatch(first.lookup, batch);
777
+ }
778
+ }
779
+ cacheResult(entry, state) {
780
+ const ttl = state.status === "missing" ? this.options.missingTtlMs : this.config.lookups[entry.lookup].cacheTtlMs ?? this.options.cacheTtlMs;
781
+ if (!ttl || !this.options.maxCacheEntries) return;
782
+ this.cache.delete(entry.key);
783
+ this.cache.set(entry.key, { state, expiresAt: Date.now() + ttl });
784
+ while (this.cache.size > this.options.maxCacheEntries)
785
+ this.cache.delete(this.cache.keys().next().value);
786
+ }
787
+ async runBatch(lookup, batch) {
788
+ const generation = this.generation;
789
+ const scopeKey = this.scope;
790
+ const versions = batch.map((entry) => entry.version);
791
+ const controller = new AbortController();
792
+ this.controllers.add(controller);
793
+ this.active++;
794
+ let timeout;
795
+ const cancelled = new Promise((_, reject) => {
796
+ controller.signal.addEventListener(
797
+ "abort",
798
+ () => reject(controller.signal.reason ?? new Error("Lookup cancelled")),
799
+ { once: true }
800
+ );
801
+ timeout = setTimeout(
802
+ () => controller.abort(new Error("Lookup request timed out")),
803
+ this.options.requestTimeoutMs
804
+ );
805
+ });
806
+ try {
807
+ const result = await Promise.race([
808
+ Promise.resolve().then(() => {
809
+ if (controller.signal.aborted) throw controller.signal.reason;
810
+ return this.config.lookups[lookup].resolve(
811
+ batch.map((entry) => entry.code),
812
+ { scopeKey, signal: controller.signal }
813
+ );
814
+ }),
815
+ cancelled
816
+ ]);
817
+ if (this.disposed || generation !== this.generation) return;
818
+ batch.forEach((entry, index) => {
819
+ if (entry.version !== versions[index]) return;
820
+ const valid = result && Object.hasOwn(result, entry.code) && (typeof result[entry.code] === "string" || result[entry.code] === null);
821
+ entry.state = !valid ? {
822
+ status: "error",
823
+ error: new Error(`Incomplete lookup response for ${entry.code}`)
824
+ } : result[entry.code] === null ? { status: "missing" } : { status: "ready", label: result[entry.code] };
825
+ entry.pending = false;
826
+ if (entry.state.status !== "error")
827
+ this.cacheResult(entry, entry.state);
828
+ this.emit(entry);
829
+ if (!entry.listeners.size) this.entries.delete(entry.key);
830
+ });
831
+ } catch (error) {
832
+ if (this.disposed || generation !== this.generation) return;
833
+ batch.forEach((entry, index) => {
834
+ if (entry.version !== versions[index]) return;
835
+ entry.pending = false;
836
+ entry.state = { status: "error", error };
837
+ this.emit(entry);
838
+ if (!entry.listeners.size) this.entries.delete(entry.key);
839
+ });
840
+ } finally {
841
+ clearTimeout(timeout);
842
+ this.controllers.delete(controller);
843
+ if (generation === this.generation) {
844
+ this.active--;
845
+ this.flush();
846
+ }
847
+ }
848
+ }
849
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
850
+ invalidate(lookup, code) {
851
+ const key = code === void 0 ? void 0 : this.key(lookup ?? "", code);
852
+ const matches = (entryKey, name) => key ? entryKey === key : !lookup || name === lookup;
853
+ for (const cachedKey of this.cache.keys()) {
854
+ const name = JSON.parse(cachedKey)[0];
855
+ if (matches(cachedKey, name)) this.cache.delete(cachedKey);
856
+ }
857
+ for (const entry of this.entries.values()) {
858
+ if (!matches(entry.key, entry.lookup)) continue;
859
+ entry.version++;
860
+ entry.pending = false;
861
+ this.queue.delete(entry.key);
862
+ entry.state = idle;
863
+ if (entry.listeners.size) this.request(entry);
864
+ else this.entries.delete(entry.key);
865
+ }
866
+ }
867
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
868
+ prime(lookup, code, label) {
869
+ const key = this.key(lookup, code);
870
+ if (!key || this.disposed) return;
871
+ if (!Object.hasOwn(this.config.lookups, lookup))
872
+ throw new Error(`Unknown lookup: ${lookup}`);
873
+ const entry = this.entries.get(key) ?? {
874
+ key,
875
+ lookup,
876
+ code: String(code),
877
+ state: idle,
878
+ listeners: /* @__PURE__ */ new Set(),
879
+ version: 0,
880
+ pending: false
881
+ };
882
+ entry.version++;
883
+ entry.pending = false;
884
+ this.queue.delete(key);
885
+ entry.state = label === null ? { status: "missing" } : { status: "ready", label };
886
+ this.cacheResult(entry, entry.state);
887
+ this.emit(entry);
888
+ }
889
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
890
+ setScope(scopeKey) {
891
+ if (scopeKey === this.scope || this.disposed) return;
892
+ this.scope = scopeKey;
893
+ this.reset();
894
+ }
895
+ clear() {
896
+ if (!this.disposed) this.reset();
897
+ }
898
+ reset() {
899
+ this.generation++;
900
+ this.active = 0;
901
+ clearTimeout(this.timer);
902
+ this.timer = void 0;
903
+ for (const controller of this.controllers) controller.abort();
904
+ this.controllers.clear();
905
+ this.queue.clear();
906
+ this.cache.clear();
907
+ for (const entry of this.entries.values()) {
908
+ entry.version++;
909
+ entry.pending = false;
910
+ entry.state = idle;
911
+ if (entry.listeners.size) this.request(entry);
912
+ else this.entries.delete(entry.key);
913
+ }
914
+ }
915
+ dispose() {
916
+ if (this.disposed) return;
917
+ this.disposed = true;
918
+ this.generation++;
919
+ clearTimeout(this.timer);
920
+ this.timer = void 0;
921
+ for (const controller of this.controllers) controller.abort();
922
+ this.controllers.clear();
923
+ this.queue.clear();
924
+ this.cache.clear();
925
+ this.entries.clear();
926
+ }
927
+ };
928
+ function createAsyncLabelStore(config) {
929
+ return new AsyncLabelStore(config);
930
+ }
931
+
932
+ // src/tooltip.ts
933
+ function resolveTooltipLocation(preferred, anchor, tooltip, viewport, gap = 6) {
934
+ const available = {
935
+ top: anchor.top,
936
+ right: viewport.width - anchor.right,
937
+ bottom: viewport.height - anchor.bottom,
938
+ left: anchor.left
939
+ };
940
+ const opposite = {
941
+ top: "bottom",
942
+ bottom: "top",
943
+ left: "right",
944
+ right: "left"
945
+ };
946
+ const required = preferred === "top" || preferred === "bottom" ? tooltip.height + gap : tooltip.width + gap;
947
+ return available[preferred] < required && available[opposite[preferred]] > available[preferred] ? opposite[preferred] : preferred;
948
+ }
609
949
  export {
950
+ AsyncLabelStore,
610
951
  clampNumber,
952
+ createAsyncLabelStore,
611
953
  createTheme,
612
954
  defaultTheme,
613
955
  enabledSelectableDescendants,
956
+ exportTableToCsv,
614
957
  exportTableToExcel,
615
958
  exportTableToPdf,
616
959
  filterTree,
@@ -619,9 +962,11 @@ export {
619
962
  formatLocalDateTime,
620
963
  resolveColorValue,
621
964
  resolveFlowStyle,
965
+ resolveTooltipLocation,
622
966
  responsiveCSS,
623
967
  sanitizeInputValue,
624
968
  selectedTreeModels,
625
969
  setLocalDayBoundary,
970
+ tableToCsv,
626
971
  themeToCSS
627
972
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akin2unde/flowui-core",
3
- "version": "0.2.1",
3
+ "version": "1.0.0",
4
4
  "description": "Framework-independent contracts, themes and style resolution for FlowUI.",
5
5
  "author": "Akintunde Morakinyo",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "dist"
35
35
  ],
36
36
  "scripts": {
37
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
37
+ "build": "tsup src/index.ts --format esm,cjs --config ../../scripts/tsup.config.mjs --clean",
38
38
  "typecheck": "tsc --noEmit",
39
39
  "test": "vitest run",
40
40
  "prepack": "node ../../scripts/prepack.mjs core"
@@ -44,8 +44,8 @@
44
44
  },
45
45
  "devDependencies": {
46
46
  "tsup": "^8.5.0",
47
- "typescript": "^5.9.0",
48
- "vitest": "^3.2.0"
47
+ "typescript": "~6.0.3",
48
+ "vitest": "^4.0.8"
49
49
  },
50
50
  "sideEffects": false
51
51
  }