@oddmash/juliya 0.5.1 → 0.6.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.
@@ -1,6 +1,7 @@
1
1
  import type { HTMLAttributes } from "react";
2
2
  import type { JuliyaConfig } from "../../core/config.js";
3
- export declare const useJuliyaScope: (config?: JuliyaConfig) => {
3
+ import type { JuliyaScopeDiagnostics } from "../../dom/scope.js";
4
+ export declare const useJuliyaScope: (config?: JuliyaConfig, diagnostics?: JuliyaScopeDiagnostics) => {
4
5
  ref: (next: HTMLElement | null) => void;
5
6
  refresh: () => void | undefined;
6
7
  };
@@ -8,5 +9,6 @@ export interface JuliyaScopeProps extends Omit<HTMLAttributes<HTMLElement>, "chi
8
9
  as?: "div" | "article" | "section" | "main";
9
10
  html: string;
10
11
  config?: JuliyaConfig;
12
+ diagnostics?: JuliyaScopeDiagnostics;
11
13
  }
12
- export declare const JuliyaScope: ({ as: Tag, html, config, ...props }: JuliyaScopeProps) => import("react").JSX.Element;
14
+ export declare const JuliyaScope: ({ as: Tag, html, config, diagnostics, ...props }: JuliyaScopeProps) => import("react").JSX.Element;
@@ -3,28 +3,37 @@ import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { useCallback, useEffect, useRef, useState } from "react";
4
4
  import { mountJuliyaScope } from "../../dom/scope.js";
5
5
  import { useJuliyaConfig } from "./juliya-provider.js";
6
- export const useJuliyaScope = (config) => {
6
+ export const useJuliyaScope = (config, diagnostics) => {
7
7
  const resolved = useJuliyaConfig(config);
8
8
  const [element, setElement] = useState(null);
9
9
  const controller = useRef(undefined);
10
10
  const latest = useRef(resolved);
11
- latest.current = resolved;
11
+ const latestDiagnostics = useRef(diagnostics);
12
+ useEffect(() => {
13
+ latest.current = resolved;
14
+ latestDiagnostics.current = diagnostics;
15
+ }, [resolved, diagnostics]);
16
+ const decisionsEnabled = !!diagnostics;
17
+ const runtimeDiagnosticsEnabled = !!diagnostics?.onDiagnostic;
12
18
  const ref = useCallback((next) => { setElement(next); }, []);
13
19
  useEffect(() => {
14
20
  if (!element)
15
21
  return;
16
- const mounted = mountJuliyaScope(element, latest.current);
22
+ const mounted = mountJuliyaScope(element, latest.current, decisionsEnabled ? {
23
+ onDecision: (target, decision) => latestDiagnostics.current?.onDecision(target, decision),
24
+ onDiagnostic: runtimeDiagnosticsEnabled ? (target, event) => latestDiagnostics.current?.onDiagnostic?.(target, event) : undefined,
25
+ } : undefined);
17
26
  controller.current = mounted;
18
27
  return () => {
19
28
  mounted.destroy();
20
29
  if (controller.current === mounted)
21
30
  controller.current = undefined;
22
31
  };
23
- }, [element]);
32
+ }, [element, decisionsEnabled, runtimeDiagnosticsEnabled]);
24
33
  useEffect(() => { controller.current?.update(resolved); }, [resolved]);
25
34
  return { ref, refresh: () => controller.current?.refresh() };
26
35
  };
27
- export const JuliyaScope = ({ as: Tag = "div", html, config, ...props }) => {
28
- const { ref } = useJuliyaScope(config);
36
+ export const JuliyaScope = ({ as: Tag = "div", html, config, diagnostics, ...props }) => {
37
+ const { ref } = useJuliyaScope(config, diagnostics);
29
38
  return _jsx(Tag, { ...props, ref: ref, dangerouslySetInnerHTML: { __html: html } }, html);
30
39
  };
@@ -9,7 +9,7 @@ export interface UseKowrapOptions extends KowrapOptions {
9
9
  tag?: TextTag;
10
10
  }
11
11
  export type UseJuliyaOptions = UseKowrapOptions;
12
- export declare const useJuliya: ({ text, locale: explicitLocale, strategy: explicitStrategy, breakLongWords: explicitBreakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks, onForcedBreaksChange, style, className, tag, }: UseJuliyaOptions) => {
12
+ export declare const useJuliya: ({ text, locale: explicitLocale, strategy: explicitStrategy, breakLongWords: explicitBreakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks, onForcedBreaksChange, style, className, tag, onDiagnostic, }: UseJuliyaOptions) => {
13
13
  locale: import("../../index.js").WrapLocale;
14
14
  forcedBreaks: readonly number[];
15
15
  setForcedBreaks: (breaks: readonly number[]) => void;
@@ -18,7 +18,7 @@ export declare const useJuliya: ({ text, locale: explicitLocale, strategy: expli
18
18
  lines: import("../../index.js").WrappedLine[];
19
19
  measured: boolean;
20
20
  };
21
- export declare const useKowrap: ({ text, locale: explicitLocale, strategy: explicitStrategy, breakLongWords: explicitBreakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks, onForcedBreaksChange, style, className, tag, }: UseJuliyaOptions) => {
21
+ export declare const useKowrap: ({ text, locale: explicitLocale, strategy: explicitStrategy, breakLongWords: explicitBreakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks, onForcedBreaksChange, style, className, tag, onDiagnostic, }: UseJuliyaOptions) => {
22
22
  locale: import("../../index.js").WrapLocale;
23
23
  forcedBreaks: readonly number[];
24
24
  setForcedBreaks: (breaks: readonly number[]) => void;
@@ -2,11 +2,11 @@ import { useCallback, useState } from "react";
2
2
  import { manualLines } from "../../core/segmentation.js";
3
3
  import { useWrapLayout } from "./use-wrap-layout.js";
4
4
  import { useJuliyaDefaults } from "./juliya-provider.js";
5
- export const useJuliya = ({ text, locale: explicitLocale, strategy: explicitStrategy, breakLongWords: explicitBreakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks = [], onForcedBreaksChange, style, className, tag = "span", }) => {
5
+ export const useJuliya = ({ text, locale: explicitLocale, strategy: explicitStrategy, breakLongWords: explicitBreakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks = [], onForcedBreaksChange, style, className, tag = "span", onDiagnostic, }) => {
6
6
  const { locale, strategy = "balanced", breakLongWords = true } = useJuliyaDefaults({ locale: explicitLocale, strategy: explicitStrategy, breakLongWords: explicitBreakLongWords });
7
7
  const [internal, setInternal] = useState({ text, breaks: initialForcedBreaks });
8
8
  const forcedBreaks = controlledBreaks ?? (internal.text === text ? internal.breaks : []);
9
- const layout = useWrapLayout({ text, locale, strategy, breakLongWords, forcedBreaks, style, className, tag });
9
+ const layout = useWrapLayout({ text, locale, strategy, breakLongWords, forcedBreaks, style, className, tag, onDiagnostic });
10
10
  const setForcedBreaks = useCallback((breaks) => {
11
11
  manualLines(text, breaks);
12
12
  if (controlledBreaks === undefined)
@@ -1,5 +1,6 @@
1
1
  import type { CSSProperties } from "react";
2
2
  import type { WrapOptions, WrappedLine } from "../../core/types.js";
3
+ import type { JuliyaDiagnosticCallback } from "../../dom/types.js";
3
4
  import type { TextTag } from "./types.js";
4
5
  interface LayoutOptions {
5
6
  text: string;
@@ -10,6 +11,7 @@ interface LayoutOptions {
10
11
  style?: CSSProperties;
11
12
  className?: string;
12
13
  tag: TextTag;
14
+ onDiagnostic?: JuliyaDiagnosticCallback;
13
15
  }
14
16
  export declare const useWrapLayout: (options: LayoutOptions) => {
15
17
  ref: (element: HTMLElement | null) => void;
@@ -6,7 +6,10 @@ const keyOf = (forcedBreaks) => forcedBreaks?.join(",") ?? "";
6
6
  const matches = (layout, { text, locale, strategy, breakLongWords, forcedBreaks }) => layout?.text === text && layout.locale === locale && layout.strategy === strategy && layout.breakLongWords === breakLongWords && layout.breakKey === keyOf(forcedBreaks);
7
7
  const sameBreaks = (previous, next) => previous.length === next.length && previous.every((line, index) => line.end === next[index]?.end && line.width === next[index]?.width);
8
8
  export const useWrapLayout = (options) => {
9
- const { text, locale, strategy, breakLongWords, forcedBreaks, style, className, tag } = options;
9
+ const { text, locale, strategy, breakLongWords, forcedBreaks, style, className, tag, onDiagnostic } = options;
10
+ const diagnosticRef = useRef(onDiagnostic);
11
+ useEffect(() => { diagnosticRef.current = onDiagnostic; }, [onDiagnostic]);
12
+ const diagnosticsEnabled = !!onDiagnostic;
10
13
  const breakKey = keyOf(forcedBreaks);
11
14
  const fallback = useMemo(() => manualLines(text, forcedBreaks), [text, breakKey]);
12
15
  const elementRef = useRef(null);
@@ -23,12 +26,12 @@ export const useWrapLayout = (options) => {
23
26
  const element = elementRef.current;
24
27
  if (!element)
25
28
  return;
26
- const controller = observeKowrap(element, { text, locale, strategy, breakLongWords, forcedBreaks }, ({ lines, measured }) => {
29
+ const controller = observeKowrap(element, { text, locale, strategy, breakLongWords, forcedBreaks, onDiagnostic: diagnosticsEnabled ? event => diagnosticRef.current?.(event) : undefined }, ({ lines, measured }) => {
27
30
  setLayout((previous) => matches(previous, { text, locale, strategy, breakLongWords, forcedBreaks, tag }) && previous.measured === measured && sameBreaks(previous.lines, lines)
28
31
  ? previous : { text, locale, strategy, breakLongWords, breakKey, measured, lines });
29
32
  });
30
33
  return controller.destroy;
31
- }, [text, locale, strategy, breakLongWords, breakKey, style, className, tag]);
34
+ }, [text, locale, strategy, breakLongWords, breakKey, style, className, tag, diagnosticsEnabled]);
32
35
  const current = matches(layout, options) ? layout : undefined;
33
36
  return { ref, lines: current?.lines ?? fallback, measured: current?.measured ?? false };
34
37
  };
@@ -1,5 +1,6 @@
1
1
  import type { ReactNode } from "react";
2
2
  import type { WrapOptions } from "../../core/types.js";
3
+ import type { JuliyaDiagnosticCallback } from "../../dom/types.js";
3
4
  import type { TextProps } from "./types.js";
4
5
  export interface WrapTextProps extends Omit<TextProps, "children"> {
5
6
  children: ReactNode;
@@ -7,6 +8,7 @@ export interface WrapTextProps extends Omit<TextProps, "children"> {
7
8
  strategy?: WrapOptions["strategy"];
8
9
  breakLongWords?: boolean;
9
10
  forcedBreaks?: readonly number[];
11
+ onDiagnostic?: JuliyaDiagnosticCallback;
10
12
  }
11
13
  export type JuliyaTextProps = WrapTextProps;
12
14
  export declare const JuliyaText: (props: JuliyaTextProps) => import("react").JSX.Element;
@@ -12,8 +12,8 @@ const baseStyle = {
12
12
  overflowWrap: "anywhere",
13
13
  textWrap: "pretty",
14
14
  };
15
- const PlainText = ({ children, as: Tag = "span", locale, strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, ...props }) => {
16
- const { ref, lines } = useWrapLayout({ text: children, locale, strategy, breakLongWords, forcedBreaks, style, className, tag: Tag });
15
+ const PlainText = ({ children, as: Tag = "span", locale, strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, onDiagnostic, ...props }) => {
16
+ const { ref, lines } = useWrapLayout({ text: children, locale, strategy, breakLongWords, forcedBreaks, style, className, tag: Tag, onDiagnostic });
17
17
  return _jsx(Tag, { ...props, lang: props.lang ?? locale, className: className, style: { ...baseStyle, overflowWrap: breakLongWords ? "anywhere" : "normal", ...style }, "data-juliya-managed": "", ref: ref, children: lines.length > 1 ? lines.map((line, index) => _jsxs(Fragment, { children: [line.text, line.breakAfter || (index < lines.length - 1 ? _jsx("br", {}) : null)] }, line.start)) : children });
18
18
  };
19
19
  const inlineText = (children) => Children.toArray(children).map((child) => {
@@ -53,8 +53,11 @@ const renderInline = (children, offsets) => {
53
53
  });
54
54
  return visit(children);
55
55
  };
56
- const InlineText = ({ children, as: Tag = "span", locale, strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, ...props }) => {
56
+ const InlineText = ({ children, as: Tag = "span", locale, strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, onDiagnostic, ...props }) => {
57
57
  const ref = useRef(null);
58
+ const diagnosticRef = useRef(onDiagnostic);
59
+ useEffect(() => { diagnosticRef.current = onDiagnostic; }, [onDiagnostic]);
60
+ const diagnosticsEnabled = !!onDiagnostic;
58
61
  const text = inlineText(children);
59
62
  const key = `${text}:${locale ?? "ko"}:${forcedBreaks?.join(",") ?? ""}`;
60
63
  const [layout, setLayout] = useState();
@@ -62,11 +65,11 @@ const InlineText = ({ children, as: Tag = "span", locale, strategy = "balanced",
62
65
  useEffect(() => {
63
66
  if (!ref.current)
64
67
  return;
65
- const observer = observeInline(ref.current, () => ({ inline: true, locale, strategy, breakLongWords, forcedBreaks }), (next) => {
68
+ const observer = observeInline(ref.current, () => ({ inline: true, locale, strategy, breakLongWords, forcedBreaks, onDiagnostic: diagnosticsEnabled ? event => diagnosticRef.current?.(event) : undefined }), (next) => {
66
69
  setLayout((previous) => previous?.key === key && previous.offsets.join(",") === next.join(",") ? previous : { key, offsets: next });
67
70
  });
68
71
  return observer.destroy;
69
- }, [key, children, locale, strategy, breakLongWords, style, className, Tag]);
72
+ }, [key, children, locale, strategy, breakLongWords, style, className, Tag, diagnosticsEnabled]);
70
73
  return _jsx(Tag, { ...props, lang: props.lang ?? locale, className: className, style: { ...baseStyle, overflowWrap: breakLongWords ? "anywhere" : "normal", ...style }, "data-juliya-managed": "", ref: (element) => { ref.current = element; }, children: renderInline(children, offsets) });
71
74
  };
72
75
  export const JuliyaText = (props) => {
@@ -0,0 +1,2 @@
1
+ import type { JuliyaDiagnosticCallback, JuliyaRuntimeDiagnostic } from "./types.js";
2
+ export declare const emitDiagnostic: (callback: JuliyaDiagnosticCallback, event: JuliyaRuntimeDiagnostic) => void;
@@ -0,0 +1,6 @@
1
+ export const emitDiagnostic = (callback, event) => {
2
+ try {
3
+ callback(event);
4
+ }
5
+ catch { /* Diagnostic observers must not interrupt wrapping. */ }
6
+ };
@@ -1,3 +1,4 @@
1
+ export type { JuliyaDiagnosticCallback, JuliyaRuntimeDiagnostic, JuliyaMeasurementDiagnostic, JuliyaMeasurementCause, JuliyaWrappingDiagnostic } from "./types.js";
1
2
  export type { CanvasMeasureOptions } from "./measure.js";
2
3
  export { createCanvasMeasure } from "./measure.js";
3
4
  export type { KowrapController, KowrapLayout, KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "./types.js";
@@ -7,4 +8,4 @@ export type { KowrapController as JuliyaController, KowrapLayout as JuliyaLayout
7
8
  export { observeKowrap as observeJuliya } from "./observe.js";
8
9
  export { mountKowrap as mountJuliya } from "./render.js";
9
10
  export { mountJuliyaScope } from "./scope.js";
10
- export type { JuliyaScopeController, JuliyaScopeDecision, JuliyaScopeDiagnostics } from "./scope.js";
11
+ export type { JuliyaScopeController, JuliyaScopeDecision, JuliyaScopeDiagnostics, JuliyaOptionSource, JuliyaOptionSources } from "./scope.js";
@@ -1,6 +1,7 @@
1
1
  import { manualLines } from "../core/segmentation.js";
2
- import { wrap } from "../core/wrap.js";
2
+ import { wrap, wrapWithDiagnostics } from "../core/wrap.js";
3
3
  import { createLocalizedCanvasMeasure, languageOf } from "./measure.js";
4
+ import { emitDiagnostic } from "./diagnostics.js";
4
5
  import { fontOf, observeElementLayout } from "./observe-element.js";
5
6
  export const inlineBreakAttribute = "data-kowrap-break";
6
7
  export const readInline = (element) => {
@@ -47,12 +48,16 @@ const readStyledRuns = (element) => {
47
48
  };
48
49
  export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) => {
49
50
  let previous;
51
+ let active = true;
50
52
  let forceAuthorRead = false;
51
53
  const observer = observeElementLayout(element, (layout, fromWindowResize) => {
52
54
  const options = getOptions();
55
+ const diagnostic = options.onDiagnostic;
53
56
  if (!layout) {
54
57
  previous = undefined;
55
58
  onBreaks(breakOffsets(manualLines(readInline(element).text, options.forcedBreaks)));
59
+ if (diagnostic)
60
+ emitDiagnostic(diagnostic, { phase: "wrapping", status: "fallback", reason: "measurement-unavailable", locale: options.locale ?? "ko", strategy: options.strategy ?? "balanced" });
56
61
  return;
57
62
  }
58
63
  const { locale, strategy, breakLongWords, forcedBreaks, protectInlineCode } = options;
@@ -62,6 +67,8 @@ export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) =
62
67
  // Generated breaks can mask structural CSS changes during a viewport resize.
63
68
  if (!forceAuthorRead && !fromWindowResize && previous?.signature === signature && previous.measure === layout.measure) {
64
69
  onBreaks(previous.offsets);
70
+ if (diagnostic)
71
+ emitDiagnostic(diagnostic, { phase: "wrapping", status: "reused", locale: locale ?? "ko", strategy: strategy ?? "balanced", width: layout.width });
65
72
  return;
66
73
  }
67
74
  const author = readAuthorMarkup ? readAuthorMarkup(() => readStyledRuns(element)) : rendered;
@@ -70,6 +77,8 @@ export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) =
70
77
  if (previous?.authorSignature === authorSignature && previous.measure === layout.measure) {
71
78
  onBreaks(previous.offsets);
72
79
  previous.signature = readAuthorMarkup ? signatureOf(readStyledRuns(element)) : signature;
80
+ if (diagnostic)
81
+ emitDiagnostic(diagnostic, { phase: "wrapping", status: "reused", locale: locale ?? "ko", strategy: strategy ?? "balanced", width: layout.width });
73
82
  return;
74
83
  }
75
84
  const measures = new Map();
@@ -81,7 +90,10 @@ export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) =
81
90
  const right = Math.min(end, run.end);
82
91
  return left < right ? width + measures.get(run.key)(text.slice(left, right)) : width;
83
92
  }, 0);
84
- let offsets = breakOffsets(wrap(text, { ...options, ...layout, measureRange }));
93
+ const wrapOptions = { ...options, ...layout, measureRange };
94
+ const result = diagnostic ? wrapWithDiagnostics(text, wrapOptions) : undefined;
95
+ let offsets = breakOffsets(result?.lines ?? wrap(text, wrapOptions));
96
+ let protectedFallback = false;
85
97
  if (protectInlineCode) {
86
98
  const ranges = new Map();
87
99
  for (const run of readInline(element).runs) {
@@ -95,15 +107,21 @@ export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) =
95
107
  ranges.set(code, { start: run.start, end: run.end });
96
108
  }
97
109
  // If the planner chose a protected boundary, retain native wrapping for this paragraph.
98
- if (offsets.some(offset => [...ranges.values()].some(range => range.start < offset && offset <= range.end)))
110
+ if (offsets.some(offset => [...ranges.values()].some(range => range.start < offset && offset <= range.end))) {
111
+ protectedFallback = true;
99
112
  offsets = [];
113
+ }
100
114
  }
101
115
  onBreaks(offsets);
102
116
  previous = { signature: readAuthorMarkup ? signatureOf(readStyledRuns(element)) : signature, authorSignature, measure: layout.measure, offsets };
103
- });
117
+ if (diagnostic)
118
+ emitDiagnostic(diagnostic, { phase: "wrapping", status: protectedFallback ? "fallback" : "computed", reason: protectedFallback ? "protected-inline-code" : undefined, locale: locale ?? "ko", strategy: strategy ?? "balanced", width: layout.width, plan: result?.diagnostics });
119
+ }, false, () => getOptions().onDiagnostic);
104
120
  return {
105
121
  ...observer,
106
122
  refresh: (force = true) => {
123
+ if (!active)
124
+ return;
107
125
  forceAuthorRead = force;
108
126
  try {
109
127
  observer.refresh();
@@ -112,10 +130,18 @@ export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) =
112
130
  forceAuthorRead = false;
113
131
  }
114
132
  },
133
+ destroy: () => {
134
+ if (!active)
135
+ return;
136
+ active = false;
137
+ previous = undefined;
138
+ observer.destroy();
139
+ },
115
140
  };
116
141
  };
117
142
  export const mountInline = (element, initial) => {
118
143
  let options = initial;
144
+ let active = true;
119
145
  let undo = [];
120
146
  let previous = [];
121
147
  const generated = new Set();
@@ -193,15 +219,30 @@ export const mountInline = (element, initial) => {
193
219
  mutations.observe(element, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["class", "style", "lang"] });
194
220
  }
195
221
  const refresh = () => {
222
+ if (!active)
223
+ return;
196
224
  const records = mutations?.takeRecords() ?? [];
197
225
  if (records.some((record) => record.type !== "attributes"))
198
226
  restore();
199
227
  observer.refresh();
200
228
  };
201
229
  return {
202
- update: (next) => { options = next; refresh(); },
230
+ update: (next) => { if (active) {
231
+ options = next;
232
+ refresh();
233
+ } },
203
234
  refresh,
204
- destroy: () => { observer.destroy(); mutations?.disconnect(); restore(); },
205
- restore,
235
+ destroy: () => {
236
+ if (!active)
237
+ return;
238
+ active = false;
239
+ observer.destroy();
240
+ mutations?.disconnect();
241
+ restore();
242
+ mutations = undefined;
243
+ options = { inline: true };
244
+ },
245
+ restore: () => { if (active)
246
+ restore(); },
206
247
  };
207
248
  };
@@ -1,11 +1,12 @@
1
1
  import type { CanvasMeasureOptions } from "./measure.js";
2
2
  import type { Measure } from "../core/types.js";
3
+ import type { JuliyaDiagnosticCallback } from "./types.js";
3
4
  export interface ElementLayout {
4
5
  width: number;
5
6
  measure: Measure;
6
7
  }
7
8
  export declare const fontOf: (computed: CSSStyleDeclaration) => CanvasMeasureOptions;
8
- export declare const observeElementLayout: (element: HTMLElement, onLayout: (layout: ElementLayout | undefined, fromWindowResize: boolean) => void, skipUnchangedResize?: boolean) => {
9
+ export declare const observeElementLayout: (element: HTMLElement, onLayout: (layout: ElementLayout | undefined, fromWindowResize: boolean) => void, skipUnchangedResize?: boolean, getDiagnostic?: () => JuliyaDiagnosticCallback | undefined) => {
9
10
  refresh: () => void;
10
11
  destroy: () => void;
11
12
  };
@@ -1,4 +1,5 @@
1
1
  import { createLocalizedCanvasMeasure, languageOf } from "./measure.js";
2
+ import { emitDiagnostic } from "./diagnostics.js";
2
3
  const numericLength = (value) => {
3
4
  const parsed = Number.parseFloat(value);
4
5
  return Number.isFinite(parsed) ? parsed : 0;
@@ -18,12 +19,22 @@ export const fontOf = (computed) => ({
18
19
  wordSpacing: spacing(computed.wordSpacing),
19
20
  fontKerning: computed.fontKerning,
20
21
  });
21
- export const observeElementLayout = (element, onLayout, skipUnchangedResize = false) => {
22
+ export const observeElementLayout = (element, onLayout, skipUnchangedResize = false, getDiagnostic) => {
22
23
  const doc = element.ownerDocument;
23
24
  const view = doc.defaultView;
24
25
  if (!view) {
25
- onLayout(undefined, false);
26
- return { refresh: () => onLayout(undefined, false), destroy: () => { } };
26
+ let active = true;
27
+ const unavailable = (cause) => {
28
+ if (!active)
29
+ return;
30
+ const diagnostic = getDiagnostic?.();
31
+ if (diagnostic)
32
+ emitDiagnostic(diagnostic, { phase: "measurement", cause, status: "unavailable", measureCache: "unavailable", reason: "no-window", durationMs: 0 });
33
+ if (active)
34
+ onLayout(undefined, false);
35
+ };
36
+ unavailable("initial");
37
+ return { refresh: () => unavailable("refresh"), destroy: () => { active = false; } };
27
38
  }
28
39
  let active = true;
29
40
  let previousFont;
@@ -32,10 +43,14 @@ export const observeElementLayout = (element, onLayout, skipUnchangedResize = fa
32
43
  let frame;
33
44
  let published = false;
34
45
  let lastLayout;
35
- const update = (contentWidth, fromObserver = false, fromWindowResize = false) => {
46
+ const update = (contentWidth, fromObserver = false, fromWindowResize = false, cause = "initial") => {
36
47
  if (!active)
37
48
  return;
38
49
  let layout;
50
+ const diagnostic = getDiagnostic?.();
51
+ const started = diagnostic ? performance.now() : 0;
52
+ let measureCache = "unavailable";
53
+ let reason;
39
54
  try {
40
55
  const computed = view.getComputedStyle(element);
41
56
  const padding = numericLength(computed.paddingLeft) + numericLength(computed.paddingRight);
@@ -49,7 +64,7 @@ export const observeElementLayout = (element, onLayout, skipUnchangedResize = fa
49
64
  ? computedContentWidth(computed, padding, fallback) ?? Math.max(1, fallback - 1)
50
65
  : 0);
51
66
  if (!(width > 0)) {
52
- layout = undefined;
67
+ reason = "nonpositive-width";
53
68
  }
54
69
  else {
55
70
  const font = fontOf(computed);
@@ -58,14 +73,20 @@ export const observeElementLayout = (element, onLayout, skipUnchangedResize = fa
58
73
  if (!measure || previousFont !== signature) {
59
74
  measure = createLocalizedCanvasMeasure(font, doc, language);
60
75
  previousFont = signature;
76
+ measureCache = "created";
61
77
  }
78
+ else
79
+ measureCache = "reused";
62
80
  layout = { width, measure };
63
81
  }
64
82
  }
65
83
  catch {
66
- layout = undefined;
84
+ reason = "measurement-error";
67
85
  }
68
- if (skipUnchangedResize && fromObserver && published && layout?.width === lastLayout?.width && layout?.measure === lastLayout?.measure)
86
+ const unchanged = skipUnchangedResize && fromObserver && published && layout?.width === lastLayout?.width && layout?.measure === lastLayout?.measure;
87
+ if (diagnostic)
88
+ emitDiagnostic(diagnostic, { phase: "measurement", cause, status: unchanged ? "unchanged" : layout ? "ready" : "unavailable", width: layout?.width, measureCache, reason, durationMs: performance.now() - started });
89
+ if (!active || unchanged)
69
90
  return;
70
91
  published = true;
71
92
  lastLayout = layout;
@@ -74,6 +95,7 @@ export const observeElementLayout = (element, onLayout, skipUnchangedResize = fa
74
95
  let pendingWidth;
75
96
  let pendingRefresh = false;
76
97
  let pendingWindowResize = false;
98
+ let pendingFonts = false;
77
99
  const schedule = (width, cause = "observer") => {
78
100
  if (!active)
79
101
  return;
@@ -81,24 +103,29 @@ export const observeElementLayout = (element, onLayout, skipUnchangedResize = fa
81
103
  pendingWidth = width;
82
104
  pendingRefresh ||= cause !== "observer";
83
105
  pendingWindowResize ||= cause === "window";
106
+ pendingFonts ||= cause === "fonts";
84
107
  const flush = () => {
85
108
  frame = undefined;
86
109
  const nextWidth = pendingWidth;
87
110
  const fromObserver = !pendingRefresh;
88
111
  const fromWindowResize = pendingWindowResize;
112
+ const diagnosticCause = pendingFonts ? "font" : fromWindowResize ? "window-resize" : "resize";
113
+ pendingFonts = false;
89
114
  pendingWidth = undefined;
90
115
  pendingRefresh = false;
91
116
  pendingWindowResize = false;
92
- update(nextWidth, fromObserver, fromWindowResize);
117
+ update(nextWidth, fromObserver, fromWindowResize, diagnosticCause);
93
118
  };
94
119
  if (!view.requestAnimationFrame)
95
120
  flush();
96
121
  else if (frame === undefined)
97
122
  frame = view.requestAnimationFrame(flush);
98
123
  };
99
- const refresh = () => update();
124
+ const refresh = () => update(undefined, false, false, "refresh");
100
125
  const onResize = () => schedule(undefined, "window");
101
126
  const onFonts = () => {
127
+ if (!active)
128
+ return;
102
129
  measure = undefined;
103
130
  schedule(undefined, "fonts");
104
131
  };
@@ -112,9 +139,21 @@ export const observeElementLayout = (element, onLayout, skipUnchangedResize = fa
112
139
  void doc.fonts?.ready.then(onFonts);
113
140
  update();
114
141
  const destroy = () => {
142
+ if (!active)
143
+ return;
115
144
  active = false;
116
145
  if (frame !== undefined)
117
146
  view.cancelAnimationFrame(frame);
147
+ frame = undefined;
148
+ measure = undefined;
149
+ previousFont = undefined;
150
+ observedWidth = undefined;
151
+ lastLayout = undefined;
152
+ pendingWidth = undefined;
153
+ pendingRefresh = false;
154
+ pendingWindowResize = false;
155
+ pendingFonts = false;
156
+ published = false;
118
157
  observer?.disconnect();
119
158
  view.removeEventListener("resize", onResize);
120
159
  doc.fonts?.removeEventListener("loadingdone", onFonts);
@@ -1,5 +1,6 @@
1
1
  import { manualLines } from "../core/segmentation.js";
2
- import { wrap } from "../core/wrap.js";
2
+ import { wrap, wrapWithDiagnostics } from "../core/wrap.js";
3
+ import { emitDiagnostic } from "./diagnostics.js";
3
4
  import { observeElementLayout } from "./observe-element.js";
4
5
  export const observeKowrap = (element, initial, onLayout) => {
5
6
  if (initial.inline)
@@ -8,13 +9,23 @@ export const observeKowrap = (element, initial, onLayout) => {
8
9
  let active = true;
9
10
  let fallback = manualLines(options.text, options.forcedBreaks);
10
11
  const observer = observeElementLayout(element, (measurement) => {
12
+ const diagnostic = options.onDiagnostic;
11
13
  if (!measurement) {
12
14
  onLayout({ lines: fallback, measured: false });
15
+ if (active && diagnostic)
16
+ emitDiagnostic(diagnostic, { phase: "wrapping", status: "fallback", reason: "measurement-unavailable", locale: options.locale ?? "ko", strategy: options.strategy ?? "balanced" });
13
17
  return;
14
18
  }
15
- const lines = wrap(options.text, { ...options, ...measurement });
16
- onLayout({ lines, measured: true });
17
- }, true);
19
+ const wrapOptions = { ...options, ...measurement };
20
+ if (diagnostic) {
21
+ const result = wrapWithDiagnostics(options.text, wrapOptions);
22
+ onLayout({ lines: result.lines, measured: true });
23
+ if (active)
24
+ emitDiagnostic(diagnostic, { phase: "wrapping", status: "computed", locale: result.diagnostics.locale, strategy: result.diagnostics.strategy, width: measurement.width, plan: result.diagnostics });
25
+ }
26
+ else
27
+ onLayout({ lines: wrap(options.text, wrapOptions), measured: true });
28
+ }, true, () => options.onDiagnostic);
18
29
  return {
19
30
  update: (next) => {
20
31
  if (!active)
@@ -32,6 +43,8 @@ export const observeKowrap = (element, initial, onLayout) => {
32
43
  return;
33
44
  active = false;
34
45
  observer.destroy();
46
+ fallback = [];
47
+ options = { text: "" };
35
48
  },
36
49
  };
37
50
  };
@@ -48,8 +48,11 @@ export const mountElement = (element, initial) => {
48
48
  const restoreStyles = captureStyles(element);
49
49
  Object.assign(element.style, wrapStyles, { overflowWrap: initial.breakLongWords === false ? "normal" : "anywhere" });
50
50
  const controller = mountInline(element, initial);
51
- return { ...controller, update: (next) => { if (!next.inline)
52
- throw new TypeError("Cannot change inline mode"); element.style.overflowWrap = next.breakLongWords === false ? "normal" : "anywhere"; controller.update(next); }, destroy: () => { controller.destroy(); restoreStyles(); } };
51
+ let active = true;
52
+ return { ...controller, update: (next) => { if (!active)
53
+ return; if (!next.inline)
54
+ throw new TypeError("Cannot change inline mode"); element.style.overflowWrap = next.breakLongWords === false ? "normal" : "anywhere"; controller.update(next); }, destroy: () => { if (!active)
55
+ return; active = false; controller.destroy(); restoreStyles(); } };
53
56
  }
54
57
  const initialLines = manualLines(initial.text, initial.forcedBreaks);
55
58
  const style = element.style;
@@ -85,6 +88,8 @@ export const mountElement = (element, initial) => {
85
88
  observer.destroy();
86
89
  restoreStyles();
87
90
  element.textContent = options.text;
91
+ previousLines = undefined;
92
+ options = { text: "" };
88
93
  },
89
94
  };
90
95
  };
@@ -1,11 +1,17 @@
1
1
  import type { JuliyaConfig, JuliyaDefaults } from "../core/config.js";
2
+ import type { JuliyaRuntimeDiagnostic } from "./types.js";
3
+ export type JuliyaOptionSource = "library" | "scope" | "rule" | "css" | "attribute";
4
+ export type JuliyaOptionSources = Record<keyof JuliyaDefaults, JuliyaOptionSource>;
2
5
  export interface JuliyaScopeDecision {
3
6
  status: "mounted" | "updated" | "skipped" | "unmounted";
4
7
  reason?: "excluded" | "nested-scope" | "managed" | "unsupported-markup" | "empty" | "no-longer-matches" | "destroyed" | "ownership-transferred";
5
8
  options?: JuliyaDefaults;
9
+ sources?: JuliyaOptionSources;
10
+ resolvedOptions?: Required<JuliyaDefaults>;
6
11
  }
7
12
  export interface JuliyaScopeDiagnostics {
8
13
  onDecision: (element: HTMLElement, decision: JuliyaScopeDecision) => void;
14
+ onDiagnostic?: (element: HTMLElement, event: JuliyaRuntimeDiagnostic) => void;
9
15
  }
10
16
  export interface JuliyaScopeController {
11
17
  refresh: () => void;
package/dist/dom/scope.js CHANGED
@@ -33,6 +33,22 @@ const parseElementOptions = (locale, strategy, breakLongWords) => {
33
33
  return result;
34
34
  };
35
35
  const attributes = (element) => parseElementOptions(element.getAttribute("data-juliya-locale"), element.getAttribute("data-juliya-strategy"), element.getAttribute("data-juliya-break-long-words"));
36
+ const optionSources = (config, element, css, data) => {
37
+ const sources = { locale: "library", strategy: "library", breakLongWords: "library" };
38
+ const apply = (layer, source) => {
39
+ for (const key of ["locale", "strategy", "breakLongWords"])
40
+ if (layer[key] !== undefined)
41
+ sources[key] = source;
42
+ };
43
+ apply(config, "scope");
44
+ for (const rule of config.rules ?? [])
45
+ if (element.matches(rule.selector))
46
+ apply(rule, "rule");
47
+ apply(css, "css");
48
+ apply(data, "attribute");
49
+ return sources;
50
+ };
51
+ const resolvedOptions = (options) => ({ locale: options.locale ?? "ko", strategy: options.strategy ?? "balanced", breakLongWords: options.breakLongWords !== false });
36
52
  const cssOptions = (element) => {
37
53
  const style = element.ownerDocument.defaultView?.getComputedStyle(element);
38
54
  return parseElementOptions(style?.getPropertyValue("--juliya-locale").trim() ?? null, style?.getPropertyValue("--juliya-strategy").trim() ?? null, style?.getPropertyValue("--juliya-break-long-words").trim() ?? null);
@@ -99,22 +115,40 @@ export const mountJuliyaScope = (root, initial = {}, diagnostics) => {
99
115
  for (const element of wanted) {
100
116
  if (!active)
101
117
  return;
102
- const options = resolveJuliyaDefaults(resolveJuliyaRules(config, selector => element.matches(selector)), cssOptions(element), attributes(element));
118
+ const css = cssOptions(element);
119
+ const data = attributes(element);
120
+ const options = resolveJuliyaDefaults(resolveJuliyaRules(config, selector => element.matches(selector)), css, data);
103
121
  const key = JSON.stringify(options);
122
+ const sources = emit ? optionSources(config, element, css, data) : undefined;
123
+ const sourceKey = sources ? JSON.stringify(sources) : undefined;
104
124
  const item = mounted.get(element);
105
125
  if (item) {
106
126
  if (item.key !== key) {
107
127
  item.key = key;
108
- item.controller.update({ inline: true, protectInlineCode: true, ...options });
109
- emit?.(element, { status: "updated", options });
128
+ item.sourceKey = sourceKey;
129
+ const onDiagnostic = diagnostics?.onDiagnostic ? (event) => diagnostics.onDiagnostic?.(element, event) : undefined;
130
+ item.controller.update({ inline: true, protectInlineCode: true, ...options, onDiagnostic });
131
+ if (active)
132
+ emit?.(element, { status: "updated", options, sources, resolvedOptions: resolvedOptions(options) });
133
+ }
134
+ else if (emit && item.sourceKey !== sourceKey) {
135
+ item.sourceKey = sourceKey;
136
+ emit(element, { status: "updated", options, sources, resolvedOptions: resolvedOptions(options) });
110
137
  }
111
138
  continue;
112
139
  }
113
140
  if (!claimScoped(element, () => detach(element, "ownership-transferred")))
114
141
  continue;
115
142
  try {
116
- mounted.set(element, { controller: mountElement(element, { inline: true, protectInlineCode: true, ...options }), key });
117
- emit?.(element, { status: "mounted", options });
143
+ const onDiagnostic = diagnostics?.onDiagnostic ? (event) => diagnostics.onDiagnostic?.(element, event) : undefined;
144
+ const mountedController = mountElement(element, { inline: true, protectInlineCode: true, ...options, onDiagnostic });
145
+ if (!active) {
146
+ mountedController.destroy();
147
+ releaseScoped(element);
148
+ return;
149
+ }
150
+ mounted.set(element, { controller: mountedController, key, sourceKey });
151
+ emit?.(element, { status: "mounted", options, sources, resolvedOptions: resolvedOptions(options) });
118
152
  }
119
153
  catch (error) {
120
154
  releaseScoped(element);
@@ -1,12 +1,14 @@
1
- import type { WrapOptions, WrappedLine } from "../core/types.js";
1
+ import type { WrapOptions, WrappedLine, WrapDiagnostics, WrapLocale } from "../core/types.js";
2
2
  export interface KowrapOptions extends Pick<WrapOptions, "strategy" | "breakLongWords" | "forcedBreaks" | "locale"> {
3
3
  text: string;
4
4
  inline?: false;
5
+ onDiagnostic?: JuliyaDiagnosticCallback;
5
6
  }
6
7
  export interface InlineKowrapOptions extends Pick<WrapOptions, "strategy" | "breakLongWords" | "forcedBreaks" | "locale"> {
7
8
  inline: true;
8
9
  text?: never;
9
10
  protectInlineCode?: boolean;
11
+ onDiagnostic?: JuliyaDiagnosticCallback;
10
12
  }
11
13
  export type MountKowrapOptions = KowrapOptions | InlineKowrapOptions;
12
14
  export interface KowrapController {
@@ -19,3 +21,25 @@ export interface KowrapLayout {
19
21
  lines: WrappedLine[];
20
22
  measured: boolean;
21
23
  }
24
+ export type JuliyaMeasurementCause = "initial" | "refresh" | "resize" | "window-resize" | "font";
25
+ export interface JuliyaMeasurementDiagnostic {
26
+ phase: "measurement";
27
+ cause: JuliyaMeasurementCause;
28
+ status: "ready" | "unchanged" | "unavailable";
29
+ width?: number;
30
+ measureCache: "created" | "reused" | "unavailable";
31
+ reason?: "no-window" | "nonpositive-width" | "measurement-error";
32
+ durationMs: number;
33
+ }
34
+ export interface JuliyaWrappingDiagnostic {
35
+ phase: "wrapping";
36
+ status: "computed" | "reused" | "fallback";
37
+ locale: WrapLocale;
38
+ strategy: NonNullable<WrapOptions["strategy"]>;
39
+ width?: number;
40
+ reason?: "measurement-unavailable" | "protected-inline-code";
41
+ /** Planned line diagnostics for new computations, not cached results or actual DOM line counts. */
42
+ plan?: WrapDiagnostics;
43
+ }
44
+ export type JuliyaRuntimeDiagnostic = JuliyaMeasurementDiagnostic | JuliyaWrappingDiagnostic;
45
+ export type JuliyaDiagnosticCallback = (event: JuliyaRuntimeDiagnostic) => void;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oddmash/juliya",
3
3
  "license": "MIT",
4
- "version": "0.5.1",
4
+ "version": "0.6.0",
5
5
  "description": "Locale-aware text wrapping for Korean, English, Japanese and Simplified Chinese",
6
6
  "homepage": "https://oddmash.github.io/juliya/",
7
7
  "keywords": ["text-wrapping", "line-breaking", "typography", "internationalization", "korean", "japanese", "chinese", "react", "vue", "svelte"],