@oddmash/juliya 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,7 +41,7 @@ The provider shares its locale with child components and hooks. An explicit loca
41
41
 
42
42
  ## Try in a browser
43
43
 
44
- Save this Korean example as `index.html` and open it in a browser with an internet connection. The standalone example uses the verified Juliya 0.4.0 CDN entry point.
44
+ Save this Korean example as `index.html` and open it in a browser with an internet connection.
45
45
 
46
46
  ```html
47
47
  <!doctype html>
@@ -50,10 +50,10 @@ Save this Korean example as `index.html` and open it in a browser with an intern
50
50
  <title>Juliya 예제</title>
51
51
  <p id="title" style="max-width: 220px; font-size: 24px">팀의 모든 문서를 한곳에서 관리하세요</p>
52
52
  <script type="module">
53
- import { mountKowrap } from 'https://cdn.jsdelivr.net/npm/@oddmash/juliya@0.4.0/dist/dom/index.js/+esm';
53
+ import { mountJuliya } from 'https://cdn.jsdelivr.net/npm/@oddmash/juliya@0.5.0/dist/dom/index.js/+esm';
54
54
 
55
55
  const title = document.getElementById('title');
56
- mountKowrap(title, { text: title.textContent });
56
+ mountJuliya(title, { text: title.textContent });
57
57
  </script>
58
58
  </html>
59
59
  ```
@@ -66,8 +66,6 @@ Save this Korean example as `index.html` and open it in a browser with an intern
66
66
  - React, Next.js, Vue, Svelte, and plain HTML support.
67
67
  - Heuristic language rules, not comprehensive natural-language analysis. Best suited to headings and short passages.
68
68
 
69
- ## Migrating from Kowrap
69
+ [Usage guide](https://oddmash.github.io/juliya/en/docs/) | [Contributing](CONTRIBUTING.md) | [MIT License](LICENSE)
70
70
 
71
- `@oddmash/kowrap@0.4.0` is the final legacy release. All future updates and fixes are published exclusively as `@oddmash/juliya`. Existing versions remain available. Switch the package name while retaining the public API and subpath imports. Compatibility names such as `mountKowrap`, `WrapText`, and `useKowrap` remain available in Juliya.
72
-
73
- [Migration and usage](https://oddmash.github.io/juliya/en/docs/) | [Contributing](CONTRIBUTING.md) | [MIT License](LICENSE)
71
+ Use `mountJuliya`, `observeJuliya`, `juliyaDirective`, and `juliya` for DOM, Vue, and Svelte integrations.
@@ -4,3 +4,5 @@ export type { UseJuliyaOptions, UseKowrapOptions } from "./use-kowrap.js";
4
4
  export { useJuliya, useKowrap } from "./use-kowrap.js";
5
5
  export type { JuliyaProviderProps } from "./juliya-provider.js";
6
6
  export { JuliyaProvider } from "./juliya-provider.js";
7
+ export type { JuliyaScopeProps } from "./juliya-scope.js";
8
+ export { JuliyaScope, useJuliyaScope } from "./juliya-scope.js";
@@ -2,3 +2,4 @@
2
2
  export { JuliyaText, WrapText } from "./wrap-text.js";
3
3
  export { useJuliya, useKowrap } from "./use-kowrap.js";
4
4
  export { JuliyaProvider } from "./juliya-provider.js";
5
+ export { JuliyaScope, useJuliyaScope } from "./juliya-scope.js";
@@ -1,8 +1,9 @@
1
1
  import type { ReactNode } from "react";
2
- import type { WrapLocale } from "../../core/types.js";
3
- export interface JuliyaProviderProps {
4
- locale?: WrapLocale;
2
+ import type { JuliyaConfig, JuliyaDefaults } from "../../core/config.js";
3
+ export interface JuliyaProviderProps extends JuliyaDefaults {
4
+ config?: JuliyaConfig;
5
5
  children: ReactNode;
6
6
  }
7
- export declare const useJuliyaLocale: (locale?: WrapLocale) => WrapLocale | undefined;
8
- export declare const JuliyaProvider: ({ locale, children }: JuliyaProviderProps) => import("react").JSX.Element;
7
+ export declare const useJuliyaConfig: (config?: JuliyaConfig) => JuliyaConfig;
8
+ export declare const useJuliyaDefaults: (options?: JuliyaDefaults) => JuliyaDefaults;
9
+ export declare const JuliyaProvider: ({ locale, strategy, breakLongWords, config, children }: JuliyaProviderProps) => import("react").JSX.Element;
@@ -1,12 +1,24 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { createContext, useContext } from "react";
4
- const LocaleContext = createContext(undefined);
5
- export const useJuliyaLocale = (locale) => {
6
- const inheritedLocale = useContext(LocaleContext);
7
- return locale ?? inheritedLocale;
3
+ import { createContext, useContext, useMemo } from "react";
4
+ import { resolveJuliyaDefaults, parseConfig } from "../../core/config.js";
5
+ const DefaultsContext = createContext({});
6
+ const mergeConfig = (inherited, local, overrides) => ({
7
+ ...resolveJuliyaDefaults(inherited, local, overrides),
8
+ include: local?.include ?? inherited.include,
9
+ exclude: [...(inherited.exclude ?? []), ...(local?.exclude ?? [])],
10
+ rules: [...(inherited.rules ?? []), ...(local?.rules ?? [])],
11
+ });
12
+ export const useJuliyaConfig = (config) => {
13
+ const inherited = useContext(DefaultsContext);
14
+ return useMemo(() => mergeConfig(inherited, config && parseConfig(config)), [inherited, config]);
8
15
  };
9
- export const JuliyaProvider = ({ locale, children }) => {
10
- const resolvedLocale = useJuliyaLocale(locale);
11
- return _jsx(LocaleContext.Provider, { value: resolvedLocale, children: children });
16
+ export const useJuliyaDefaults = (options = {}) => {
17
+ const inherited = useContext(DefaultsContext);
18
+ return resolveJuliyaDefaults(inherited, options);
19
+ };
20
+ export const JuliyaProvider = ({ locale, strategy, breakLongWords, config, children }) => {
21
+ const inherited = useContext(DefaultsContext);
22
+ const resolved = useMemo(() => mergeConfig(inherited, config && parseConfig(config), { locale, strategy, breakLongWords }), [inherited, config, locale, strategy, breakLongWords]);
23
+ return _jsx(DefaultsContext.Provider, { value: resolved, children: children });
12
24
  };
@@ -0,0 +1,12 @@
1
+ import type { HTMLAttributes } from "react";
2
+ import type { JuliyaConfig } from "../../core/config.js";
3
+ export declare const useJuliyaScope: (config?: JuliyaConfig) => {
4
+ ref: (next: HTMLElement | null) => void;
5
+ refresh: () => void | undefined;
6
+ };
7
+ export interface JuliyaScopeProps extends Omit<HTMLAttributes<HTMLElement>, "children" | "dangerouslySetInnerHTML"> {
8
+ as?: "div" | "article" | "section" | "main";
9
+ html: string;
10
+ config?: JuliyaConfig;
11
+ }
12
+ export declare const JuliyaScope: ({ as: Tag, html, config, ...props }: JuliyaScopeProps) => import("react").JSX.Element;
@@ -0,0 +1,30 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+ import { mountJuliyaScope } from "../../dom/scope.js";
5
+ import { useJuliyaConfig } from "./juliya-provider.js";
6
+ export const useJuliyaScope = (config) => {
7
+ const resolved = useJuliyaConfig(config);
8
+ const [element, setElement] = useState(null);
9
+ const controller = useRef(undefined);
10
+ const latest = useRef(resolved);
11
+ latest.current = resolved;
12
+ const ref = useCallback((next) => { setElement(next); }, []);
13
+ useEffect(() => {
14
+ if (!element)
15
+ return;
16
+ const mounted = mountJuliyaScope(element, latest.current);
17
+ controller.current = mounted;
18
+ return () => {
19
+ mounted.destroy();
20
+ if (controller.current === mounted)
21
+ controller.current = undefined;
22
+ };
23
+ }, [element]);
24
+ useEffect(() => { controller.current?.update(resolved); }, [resolved]);
25
+ return { ref, refresh: () => controller.current?.refresh() };
26
+ };
27
+ export const JuliyaScope = ({ as: Tag = "div", html, config, ...props }) => {
28
+ const { ref } = useJuliyaScope(config);
29
+ return _jsx(Tag, { ...props, ref: ref, dangerouslySetInnerHTML: { __html: html } }, html);
30
+ };
@@ -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, breakLongWords, 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, }: 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, break
18
18
  lines: import("../../index.js").WrappedLine[];
19
19
  measured: boolean;
20
20
  };
21
- export declare const useKowrap: ({ text, locale: explicitLocale, strategy, breakLongWords, 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, }: UseJuliyaOptions) => {
22
22
  locale: import("../../index.js").WrapLocale;
23
23
  forcedBreaks: readonly number[];
24
24
  setForcedBreaks: (breaks: readonly number[]) => void;
@@ -1,9 +1,9 @@
1
1
  import { useCallback, useState } from "react";
2
2
  import { manualLines } from "../../core/segmentation.js";
3
3
  import { useWrapLayout } from "./use-wrap-layout.js";
4
- import { useJuliyaLocale } from "./juliya-provider.js";
5
- export const useJuliya = ({ text, locale: explicitLocale, strategy = "balanced", breakLongWords = true, forcedBreaks: controlledBreaks, initialForcedBreaks = [], onForcedBreaksChange, style, className, tag = "span", }) => {
6
- const locale = useJuliyaLocale(explicitLocale);
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", }) => {
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
9
  const layout = useWrapLayout({ text, locale, strategy, breakLongWords, forcedBreaks, style, className, tag });
@@ -1,5 +1,6 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
2
  import { observeKowrap } from "../../dom/observe.js";
3
+ import { claimExplicit } from "../../dom/ownership.js";
3
4
  import { manualLines } from "../../core/segmentation.js";
4
5
  const keyOf = (forcedBreaks) => forcedBreaks?.join(",") ?? "";
5
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);
@@ -9,7 +10,14 @@ export const useWrapLayout = (options) => {
9
10
  const breakKey = keyOf(forcedBreaks);
10
11
  const fallback = useMemo(() => manualLines(text, forcedBreaks), [text, breakKey]);
11
12
  const elementRef = useRef(null);
12
- const ref = useCallback((element) => { elementRef.current = element; }, []);
13
+ const release = useRef(undefined);
14
+ const ref = useCallback((element) => {
15
+ if (elementRef.current === element)
16
+ return;
17
+ release.current?.();
18
+ elementRef.current = element;
19
+ release.current = element ? claimExplicit(element) : undefined;
20
+ }, []);
13
21
  const [layout, setLayout] = useState();
14
22
  useEffect(() => {
15
23
  const element = elementRef.current;
@@ -2,7 +2,7 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { Children, cloneElement, Fragment, isValidElement, useEffect, useRef, useState } from "react";
4
4
  import { useWrapLayout } from "./use-wrap-layout.js";
5
- import { useJuliyaLocale } from "./juliya-provider.js";
5
+ import { useJuliyaDefaults } from "./juliya-provider.js";
6
6
  import { breakOffsets, inlineBreakAttribute, observeInline } from "../../dom/inline.js";
7
7
  import { manualLines } from "../../core/segmentation.js";
8
8
  const baseStyle = {
@@ -14,7 +14,7 @@ const baseStyle = {
14
14
  };
15
15
  const PlainText = ({ children, as: Tag = "span", locale, strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, ...props }) => {
16
16
  const { ref, lines } = useWrapLayout({ text: children, locale, strategy, breakLongWords, forcedBreaks, style, className, tag: Tag });
17
- return _jsx(Tag, { ...props, lang: props.lang ?? locale, className: className, style: { ...baseStyle, overflowWrap: breakLongWords ? "anywhere" : "normal", ...style }, 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 });
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) => {
20
20
  if (typeof child === "string" || typeof child === "number" || typeof child === "bigint")
@@ -67,12 +67,12 @@ const InlineText = ({ children, as: Tag = "span", locale, strategy = "balanced",
67
67
  });
68
68
  return observer.destroy;
69
69
  }, [key, children, locale, strategy, breakLongWords, style, className, Tag]);
70
- return _jsx(Tag, { ...props, lang: props.lang ?? locale, className: className, style: { ...baseStyle, overflowWrap: breakLongWords ? "anywhere" : "normal", ...style }, ref: (element) => { ref.current = element; }, children: renderInline(children, offsets) });
70
+ 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
71
  };
72
72
  export const JuliyaText = (props) => {
73
- const locale = useJuliyaLocale(props.locale);
73
+ const options = useJuliyaDefaults(props);
74
74
  return typeof props.children === "string"
75
- ? _jsx(PlainText, { ...props, locale: locale, children: props.children })
76
- : _jsx(InlineText, { ...props, locale: locale });
75
+ ? _jsx(PlainText, { ...props, ...options, children: props.children })
76
+ : _jsx(InlineText, { ...props, ...options });
77
77
  };
78
78
  export const WrapText = JuliyaText;
@@ -1,6 +1,17 @@
1
+ import type { JuliyaConfig } from "../../core/config.js";
1
2
  import type { MountKowrapOptions } from "../../dom/types.js";
2
3
  export declare const kowrap: (element: HTMLElement, options: MountKowrapOptions) => {
3
4
  update: (options: MountKowrapOptions) => void;
4
5
  destroy: () => void;
5
6
  };
6
7
  export type { KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "../../dom/types.js";
8
+ export declare const juliya: (element: HTMLElement, options: MountKowrapOptions) => {
9
+ update: (options: MountKowrapOptions) => void;
10
+ destroy: () => void;
11
+ };
12
+ export type { KowrapOptions as JuliyaOptions, InlineKowrapOptions as InlineJuliyaOptions, MountKowrapOptions as MountJuliyaOptions } from "../../dom/types.js";
13
+ export declare const juliyaScope: (element: HTMLElement, config?: JuliyaConfig) => {
14
+ update: (config: JuliyaConfig) => void;
15
+ destroy: () => void;
16
+ };
17
+ export type { JuliyaConfig } from "../../core/config.js";
@@ -1,5 +1,11 @@
1
1
  import { mountKowrap } from "../../dom/render.js";
2
+ import { mountJuliyaScope } from "../../dom/scope.js";
2
3
  export const kowrap = (element, options) => {
3
4
  const controller = mountKowrap(element, options);
4
5
  return { update: controller.update, destroy: controller.destroy };
5
6
  };
7
+ export const juliya = kowrap;
8
+ export const juliyaScope = (element, config = {}) => {
9
+ const controller = mountJuliyaScope(element, config);
10
+ return { update: controller.update, destroy: controller.destroy };
11
+ };
@@ -1,3 +1,4 @@
1
+ import type { JuliyaConfig } from "../../core/config.js";
1
2
  import type { MountKowrapOptions } from "../../dom/types.js";
2
3
  interface Binding {
3
4
  value: MountKowrapOptions;
@@ -9,3 +10,20 @@ export declare const kowrapDirective: {
9
10
  beforeUnmount: (element: HTMLElement) => void;
10
11
  };
11
12
  export type { KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "../../dom/types.js";
13
+ export declare const juliyaDirective: {
14
+ mounted: (element: HTMLElement, binding: Binding) => void;
15
+ updated: (element: HTMLElement, binding: Binding) => void | undefined;
16
+ beforeUpdate: (element: HTMLElement) => void | undefined;
17
+ beforeUnmount: (element: HTMLElement) => void;
18
+ };
19
+ export type { KowrapOptions as JuliyaOptions, InlineKowrapOptions as InlineJuliyaOptions, MountKowrapOptions as MountJuliyaOptions } from "../../dom/types.js";
20
+ interface ScopeBinding {
21
+ value: JuliyaConfig;
22
+ }
23
+ export declare const juliyaScopeDirective: {
24
+ mounted: (element: HTMLElement, binding: ScopeBinding) => void;
25
+ beforeUpdate: (element: HTMLElement) => void;
26
+ updated: (element: HTMLElement, binding: ScopeBinding) => void;
27
+ beforeUnmount: (element: HTMLElement) => void;
28
+ };
29
+ export type { JuliyaConfig } from "../../core/config.js";
@@ -1,4 +1,5 @@
1
1
  import { mountKowrap } from "../../dom/render.js";
2
+ import { mountJuliyaScope } from "../../dom/scope.js";
2
3
  const mounted = new WeakMap();
3
4
  export const kowrapDirective = {
4
5
  mounted: (element, binding) => {
@@ -12,3 +13,19 @@ export const kowrapDirective = {
12
13
  mounted.delete(element);
13
14
  },
14
15
  };
16
+ export const juliyaDirective = kowrapDirective;
17
+ const mountedScopes = new WeakMap();
18
+ const mountScope = (element, binding) => {
19
+ mountedScopes.get(element)?.destroy();
20
+ mountedScopes.set(element, mountJuliyaScope(element, binding.value));
21
+ };
22
+ const destroyScope = (element) => {
23
+ mountedScopes.get(element)?.destroy();
24
+ mountedScopes.delete(element);
25
+ };
26
+ export const juliyaScopeDirective = {
27
+ mounted: mountScope,
28
+ beforeUpdate: destroyScope,
29
+ updated: mountScope,
30
+ beforeUnmount: destroyScope,
31
+ };
@@ -0,0 +1,15 @@
1
+ import type { WrapOptions } from "./types.js";
2
+ export type JuliyaDefaults = Pick<WrapOptions, "locale" | "strategy" | "breakLongWords">;
3
+ export interface JuliyaRule extends JuliyaDefaults {
4
+ selector: string;
5
+ }
6
+ export interface JuliyaConfig extends JuliyaDefaults {
7
+ $schema?: string;
8
+ include?: readonly string[];
9
+ exclude?: readonly string[];
10
+ rules?: readonly JuliyaRule[];
11
+ }
12
+ export declare const parseConfig: (input: unknown) => JuliyaConfig;
13
+ export declare const defineConfig: (config: JuliyaConfig) => JuliyaConfig;
14
+ export declare const resolveJuliyaDefaults: (...layers: readonly (JuliyaDefaults | undefined)[]) => JuliyaDefaults;
15
+ export declare const resolveJuliyaRules: (config: JuliyaConfig, matches: (selector: string) => boolean) => JuliyaDefaults;
@@ -0,0 +1,84 @@
1
+ const locales = ["ko", "en", "ja", "zh", "zh-Hans"];
2
+ const strategies = ["balanced", "greedy"];
3
+ const optionKeys = ["locale", "strategy", "breakLongWords"];
4
+ const fail = (path, message) => {
5
+ throw new TypeError(`Invalid Juliya config at ${path}: ${message}`);
6
+ };
7
+ const record = (value, path) => {
8
+ if (typeof value !== "object" || value === null || Array.isArray(value))
9
+ return fail(path, "expected an object");
10
+ return value;
11
+ };
12
+ const checkKeys = (value, keys, path) => {
13
+ for (const key of Object.keys(value))
14
+ if (!keys.includes(key))
15
+ fail(`${path}.${key}`, "unknown option");
16
+ };
17
+ const selector = (value, path) => {
18
+ if (typeof value !== "string" || !value.trim())
19
+ return fail(path, "expected a nonempty selector");
20
+ return value;
21
+ };
22
+ const selectors = (value, path) => {
23
+ if (!Array.isArray(value))
24
+ return fail(path, "expected an array of selectors");
25
+ return Array.from(value, (item, index) => selector(item, `${path}[${index}]`));
26
+ };
27
+ const defaults = (value, path) => {
28
+ const result = {};
29
+ if (value.locale !== undefined) {
30
+ if (typeof value.locale !== "string" || !locales.includes(value.locale))
31
+ fail(`${path}.locale`, "unsupported locale");
32
+ result.locale = value.locale;
33
+ }
34
+ if (value.strategy !== undefined) {
35
+ if (typeof value.strategy !== "string" || !strategies.includes(value.strategy))
36
+ fail(`${path}.strategy`, "unsupported strategy");
37
+ result.strategy = value.strategy;
38
+ }
39
+ if (value.breakLongWords !== undefined) {
40
+ if (typeof value.breakLongWords !== "boolean")
41
+ return fail(`${path}.breakLongWords`, "expected a boolean");
42
+ result.breakLongWords = value.breakLongWords;
43
+ }
44
+ return result;
45
+ };
46
+ export const parseConfig = (input) => {
47
+ const value = record(input, "$");
48
+ checkKeys(value, [...optionKeys, "$schema", "include", "exclude", "rules"], "$");
49
+ const result = defaults(value, "$");
50
+ if (value.$schema !== undefined) {
51
+ if (typeof value.$schema !== "string")
52
+ return fail("$.$schema", "expected a string");
53
+ result.$schema = value.$schema;
54
+ }
55
+ if (value.include !== undefined)
56
+ result.include = selectors(value.include, "$.include");
57
+ if (value.exclude !== undefined)
58
+ result.exclude = selectors(value.exclude, "$.exclude");
59
+ if (value.rules !== undefined) {
60
+ if (!Array.isArray(value.rules))
61
+ return fail("$.rules", "expected an array");
62
+ result.rules = Array.from(value.rules, (item, index) => {
63
+ const path = `$.rules[${index}]`;
64
+ const rule = record(item, path);
65
+ checkKeys(rule, [...optionKeys, "selector"], path);
66
+ return { selector: selector(rule.selector, `${path}.selector`), ...defaults(rule, path) };
67
+ });
68
+ }
69
+ return result;
70
+ };
71
+ export const defineConfig = (config) => parseConfig(config);
72
+ export const resolveJuliyaDefaults = (...layers) => {
73
+ const result = {};
74
+ for (const layer of layers) {
75
+ if (layer?.locale !== undefined)
76
+ result.locale = layer.locale;
77
+ if (layer?.strategy !== undefined)
78
+ result.strategy = layer.strategy;
79
+ if (layer?.breakLongWords !== undefined)
80
+ result.breakLongWords = layer.breakLongWords;
81
+ }
82
+ return result;
83
+ };
84
+ export const resolveJuliyaRules = (config, matches) => resolveJuliyaDefaults(config, ...(config.rules?.filter(rule => matches(rule.selector)) ?? []));
@@ -1,2 +1,2 @@
1
- import type { ParagraphOptions, PlannedLine } from "./types.js";
2
- export declare const planParagraph: (text: string, options: ParagraphOptions) => PlannedLine[];
1
+ import type { ParagraphOptions, PlannedLine, WrapDecision } from "./types.js";
2
+ export declare const planParagraph: (text: string, options: ParagraphOptions, trace?: (decision: WrapDecision) => void) => PlannedLine[];
@@ -1,7 +1,7 @@
1
1
  import { boundariesOf, candidatesFrom } from "./boundaries.js";
2
2
  import { visibleText } from "./segmentation.js";
3
3
  import { lineCost } from "./scoring.js";
4
- const greedyPlan = (text, points, options) => {
4
+ const greedyPlan = (text, points, options, trace) => {
5
5
  const lines = [];
6
6
  for (let start = 0; start < points.length - 1;) {
7
7
  let chosen;
@@ -9,12 +9,14 @@ const greedyPlan = (text, points, options) => {
9
9
  chosen = candidate;
10
10
  if (!chosen)
11
11
  throw new Error("No line candidate");
12
- lines.push({ start: points[start].offset, end: points[chosen.next].offset, width: chosen.width });
12
+ const line = { start: points[start].offset, end: points[chosen.next].offset, width: chosen.width };
13
+ lines.push(line);
14
+ trace?.({ ...line, reason: "greedy" });
13
15
  start = chosen.next;
14
16
  }
15
17
  return lines;
16
18
  };
17
- const balancedPlan = (text, points, options) => {
19
+ const balancedPlan = (text, points, options, trace) => {
18
20
  const last = points.length - 1;
19
21
  const choices = [];
20
22
  const nextWords = (options.locale ?? "ko") === "ko"
@@ -41,16 +43,21 @@ const balancedPlan = (text, points, options) => {
41
43
  const lines = [];
42
44
  for (let start = 0; start < last;) {
43
45
  const choice = choices[start];
44
- lines.push({ start: points[start].offset, end: points[choice.next].offset, width: choice.width });
46
+ const line = { start: points[start].offset, end: points[choice.next].offset, width: choice.width };
47
+ lines.push(line);
48
+ trace?.({ ...line, reason: "balanced", cost: choice.cost - choices[choice.next].cost, remainingCost: choice.cost });
45
49
  start = choice.next;
46
50
  }
47
51
  return lines;
48
52
  };
49
- export const planParagraph = (text, options) => {
53
+ export const planParagraph = (text, options, trace) => {
50
54
  const visible = visibleText(text);
51
55
  const fullWidth = options.measureRange ? options.measureRange(0, visible.length) : options.measure(visible);
52
- if (!text || fullWidth <= options.width)
53
- return [{ start: 0, end: text.length, width: fullWidth }];
56
+ if (!text || fullWidth <= options.width) {
57
+ const line = { start: 0, end: text.length, width: fullWidth };
58
+ trace?.({ ...line, reason: "fits" });
59
+ return [line];
60
+ }
54
61
  const points = boundariesOf(text, options);
55
- return options.strategy === "greedy" ? greedyPlan(text, points, options) : balancedPlan(text, points, options);
62
+ return options.strategy === "greedy" ? greedyPlan(text, points, options, trace) : balancedPlan(text, points, options, trace);
56
63
  };
@@ -23,9 +23,22 @@ const compounds = {
23
23
  };
24
24
  const adverbialModifier = /^[가-힣]+게$/u;
25
25
  const predicateHead = /^[가-힣]+(?:거나|지만|면서|도록|고|면|며|다|요|기|지|게|서)[.!?。!?…,;:]?$/u;
26
+ const vowelPredicateStems = new Set(["가", "오", "보", "주", "쓰", "켜", "끄", "뛰", "서", "자", "피", "치", "비치", "보이", "들리", "바꾸", "만드", "지나", "나오", "들어오"]);
27
+ const inflectedPredicateHead = (word) => {
28
+ const match = /^([가-힣]+)[.!?。!?…,;:]?$/u.exec(word);
29
+ if (!match)
30
+ return false;
31
+ const head = match[1];
32
+ const last = head.charCodeAt(head.length - 1) - 0xac00;
33
+ const final = last % 28;
34
+ if (final !== 4 && final !== 8)
35
+ return false;
36
+ const stem = head.slice(0, -1) + String.fromCharCode(0xac00 + last - final);
37
+ return vowelPredicateStems.has(stem) || /(?:하|되|시키)$/u.test(stem);
38
+ };
26
39
  const protectedPair = (fragment, nextWord) => {
27
40
  const left = fragment.match(/\S+$/u)?.[0] ?? "";
28
- if (adverbialModifier.test(left) && !left.endsWith("에게") && predicateHead.test(nextWord))
41
+ if (adverbialModifier.test(left) && !left.endsWith("에게") && (predicateHead.test(nextWord) || inflectedPredicateHead(nextWord)))
29
42
  return true;
30
43
  if (numeralModifier.test(left) && counterHead.test(nextWord))
31
44
  return true;
@@ -44,3 +44,19 @@ export interface PlannedLine {
44
44
  end: number;
45
45
  width: number;
46
46
  }
47
+ export interface WrapDecision {
48
+ start: number;
49
+ end: number;
50
+ width: number;
51
+ reason: "fits" | "greedy" | "balanced";
52
+ cost?: number;
53
+ remainingCost?: number;
54
+ }
55
+ export interface WrapDiagnostics {
56
+ locale: WrapLocale;
57
+ strategy: NonNullable<WrapOptions["strategy"]>;
58
+ width: number;
59
+ lineCount: number;
60
+ durationMs: number;
61
+ decisions: WrapDecision[];
62
+ }
@@ -1,2 +1,6 @@
1
- import type { WrapOptions, WrappedLine } from "./types.js";
1
+ import type { WrapOptions, WrappedLine, WrapDiagnostics } from "./types.js";
2
2
  export declare const wrap: (text: string, options: WrapOptions) => WrappedLine[];
3
+ export declare const wrapWithDiagnostics: (text: string, options: WrapOptions) => {
4
+ lines: WrappedLine[];
5
+ diagnostics: WrapDiagnostics;
6
+ };
package/dist/core/wrap.js CHANGED
@@ -8,7 +8,7 @@ const checkedMeasure = (measure) => (value) => {
8
8
  throw new RangeError("measure must return a non-negative finite number");
9
9
  return result;
10
10
  };
11
- export const wrap = (text, options) => {
11
+ const wrapInternal = (text, options, trace) => {
12
12
  if (!Number.isFinite(options.width) || options.width <= 0)
13
13
  throw new RangeError("width must be positive and finite");
14
14
  const paragraphOptions = {
@@ -25,7 +25,7 @@ export const wrap = (text, options) => {
25
25
  if (!Number.isFinite(result) || result < 0)
26
26
  throw new RangeError("measureRange must return a non-negative finite number");
27
27
  return result;
28
- } : undefined });
28
+ } : undefined }, trace ? decision => trace({ ...decision, start: decision.start + paragraph.start, end: decision.end + paragraph.start }) : undefined);
29
29
  for (const [index, line] of plan.entries()) {
30
30
  lines.push({
31
31
  text: paragraph.text.slice(line.start, line.end),
@@ -38,3 +38,10 @@ export const wrap = (text, options) => {
38
38
  }
39
39
  return lines;
40
40
  };
41
+ export const wrap = (text, options) => wrapInternal(text, options);
42
+ export const wrapWithDiagnostics = (text, options) => {
43
+ const decisions = [];
44
+ const start = performance.now();
45
+ const lines = wrapInternal(text, options, decision => decisions.push(decision));
46
+ return { lines, diagnostics: { locale: options.locale ?? "ko", strategy: options.strategy ?? "balanced", width: options.width, lineCount: lines.length, durationMs: performance.now() - start, decisions } };
47
+ };
@@ -3,3 +3,8 @@ export { createCanvasMeasure } from "./measure.js";
3
3
  export type { KowrapController, KowrapLayout, KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "./types.js";
4
4
  export { observeKowrap } from "./observe.js";
5
5
  export { mountKowrap } from "./render.js";
6
+ export type { KowrapController as JuliyaController, KowrapLayout as JuliyaLayout, KowrapOptions as JuliyaOptions, InlineKowrapOptions as InlineJuliyaOptions, MountKowrapOptions as MountJuliyaOptions } from "./types.js";
7
+ export { observeKowrap as observeJuliya } from "./observe.js";
8
+ export { mountKowrap as mountJuliya } from "./render.js";
9
+ export { mountJuliyaScope } from "./scope.js";
10
+ export type { JuliyaScopeController, JuliyaScopeDecision, JuliyaScopeDiagnostics } from "./scope.js";
package/dist/dom/index.js CHANGED
@@ -1,3 +1,6 @@
1
1
  export { createCanvasMeasure } from "./measure.js";
2
2
  export { observeKowrap } from "./observe.js";
3
3
  export { mountKowrap } from "./render.js";
4
+ export { observeKowrap as observeJuliya } from "./observe.js";
5
+ export { mountKowrap as mountJuliya } from "./render.js";
6
+ export { mountJuliyaScope } from "./scope.js";
@@ -55,8 +55,8 @@ export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) =
55
55
  onBreaks(breakOffsets(manualLines(readInline(element).text, options.forcedBreaks)));
56
56
  return;
57
57
  }
58
- const { locale, strategy, breakLongWords, forcedBreaks } = options;
59
- const signatureOf = ({ text, styled }) => JSON.stringify([text, layout.width, locale, strategy, breakLongWords, forcedBreaks, styled]);
58
+ const { locale, strategy, breakLongWords, forcedBreaks, protectInlineCode } = options;
59
+ const signatureOf = ({ text, styled }) => JSON.stringify([text, layout.width, locale, strategy, breakLongWords, forcedBreaks, protectInlineCode, styled]);
60
60
  const rendered = readStyledRuns(element);
61
61
  const signature = signatureOf(rendered);
62
62
  // Generated breaks can mask structural CSS changes during a viewport resize.
@@ -81,7 +81,23 @@ export const observeInline = (element, getOptions, onBreaks, readAuthorMarkup) =
81
81
  const right = Math.min(end, run.end);
82
82
  return left < right ? width + measures.get(run.key)(text.slice(left, right)) : width;
83
83
  }, 0);
84
- const offsets = breakOffsets(wrap(text, { ...options, ...layout, measureRange }));
84
+ let offsets = breakOffsets(wrap(text, { ...options, ...layout, measureRange }));
85
+ if (protectInlineCode) {
86
+ const ranges = new Map();
87
+ for (const run of readInline(element).runs) {
88
+ const code = run.node.parentElement?.closest("code");
89
+ if (!code || !element.contains(code))
90
+ continue;
91
+ const range = ranges.get(code);
92
+ if (range)
93
+ range.end = run.end;
94
+ else
95
+ ranges.set(code, { start: run.start, end: run.end });
96
+ }
97
+ // 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)))
99
+ offsets = [];
100
+ }
85
101
  onBreaks(offsets);
86
102
  previous = { signature: readAuthorMarkup ? signatureOf(readStyledRuns(element)) : signature, authorSignature, measure: layout.measure, offsets };
87
103
  });
@@ -0,0 +1,5 @@
1
+ export declare const isExplicitlyManaged: (element: HTMLElement) => boolean;
2
+ export declare const isScopeManaged: (element: HTMLElement) => boolean;
3
+ export declare const claimExplicit: (element: HTMLElement) => () => void;
4
+ export declare const claimScoped: (element: HTMLElement, release: () => void) => boolean;
5
+ export declare const releaseScoped: (element: HTMLElement) => void;
@@ -0,0 +1,29 @@
1
+ const explicit = new Map();
2
+ const scoped = new Map();
3
+ const overlaps = (a, b) => a.contains(b) || b.contains(a);
4
+ export const isExplicitlyManaged = (element) => [...explicit.keys()].some(owner => overlaps(owner, element));
5
+ export const isScopeManaged = (element) => scoped.has(element);
6
+ export const claimExplicit = (element) => {
7
+ explicit.set(element, (explicit.get(element) ?? 0) + 1);
8
+ for (const [owner, release] of scoped)
9
+ if (overlaps(owner, element))
10
+ release();
11
+ let active = true;
12
+ return () => {
13
+ if (!active)
14
+ return;
15
+ active = false;
16
+ const count = explicit.get(element) ?? 0;
17
+ if (count <= 1)
18
+ explicit.delete(element);
19
+ else
20
+ explicit.set(element, count - 1);
21
+ };
22
+ };
23
+ export const claimScoped = (element, release) => {
24
+ if (isExplicitlyManaged(element) || [...scoped.keys()].some(owner => overlaps(owner, element)))
25
+ return false;
26
+ scoped.set(element, release);
27
+ return true;
28
+ };
29
+ export const releaseScoped = (element) => { scoped.delete(element); };
@@ -1,2 +1,3 @@
1
1
  import type { KowrapController, MountKowrapOptions } from "./types.js";
2
+ export declare const mountElement: (element: HTMLElement, initial: MountKowrapOptions) => KowrapController;
2
3
  export declare const mountKowrap: (element: HTMLElement, initial: MountKowrapOptions) => KowrapController;
@@ -1,11 +1,35 @@
1
1
  import { manualLines } from "../core/segmentation.js";
2
2
  import { observeKowrap } from "./observe.js";
3
3
  import { mountInline } from "./inline.js";
4
+ import { claimExplicit } from "./ownership.js";
4
5
  const wrapStyles = {
5
6
  whiteSpace: "pre-wrap",
6
7
  wordBreak: "keep-all",
7
8
  overflowWrap: "anywhere",
8
9
  };
10
+ const captureStyles = (element) => {
11
+ const originalStyle = element.getAttribute("style");
12
+ const originalCssText = element.style.cssText;
13
+ const names = ["white-space", "word-break", "overflow-wrap"];
14
+ const entries = names.map(name => ({ name, value: element.style.getPropertyValue(name), priority: element.style.getPropertyPriority(name) }));
15
+ return () => {
16
+ // The caller may already have replaced all wrapping styles with its own attribute.
17
+ if (element.style.cssText === originalCssText)
18
+ return;
19
+ for (const { name, value, priority } of entries) {
20
+ if (value)
21
+ element.style.setProperty(name, value, priority);
22
+ else
23
+ element.style.removeProperty(name);
24
+ }
25
+ if (element.style.cssText === originalCssText) {
26
+ // Flush pending CSSOM serialization before removing an originally absent attribute.
27
+ element.setAttribute("style", originalStyle ?? "");
28
+ if (originalStyle === null)
29
+ element.removeAttribute("style");
30
+ }
31
+ };
32
+ };
9
33
  const renderLines = (element, lines) => {
10
34
  const doc = element.ownerDocument;
11
35
  const fragment = doc.createDocumentFragment();
@@ -19,17 +43,17 @@ const renderLines = (element, lines) => {
19
43
  element.replaceChildren(fragment);
20
44
  };
21
45
  const sameLines = (previous, next) => previous?.length === next.length && previous.every((line, index) => line.text === next[index]?.text && line.breakAfter === next[index]?.breakAfter);
22
- export const mountKowrap = (element, initial) => {
46
+ export const mountElement = (element, initial) => {
23
47
  if (initial.inline) {
24
- const previous = { whiteSpace: element.style.whiteSpace, wordBreak: element.style.wordBreak, overflowWrap: element.style.overflowWrap };
48
+ const restoreStyles = captureStyles(element);
25
49
  Object.assign(element.style, wrapStyles, { overflowWrap: initial.breakLongWords === false ? "normal" : "anywhere" });
26
50
  const controller = mountInline(element, initial);
27
51
  return { ...controller, update: (next) => { if (!next.inline)
28
- throw new TypeError("Cannot change inline mode"); element.style.overflowWrap = next.breakLongWords === false ? "normal" : "anywhere"; controller.update(next); }, destroy: () => { controller.destroy(); Object.assign(element.style, previous); } };
52
+ throw new TypeError("Cannot change inline mode"); element.style.overflowWrap = next.breakLongWords === false ? "normal" : "anywhere"; controller.update(next); }, destroy: () => { controller.destroy(); restoreStyles(); } };
29
53
  }
30
54
  const initialLines = manualLines(initial.text, initial.forcedBreaks);
31
55
  const style = element.style;
32
- const previousStyles = { whiteSpace: style.whiteSpace, wordBreak: style.wordBreak, overflowWrap: style.overflowWrap };
56
+ const restoreStyles = captureStyles(element);
33
57
  let options = initial;
34
58
  let previousLines;
35
59
  let active = true;
@@ -59,8 +83,24 @@ export const mountKowrap = (element, initial) => {
59
83
  return;
60
84
  active = false;
61
85
  observer.destroy();
62
- Object.assign(style, previousStyles);
86
+ restoreStyles();
63
87
  element.textContent = options.text;
64
88
  },
65
89
  };
66
90
  };
91
+ export const mountKowrap = (element, initial) => {
92
+ const release = claimExplicit(element);
93
+ try {
94
+ const controller = mountElement(element, initial);
95
+ return { ...controller, destroy: () => { try {
96
+ controller.destroy();
97
+ }
98
+ finally {
99
+ release();
100
+ } } };
101
+ }
102
+ catch (error) {
103
+ release();
104
+ throw error;
105
+ }
106
+ };
@@ -0,0 +1,15 @@
1
+ import type { JuliyaConfig, JuliyaDefaults } from "../core/config.js";
2
+ export interface JuliyaScopeDecision {
3
+ status: "mounted" | "updated" | "skipped" | "unmounted";
4
+ reason?: "excluded" | "nested-scope" | "managed" | "unsupported-markup" | "empty" | "no-longer-matches" | "destroyed" | "ownership-transferred";
5
+ options?: JuliyaDefaults;
6
+ }
7
+ export interface JuliyaScopeDiagnostics {
8
+ onDecision: (element: HTMLElement, decision: JuliyaScopeDecision) => void;
9
+ }
10
+ export interface JuliyaScopeController {
11
+ refresh: () => void;
12
+ update: (config: JuliyaConfig) => void;
13
+ destroy: () => void;
14
+ }
15
+ export declare const mountJuliyaScope: (root: HTMLElement, initial?: JuliyaConfig, diagnostics?: JuliyaScopeDiagnostics) => JuliyaScopeController;
@@ -0,0 +1,223 @@
1
+ import { parseConfig, resolveJuliyaDefaults, resolveJuliyaRules } from "../core/config.js";
2
+ import { mountElement } from "./render.js";
3
+ import { claimScoped, isExplicitlyManaged, isScopeManaged, releaseScoped } from "./ownership.js";
4
+ const hardExclusions = "pre,button,input,select,textarea,option,script,style,svg,math,[contenteditable]:not([contenteditable='false']),[data-juliya-ignore],[data-juliya-managed]";
5
+ const blockDescendants = "address,article,aside,blockquote,div,dl,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hr,main,nav,ol,p,section,table,ul";
6
+ const scopes = new Map();
7
+ const closestScope = (element) => {
8
+ for (let current = element; current; current = current.parentElement) {
9
+ const scope = scopes.get(current);
10
+ if (scope)
11
+ return scope;
12
+ }
13
+ return undefined;
14
+ };
15
+ const validateSelectors = (root, config) => {
16
+ for (const selector of [...(config.include ?? []), ...(config.exclude ?? []), ...(config.rules ?? []).map(rule => rule.selector)]) {
17
+ try {
18
+ root.matches(selector);
19
+ }
20
+ catch {
21
+ throw new TypeError(`Invalid Juliya selector: ${selector}`);
22
+ }
23
+ }
24
+ };
25
+ const parseElementOptions = (locale, strategy, breakLongWords) => {
26
+ const result = {};
27
+ if (locale === "ko" || locale === "en" || locale === "ja" || locale === "zh" || locale === "zh-Hans")
28
+ result.locale = locale;
29
+ if (strategy === "balanced" || strategy === "greedy")
30
+ result.strategy = strategy;
31
+ if (breakLongWords === "true" || breakLongWords === "false")
32
+ result.breakLongWords = breakLongWords === "true";
33
+ return result;
34
+ };
35
+ const attributes = (element) => parseElementOptions(element.getAttribute("data-juliya-locale"), element.getAttribute("data-juliya-strategy"), element.getAttribute("data-juliya-break-long-words"));
36
+ const cssOptions = (element) => {
37
+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);
38
+ return parseElementOptions(style?.getPropertyValue("--juliya-locale").trim() ?? null, style?.getPropertyValue("--juliya-strategy").trim() ?? null, style?.getPropertyValue("--juliya-break-long-words").trim() ?? null);
39
+ };
40
+ export const mountJuliyaScope = (root, initial = {}, diagnostics) => {
41
+ if (scopes.has(root))
42
+ throw new TypeError("A Juliya scope is already mounted on this root");
43
+ let config = parseConfig(initial);
44
+ validateSelectors(root, config);
45
+ const mounted = new Map();
46
+ let active = true;
47
+ let refreshing = false;
48
+ let pending = false;
49
+ let pendingFrame;
50
+ let generation = 0;
51
+ let observer;
52
+ const parent = closestScope(root.parentElement);
53
+ const view = root.ownerDocument.defaultView;
54
+ const emit = diagnostics && ((element, decision) => {
55
+ try {
56
+ diagnostics.onDecision(element, decision);
57
+ }
58
+ catch { /* Diagnostic observers must not interrupt wrapping. */ }
59
+ });
60
+ const detach = (element, reason = "no-longer-matches") => {
61
+ const item = mounted.get(element);
62
+ if (!item)
63
+ return;
64
+ mounted.delete(element);
65
+ releaseScoped(element);
66
+ item.controller.destroy();
67
+ emit?.(element, { status: "unmounted", reason });
68
+ };
69
+ const refresh = () => {
70
+ if (!active || refreshing)
71
+ return;
72
+ refreshing = true;
73
+ try {
74
+ const include = ["[data-juliya]", ...(config.include ?? [])].join(",");
75
+ const exclude = [...(config.exclude ?? []), hardExclusions].join(",");
76
+ const elements = [...(root.matches(include) ? [root] : []), ...Array.from(root.querySelectorAll(include))];
77
+ const wanted = new Set(elements.filter(element => {
78
+ const reason = element.namespaceURI !== "http://www.w3.org/1999/xhtml" || element.querySelector(exclude + "," + blockDescendants) ? "unsupported-markup"
79
+ : (closestScope(element) !== controller || [...scopes.keys()].some(nested => nested !== root && element.contains(nested))) ? "nested-scope"
80
+ : element.closest(exclude + ",code") ? "excluded"
81
+ : isExplicitlyManaged(element) || (isScopeManaged(element) && !mounted.has(element)) ? "managed"
82
+ : !element.textContent?.trim() ? "empty" : undefined;
83
+ if (reason)
84
+ emit?.(element, { status: "skipped", reason });
85
+ return !reason;
86
+ }));
87
+ for (const element of [...wanted]) {
88
+ for (let ancestor = element.parentElement; ancestor && root.contains(ancestor); ancestor = ancestor.parentElement)
89
+ wanted.delete(ancestor);
90
+ }
91
+ if (!active)
92
+ return;
93
+ for (const element of mounted.keys()) {
94
+ if (!active)
95
+ return;
96
+ if (!wanted.has(element))
97
+ detach(element);
98
+ }
99
+ for (const element of wanted) {
100
+ if (!active)
101
+ return;
102
+ const options = resolveJuliyaDefaults(resolveJuliyaRules(config, selector => element.matches(selector)), cssOptions(element), attributes(element));
103
+ const key = JSON.stringify(options);
104
+ const item = mounted.get(element);
105
+ if (item) {
106
+ if (item.key !== key) {
107
+ item.key = key;
108
+ item.controller.update({ inline: true, protectInlineCode: true, ...options });
109
+ emit?.(element, { status: "updated", options });
110
+ }
111
+ continue;
112
+ }
113
+ if (!claimScoped(element, () => detach(element, "ownership-transferred")))
114
+ continue;
115
+ try {
116
+ mounted.set(element, { controller: mountElement(element, { inline: true, protectInlineCode: true, ...options }), key });
117
+ emit?.(element, { status: "mounted", options });
118
+ }
119
+ catch (error) {
120
+ releaseScoped(element);
121
+ throw error;
122
+ }
123
+ }
124
+ }
125
+ finally {
126
+ observer?.takeRecords();
127
+ refreshing = false;
128
+ }
129
+ };
130
+ const cancelPending = () => {
131
+ generation++;
132
+ if (pendingFrame !== undefined)
133
+ view?.cancelAnimationFrame(pendingFrame);
134
+ pendingFrame = undefined;
135
+ pending = false;
136
+ };
137
+ const schedule = (immediate = false) => {
138
+ if (!active)
139
+ return;
140
+ const useFrame = !immediate && !!view?.requestAnimationFrame && root.ownerDocument.visibilityState !== "hidden";
141
+ if (pending) {
142
+ if (pendingFrame === undefined || useFrame)
143
+ return;
144
+ cancelPending();
145
+ }
146
+ pending = true;
147
+ const scheduled = ++generation;
148
+ const flush = () => {
149
+ if (scheduled !== generation)
150
+ return;
151
+ pendingFrame = undefined;
152
+ pending = false;
153
+ refresh();
154
+ };
155
+ // Coalesce mutations from independently scheduled paragraph layouts into one scan.
156
+ if (useFrame && view)
157
+ pendingFrame = view.requestAnimationFrame(flush);
158
+ else
159
+ queueMicrotask(flush);
160
+ };
161
+ const belongsToMounted = (target) => {
162
+ for (let element = target.nodeType === 1 ? target : target.parentElement; element && root.contains(element); element = element.parentElement) {
163
+ if (mounted.has(element))
164
+ return true;
165
+ }
166
+ return false;
167
+ };
168
+ const isLayoutMutation = (record) => {
169
+ if (record.type === "characterData" && !root.contains(record.target))
170
+ return true;
171
+ if (!belongsToMounted(record.target) || record.type === "attributes")
172
+ return false;
173
+ return record.type === "characterData" || [...record.addedNodes, ...record.removedNodes].every(node => node.nodeType === 3 || (node.nodeType === 1 && node.matches("br[data-kowrap-break]")));
174
+ };
175
+ const onResize = () => schedule();
176
+ const onVisibilityChange = () => {
177
+ if (root.ownerDocument.visibilityState === "hidden" && pendingFrame !== undefined)
178
+ schedule(true);
179
+ };
180
+ const controller = {
181
+ refresh: () => { cancelPending(); refresh(); for (const item of mounted.values())
182
+ item.controller.refresh(); },
183
+ update: next => {
184
+ if (!active)
185
+ return;
186
+ const validated = parseConfig(next);
187
+ validateSelectors(root, validated);
188
+ config = validated;
189
+ cancelPending();
190
+ refresh();
191
+ },
192
+ destroy: () => {
193
+ if (!active)
194
+ return;
195
+ active = false;
196
+ cancelPending();
197
+ observer?.disconnect();
198
+ view?.removeEventListener("resize", onResize);
199
+ root.ownerDocument.removeEventListener("visibilitychange", onVisibilityChange);
200
+ for (const element of mounted.keys())
201
+ detach(element, "destroyed");
202
+ scopes.delete(root);
203
+ closestScope(root.parentElement)?.refresh();
204
+ },
205
+ };
206
+ scopes.set(root, controller);
207
+ try {
208
+ parent?.refresh();
209
+ refresh();
210
+ view?.addEventListener("resize", onResize);
211
+ root.ownerDocument.addEventListener("visibilitychange", onVisibilityChange);
212
+ const Mutation = view?.MutationObserver;
213
+ if (Mutation) {
214
+ observer = new Mutation(records => schedule(records.some(record => !isLayoutMutation(record))));
215
+ observer.observe(root, { subtree: true, attributes: true, childList: true, characterData: true });
216
+ }
217
+ }
218
+ catch (error) {
219
+ controller.destroy();
220
+ throw error;
221
+ }
222
+ return controller;
223
+ };
@@ -6,6 +6,7 @@ export interface KowrapOptions extends Pick<WrapOptions, "strategy" | "breakLong
6
6
  export interface InlineKowrapOptions extends Pick<WrapOptions, "strategy" | "breakLongWords" | "forcedBreaks" | "locale"> {
7
7
  inline: true;
8
8
  text?: never;
9
+ protectInlineCode?: boolean;
9
10
  }
10
11
  export type MountKowrapOptions = KowrapOptions | InlineKowrapOptions;
11
12
  export interface KowrapController {
package/dist/index.d.ts CHANGED
@@ -1,3 +1,7 @@
1
1
  export type { Measure, TextSegment, WrapOptions, WrappedLine, WrapLocale } from "./core/types.js";
2
2
  export { manualLines as splitLines, segmentSentences } from "./core/segmentation.js";
3
3
  export { wrap } from "./core/wrap.js";
4
+ export type { JuliyaConfig, JuliyaDefaults, JuliyaRule } from "./core/config.js";
5
+ export { defineConfig, parseConfig, resolveJuliyaDefaults, resolveJuliyaRules } from "./core/config.js";
6
+ export type { WrapDecision, WrapDiagnostics } from "./core/types.js";
7
+ export { wrapWithDiagnostics } from "./core/wrap.js";
package/dist/index.js CHANGED
@@ -1,2 +1,4 @@
1
1
  export { manualLines as splitLines, segmentSentences } from "./core/segmentation.js";
2
2
  export { wrap } from "./core/wrap.js";
3
+ export { defineConfig, parseConfig, resolveJuliyaDefaults, resolveJuliyaRules } from "./core/config.js";
4
+ export { wrapWithDiagnostics } from "./core/wrap.js";
@@ -0,0 +1,77 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Juliya project configuration",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "properties": {
7
+ "$schema": {
8
+ "type": "string"
9
+ },
10
+ "locale": {
11
+ "enum": [
12
+ "ko",
13
+ "en",
14
+ "ja",
15
+ "zh",
16
+ "zh-Hans"
17
+ ]
18
+ },
19
+ "strategy": {
20
+ "enum": [
21
+ "balanced",
22
+ "greedy"
23
+ ]
24
+ },
25
+ "breakLongWords": {
26
+ "type": "boolean"
27
+ },
28
+ "include": {
29
+ "type": "array",
30
+ "items": {
31
+ "type": "string",
32
+ "pattern": "\\S"
33
+ }
34
+ },
35
+ "exclude": {
36
+ "type": "array",
37
+ "items": {
38
+ "type": "string",
39
+ "pattern": "\\S"
40
+ }
41
+ },
42
+ "rules": {
43
+ "type": "array",
44
+ "items": {
45
+ "type": "object",
46
+ "required": [
47
+ "selector"
48
+ ],
49
+ "additionalProperties": false,
50
+ "properties": {
51
+ "selector": {
52
+ "type": "string",
53
+ "pattern": "\\S"
54
+ },
55
+ "locale": {
56
+ "enum": [
57
+ "ko",
58
+ "en",
59
+ "ja",
60
+ "zh",
61
+ "zh-Hans"
62
+ ]
63
+ },
64
+ "strategy": {
65
+ "enum": [
66
+ "balanced",
67
+ "greedy"
68
+ ]
69
+ },
70
+ "breakLongWords": {
71
+ "type": "boolean"
72
+ }
73
+ }
74
+ }
75
+ }
76
+ }
77
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oddmash/juliya",
3
3
  "license": "MIT",
4
- "version": "0.4.4",
4
+ "version": "0.5.1",
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"],
@@ -29,7 +29,7 @@
29
29
  "scripts": {
30
30
  "lint": "eslint . --max-warnings 0",
31
31
  "lint:fix": "eslint . --fix --max-warnings 0",
32
- "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json",
32
+ "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json && node scripts/copy-config-schema.mjs",
33
33
  "test": "pnpm run build && node --test test/*.test.mjs",
34
34
  "test:next": "pnpm run build && pnpm --dir test/next-app run build",
35
35
  "test:hydration": "pnpm run build && pnpm --dir test/next-app run test:hydration",