@oddmash/juliya 0.0.0-stage → 0.4.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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +7 -0
  3. package/README.md +75 -2
  4. package/dist/adapters/react/index.d.ts +6 -0
  5. package/dist/adapters/react/index.js +4 -0
  6. package/dist/adapters/react/juliya-provider.d.ts +8 -0
  7. package/dist/adapters/react/juliya-provider.js +12 -0
  8. package/dist/adapters/react/server.d.ts +8 -0
  9. package/dist/adapters/react/server.js +11 -0
  10. package/dist/adapters/react/types.d.ts +6 -0
  11. package/dist/adapters/react/types.js +1 -0
  12. package/dist/adapters/react/use-kowrap.d.ts +29 -0
  13. package/dist/adapters/react/use-kowrap.js +19 -0
  14. package/dist/adapters/react/use-wrap-layout.d.ts +19 -0
  15. package/dist/adapters/react/use-wrap-layout.js +26 -0
  16. package/dist/adapters/react/wrap-text.d.ts +13 -0
  17. package/dist/adapters/react/wrap-text.js +78 -0
  18. package/dist/adapters/svelte/index.d.ts +6 -0
  19. package/dist/adapters/svelte/index.js +5 -0
  20. package/dist/adapters/vue/index.d.ts +11 -0
  21. package/dist/adapters/vue/index.js +14 -0
  22. package/dist/core/boundaries.d.ts +3 -0
  23. package/dist/core/boundaries.js +86 -0
  24. package/dist/core/layout.d.ts +2 -0
  25. package/dist/core/layout.js +56 -0
  26. package/dist/core/locales/create.d.ts +7 -0
  27. package/dist/core/locales/create.js +7 -0
  28. package/dist/core/locales/en.d.ts +3 -0
  29. package/dist/core/locales/en.js +2 -0
  30. package/dist/core/locales/ja.d.ts +3 -0
  31. package/dist/core/locales/ja.js +2 -0
  32. package/dist/core/locales/ko.d.ts +3 -0
  33. package/dist/core/locales/ko.js +2 -0
  34. package/dist/core/locales/zh.d.ts +3 -0
  35. package/dist/core/locales/zh.js +2 -0
  36. package/dist/core/scoring.d.ts +2 -0
  37. package/dist/core/scoring.js +50 -0
  38. package/dist/core/segmentation.d.ts +17 -0
  39. package/dist/core/segmentation.js +53 -0
  40. package/dist/core/types.d.ts +46 -0
  41. package/dist/core/types.js +1 -0
  42. package/dist/core/wrap.d.ts +2 -0
  43. package/dist/core/wrap.js +40 -0
  44. package/dist/dom/index.d.ts +5 -0
  45. package/dist/dom/index.js +3 -0
  46. package/dist/dom/inline.d.ts +24 -0
  47. package/dist/dom/inline.js +117 -0
  48. package/dist/dom/measure.d.ts +10 -0
  49. package/dist/dom/measure.js +18 -0
  50. package/dist/dom/observe-element.d.ts +11 -0
  51. package/dist/dom/observe-element.js +102 -0
  52. package/dist/dom/observe.d.ts +2 -0
  53. package/dist/dom/observe.js +37 -0
  54. package/dist/dom/render.d.ts +2 -0
  55. package/dist/dom/render.js +66 -0
  56. package/dist/dom/types.d.ts +20 -0
  57. package/dist/dom/types.js +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.js +2 -0
  60. package/package.json +76 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oddmash contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE.md ADDED
@@ -0,0 +1,7 @@
1
+ # Licensing and attribution
2
+
3
+ Copyright (c) 2026 Oddmash contributors.
4
+
5
+ The [MIT License](LICENSE) applies to original source code and documentation in this repository. It does not grant trademark rights or an endorsement by Oddmash. Official Oddmash logos, character artwork and other standalone branding assets are separate from the licensed source and documentation unless expressly identified otherwise. Third-party marks and assets remain subject to their own applicable terms.
6
+
7
+ This notice identifies the licensed material and separate rights. It does not impose additional conditions on material licensed under MIT.
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # 줄이야 (Juliya)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 한국어, 영어, 일본어, 중국어 간체의 줄바꿈 경계와 실제 화면 폭을 함께 고려하는 라이브러리입니다. 기존 Kowrap의 공개 API와 한국어 기본 동작을 유지합니다.
4
+
5
+ 한국어 어절, 영어 수식 관계, 일본어·중국어의 연속 텍스트와 문장부호를 고려합니다. 언어별 규칙은 휴리스틱이며 모든 문장의 의미를 완벽하게 분석한다는 보장은 없습니다.
6
+
7
+ [체험하기](https://oddmash.github.io/kowrap/#playground) | [문서](https://oddmash.github.io/kowrap/docs/) | [npm](https://www.npmjs.com/package/@oddmash/kowrap)
8
+
9
+ 랜딩에서는 선택한 언어의 다양한 예제를 표시하고 폭에 따라 실제 줄바꿈 위치가 변화하는 모습을 시연합니다.
10
+
11
+ ## 언어 선택
12
+
13
+ 신규 언어 진입점이 포함된 버전에서는 하나의 패키지에서 원하는 언어를 선택합니다.
14
+
15
+ ```ts
16
+ import { wrap } from '@oddmash/kowrap/ja';
17
+
18
+ const lines = wrap('読みやすい文章を、もっと自然に。', {
19
+ width: 10,
20
+ measure: text => [...text].length,
21
+ });
22
+ ```
23
+
24
+ 지원 경로는 `/ko`, `/en`, `/ja`, `/zh`입니다. 기존 루트의 `wrap(text, { width, measure })`는 한국어를 유지하며, `locale` 옵션으로 명시적으로 변경할 수 있습니다. React, DOM, Vue, Svelte의 기존 진입점은 유지합니다.
25
+
26
+ 새 브랜드 패키지 `@oddmash/juliya`는 동일한 구현과 언어별 진입점으로 발행할 예정입니다. 신규 패키지가 발행되면 `@oddmash/juliya/ko`, `@oddmash/juliya/en`, `@oddmash/juliya/ja`, `@oddmash/juliya/zh`로 가져올 수 있습니다. 기존 패키지는 삭제하거나 덮어쓰지 않습니다.
27
+
28
+ ## React에서 언어 선택
29
+
30
+ 신규 버전의 `JuliyaProvider`로 애플리케이션 언어를 한 번 설정하면 그 하위의 `JuliyaText`와 `useJuliya`가 언어를 공유합니다.
31
+
32
+ ```tsx
33
+ import { JuliyaProvider, JuliyaText } from '@oddmash/juliya/react';
34
+
35
+ <JuliyaProvider locale="ja">
36
+ <JuliyaText as="h1">読みやすい文章を、もっと自然に。</JuliyaText>
37
+ <JuliyaText as="p">画面の幅に合わせて改行します。</JuliyaText>
38
+ </JuliyaProvider>
39
+ ```
40
+
41
+ 개별 문장에 다른 언어를 적용하려면 `locale`을 직접 지정할 수 있습니다. Provider를 사용하지 않으면 기본 언어는 한국어입니다. 기존 `WrapText`, `useKowrap` 이름은 계속 사용할 수 있습니다. 예제의 새 패키지명은 신규 패키지가 발행된 뒤 사용할 수 있습니다.
42
+
43
+ 두 패키지를 함께 사용하는 경우 Provider와 하위 컴포넌트는 동일한 패키지에서 가져오세요. [React 및 i18n 연동 예제](docs/guide/react.md)를 참고하세요.
44
+
45
+ ## HTML에서 바로 실행하기
46
+
47
+ 아래 코드를 `index.html`로 저장하고 인터넷에 연결된 브라우저에서 열면 jsDelivr가 Kowrap `0.3.0`을 불러옵니다.
48
+
49
+ ```html
50
+ <!doctype html>
51
+ <html lang="ko">
52
+ <meta charset="utf-8">
53
+ <title>Kowrap 예제</title>
54
+ <p id="title" style="max-width: 220px; font-size: 24px">팀의 모든 문서를 한곳에서 관리하세요</p>
55
+ <script type="module">
56
+ import { mountKowrap } from 'https://cdn.jsdelivr.net/npm/@oddmash/kowrap@0.3.0/dist/dom/index.js/+esm';
57
+
58
+ const title = document.getElementById('title');
59
+ mountKowrap(title, { text: title.textContent });
60
+ </script>
61
+ </html>
62
+ ```
63
+
64
+ ## 특징
65
+
66
+ - 한국어 어절을 보존하는 균형 잡힌 줄바꿈
67
+ - 화면 폭 변화에 따른 자동 재계산
68
+ - 의도적인 개행 위치 지정
69
+ - 강조, 링크 등 인라인 마크업 유지
70
+ - React, Next.js, Vue, Svelte 및 일반 HTML 지원
71
+
72
+ ## 지원 범위
73
+
74
+ kowrap은 제목과 짧은 문장에 적합합니다. 강조와 링크를 포함한 중첩 인라인 텍스트도 지원합니다.
75
+
76
+ [기여 안내](CONTRIBUTING.md)
@@ -0,0 +1,6 @@
1
+ export type { JuliyaTextProps, WrapTextProps } from "./wrap-text.js";
2
+ export { JuliyaText, WrapText } from "./wrap-text.js";
3
+ export type { UseJuliyaOptions, UseKowrapOptions } from "./use-kowrap.js";
4
+ export { useJuliya, useKowrap } from "./use-kowrap.js";
5
+ export type { JuliyaProviderProps } from "./juliya-provider.js";
6
+ export { JuliyaProvider } from "./juliya-provider.js";
@@ -0,0 +1,4 @@
1
+ "use client";
2
+ export { JuliyaText, WrapText } from "./wrap-text.js";
3
+ export { useJuliya, useKowrap } from "./use-kowrap.js";
4
+ export { JuliyaProvider } from "./juliya-provider.js";
@@ -0,0 +1,8 @@
1
+ import type { ReactNode } from "react";
2
+ import type { WrapLocale } from "../../core/types.js";
3
+ export interface JuliyaProviderProps {
4
+ locale?: WrapLocale;
5
+ children: ReactNode;
6
+ }
7
+ export declare const useJuliyaLocale: (locale?: WrapLocale) => WrapLocale | undefined;
8
+ export declare const JuliyaProvider: ({ locale, children }: JuliyaProviderProps) => import("react").JSX.Element;
@@ -0,0 +1,12 @@
1
+ "use client";
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;
8
+ };
9
+ export const JuliyaProvider = ({ locale, children }) => {
10
+ const resolvedLocale = useJuliyaLocale(locale);
11
+ return _jsx(LocaleContext.Provider, { value: resolvedLocale, children: children });
12
+ };
@@ -0,0 +1,8 @@
1
+ import type { TextProps } from "./types.js";
2
+ export interface SentenceTextProps extends TextProps {
3
+ locale?: string;
4
+ forcedBreaks?: readonly number[];
5
+ }
6
+ export declare const SentenceText: ({ children, as: Tag, locale, forcedBreaks, style, ...props }: SentenceTextProps) => import("react").JSX.Element;
7
+ export type JuliyaSentenceTextProps = SentenceTextProps;
8
+ export declare const JuliyaSentenceText: ({ children, as: Tag, locale, forcedBreaks, style, ...props }: SentenceTextProps) => import("react").JSX.Element;
@@ -0,0 +1,11 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Fragment } from "react";
3
+ import { manualLines, segmentSentences } from "../../core/segmentation.js";
4
+ export const SentenceText = ({ children, as: Tag = "span", locale = "ko", forcedBreaks, style, ...props }) => {
5
+ const blocks = forcedBreaks?.length ? manualLines(children, forcedBreaks) : [{ text: children, start: 0, breakAfter: "" }];
6
+ return _jsx(Tag, { ...props, style: { whiteSpace: "pre-wrap", wordBreak: "keep-all", overflowWrap: "anywhere", ...style }, children: blocks.map((block, index) => _jsxs(Fragment, { children: [segmentSentences(block.text, locale).map(({ text, start }) => {
7
+ const content = text.trimEnd();
8
+ return _jsxs(Fragment, { children: [content && _jsx("span", { style: { display: "inline-block", maxWidth: "100%" }, children: content }), text.slice(content.length)] }, start);
9
+ }), block.breakAfter || (index < blocks.length - 1 ? _jsx("br", {}) : null)] }, block.start)) });
10
+ };
11
+ export const JuliyaSentenceText = SentenceText;
@@ -0,0 +1,6 @@
1
+ import type { HTMLAttributes } from "react";
2
+ export type TextTag = "span" | "p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
3
+ export interface TextProps extends Omit<HTMLAttributes<HTMLElement>, "children" | "dangerouslySetInnerHTML"> {
4
+ children: string;
5
+ as?: TextTag;
6
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ import type { CSSProperties } from "react";
2
+ import type { KowrapOptions } from "../../dom/types.js";
3
+ import type { TextTag } from "./types.js";
4
+ export interface UseKowrapOptions extends KowrapOptions {
5
+ initialForcedBreaks?: readonly number[];
6
+ onForcedBreaksChange?: (breaks: readonly number[]) => void;
7
+ style?: CSSProperties;
8
+ className?: string;
9
+ tag?: TextTag;
10
+ }
11
+ export type UseJuliyaOptions = UseKowrapOptions;
12
+ export declare const useJuliya: ({ text, locale: explicitLocale, strategy, breakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks, onForcedBreaksChange, style, className, tag, }: UseJuliyaOptions) => {
13
+ locale: import("../../index.js").WrapLocale;
14
+ forcedBreaks: readonly number[];
15
+ setForcedBreaks: (breaks: readonly number[]) => void;
16
+ clearForcedBreaks: () => void;
17
+ ref: (element: HTMLElement | null) => void;
18
+ lines: import("../../index.js").WrappedLine[];
19
+ measured: boolean;
20
+ };
21
+ export declare const useKowrap: ({ text, locale: explicitLocale, strategy, breakLongWords, forcedBreaks: controlledBreaks, initialForcedBreaks, onForcedBreaksChange, style, className, tag, }: UseJuliyaOptions) => {
22
+ locale: import("../../index.js").WrapLocale;
23
+ forcedBreaks: readonly number[];
24
+ setForcedBreaks: (breaks: readonly number[]) => void;
25
+ clearForcedBreaks: () => void;
26
+ ref: (element: HTMLElement | null) => void;
27
+ lines: import("../../index.js").WrappedLine[];
28
+ measured: boolean;
29
+ };
@@ -0,0 +1,19 @@
1
+ import { useCallback, useState } from "react";
2
+ import { manualLines } from "../../core/segmentation.js";
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);
7
+ const [internal, setInternal] = useState({ text, breaks: initialForcedBreaks });
8
+ const forcedBreaks = controlledBreaks ?? (internal.text === text ? internal.breaks : []);
9
+ const layout = useWrapLayout({ text, locale, strategy, breakLongWords, forcedBreaks, style, className, tag });
10
+ const setForcedBreaks = useCallback((breaks) => {
11
+ manualLines(text, breaks);
12
+ if (controlledBreaks === undefined)
13
+ setInternal({ text, breaks: [...breaks] });
14
+ onForcedBreaksChange?.(breaks);
15
+ }, [text, controlledBreaks, onForcedBreaksChange]);
16
+ const clearForcedBreaks = useCallback(() => setForcedBreaks([]), [setForcedBreaks]);
17
+ return { ...layout, locale: locale ?? "ko", forcedBreaks, setForcedBreaks, clearForcedBreaks };
18
+ };
19
+ export const useKowrap = useJuliya;
@@ -0,0 +1,19 @@
1
+ import type { CSSProperties } from "react";
2
+ import type { WrapOptions, WrappedLine } from "../../core/types.js";
3
+ import type { TextTag } from "./types.js";
4
+ interface LayoutOptions {
5
+ text: string;
6
+ locale?: WrapOptions["locale"];
7
+ strategy: NonNullable<WrapOptions["strategy"]>;
8
+ breakLongWords: boolean;
9
+ forcedBreaks?: readonly number[];
10
+ style?: CSSProperties;
11
+ className?: string;
12
+ tag: TextTag;
13
+ }
14
+ export declare const useWrapLayout: (options: LayoutOptions) => {
15
+ ref: (element: HTMLElement | null) => void;
16
+ lines: WrappedLine[];
17
+ measured: boolean;
18
+ };
19
+ export {};
@@ -0,0 +1,26 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { observeKowrap } from "../../dom/observe.js";
3
+ import { manualLines } from "../../core/segmentation.js";
4
+ const keyOf = (forcedBreaks) => forcedBreaks?.join(",") ?? "";
5
+ const matches = (layout, { text, locale, strategy, breakLongWords, forcedBreaks }) => layout?.text === text && layout.locale === locale && layout.strategy === strategy && layout.breakLongWords === breakLongWords && layout.breakKey === keyOf(forcedBreaks);
6
+ const sameBreaks = (previous, next) => previous.length === next.length && previous.every((line, index) => line.end === next[index]?.end && line.width === next[index]?.width);
7
+ export const useWrapLayout = (options) => {
8
+ const { text, locale, strategy, breakLongWords, forcedBreaks, style, className, tag } = options;
9
+ const breakKey = keyOf(forcedBreaks);
10
+ const fallback = useMemo(() => manualLines(text, forcedBreaks), [text, breakKey]);
11
+ const elementRef = useRef(null);
12
+ const ref = useCallback((element) => { elementRef.current = element; }, []);
13
+ const [layout, setLayout] = useState();
14
+ useEffect(() => {
15
+ const element = elementRef.current;
16
+ if (!element)
17
+ return;
18
+ const controller = observeKowrap(element, { text, locale, strategy, breakLongWords, forcedBreaks }, ({ lines, measured }) => {
19
+ setLayout((previous) => matches(previous, { text, locale, strategy, breakLongWords, forcedBreaks, tag }) && previous.measured === measured && sameBreaks(previous.lines, lines)
20
+ ? previous : { text, locale, strategy, breakLongWords, breakKey, measured, lines });
21
+ });
22
+ return controller.destroy;
23
+ }, [text, locale, strategy, breakLongWords, breakKey, style, className, tag]);
24
+ const current = matches(layout, options) ? layout : undefined;
25
+ return { ref, lines: current?.lines ?? fallback, measured: current?.measured ?? false };
26
+ };
@@ -0,0 +1,13 @@
1
+ import type { ReactNode } from "react";
2
+ import type { WrapOptions } from "../../core/types.js";
3
+ import type { TextProps } from "./types.js";
4
+ export interface WrapTextProps extends Omit<TextProps, "children"> {
5
+ children: ReactNode;
6
+ locale?: WrapOptions["locale"];
7
+ strategy?: WrapOptions["strategy"];
8
+ breakLongWords?: boolean;
9
+ forcedBreaks?: readonly number[];
10
+ }
11
+ export type JuliyaTextProps = WrapTextProps;
12
+ export declare const JuliyaText: (props: JuliyaTextProps) => import("react").JSX.Element;
13
+ export declare const WrapText: (props: JuliyaTextProps) => import("react").JSX.Element;
@@ -0,0 +1,78 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Children, cloneElement, Fragment, isValidElement, useEffect, useRef, useState } from "react";
4
+ import { useWrapLayout } from "./use-wrap-layout.js";
5
+ import { useJuliyaLocale } from "./juliya-provider.js";
6
+ import { breakOffsets, inlineBreakAttribute, observeInline } from "../../dom/inline.js";
7
+ import { manualLines } from "../../core/segmentation.js";
8
+ const baseStyle = {
9
+ display: "block",
10
+ whiteSpace: "pre-wrap",
11
+ wordBreak: "keep-all",
12
+ overflowWrap: "anywhere",
13
+ textWrap: "pretty",
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 });
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 });
18
+ };
19
+ const inlineText = (children) => Children.toArray(children).map((child) => {
20
+ if (typeof child === "string" || typeof child === "number" || typeof child === "bigint")
21
+ return String(child);
22
+ if (isValidElement(child))
23
+ return child.type === "br" ? "\n" : inlineText(child.props.children);
24
+ return "";
25
+ }).join("");
26
+ const renderInline = (children, offsets) => {
27
+ let cursor = 0;
28
+ const visit = (nodes) => Children.map(nodes, (child) => {
29
+ if (typeof child === "string" || typeof child === "number" || typeof child === "bigint") {
30
+ const text = String(child);
31
+ const start = cursor;
32
+ cursor += text.length;
33
+ const breaks = offsets.filter((offset) => start < offset && offset <= cursor);
34
+ if (!breaks.length)
35
+ return child;
36
+ let left = 0;
37
+ const parts = [];
38
+ for (const offset of breaks) {
39
+ parts.push(text.slice(left, offset - start), _jsx("br", { [inlineBreakAttribute]: "" }, offset));
40
+ left = offset - start;
41
+ }
42
+ parts.push(text.slice(left));
43
+ return _jsx(Fragment, { children: parts });
44
+ }
45
+ if (isValidElement(child)) {
46
+ if (child.type === "br") {
47
+ cursor++;
48
+ return child;
49
+ }
50
+ return cloneElement(child, undefined, visit(child.props.children));
51
+ }
52
+ return child;
53
+ });
54
+ return visit(children);
55
+ };
56
+ const InlineText = ({ children, as: Tag = "span", locale, strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, ...props }) => {
57
+ const ref = useRef(null);
58
+ const text = inlineText(children);
59
+ const key = `${text}:${locale ?? "ko"}:${forcedBreaks?.join(",") ?? ""}`;
60
+ const [layout, setLayout] = useState();
61
+ const offsets = layout?.key === key ? layout.offsets : breakOffsets(manualLines(text, forcedBreaks));
62
+ useEffect(() => {
63
+ if (!ref.current)
64
+ return;
65
+ const observer = observeInline(ref.current, () => ({ inline: true, locale, strategy, breakLongWords, forcedBreaks }), (next) => {
66
+ setLayout((previous) => previous?.key === key && previous.offsets.join(",") === next.join(",") ? previous : { key, offsets: next });
67
+ });
68
+ return observer.destroy;
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) });
71
+ };
72
+ export const JuliyaText = (props) => {
73
+ const locale = useJuliyaLocale(props.locale);
74
+ return typeof props.children === "string"
75
+ ? _jsx(PlainText, { ...props, locale: locale, children: props.children })
76
+ : _jsx(InlineText, { ...props, locale: locale });
77
+ };
78
+ export const WrapText = JuliyaText;
@@ -0,0 +1,6 @@
1
+ import type { MountKowrapOptions } from "../../dom/types.js";
2
+ export declare const kowrap: (element: HTMLElement, options: MountKowrapOptions) => {
3
+ update: (options: MountKowrapOptions) => void;
4
+ destroy: () => void;
5
+ };
6
+ export type { KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "../../dom/types.js";
@@ -0,0 +1,5 @@
1
+ import { mountKowrap } from "../../dom/render.js";
2
+ export const kowrap = (element, options) => {
3
+ const controller = mountKowrap(element, options);
4
+ return { update: controller.update, destroy: controller.destroy };
5
+ };
@@ -0,0 +1,11 @@
1
+ import type { MountKowrapOptions } from "../../dom/types.js";
2
+ interface Binding {
3
+ value: MountKowrapOptions;
4
+ }
5
+ export declare const kowrapDirective: {
6
+ mounted: (element: HTMLElement, binding: Binding) => void;
7
+ updated: (element: HTMLElement, binding: Binding) => void | undefined;
8
+ beforeUpdate: (element: HTMLElement) => void | undefined;
9
+ beforeUnmount: (element: HTMLElement) => void;
10
+ };
11
+ export type { KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "../../dom/types.js";
@@ -0,0 +1,14 @@
1
+ import { mountKowrap } from "../../dom/render.js";
2
+ const mounted = new WeakMap();
3
+ export const kowrapDirective = {
4
+ mounted: (element, binding) => {
5
+ mounted.get(element)?.destroy();
6
+ mounted.set(element, mountKowrap(element, binding.value));
7
+ },
8
+ updated: (element, binding) => mounted.get(element)?.update(binding.value),
9
+ beforeUpdate: (element) => mounted.get(element)?.restore?.(),
10
+ beforeUnmount: (element) => {
11
+ mounted.get(element)?.destroy();
12
+ mounted.delete(element);
13
+ },
14
+ };
@@ -0,0 +1,3 @@
1
+ import type { Boundary, LineCandidate, ParagraphOptions } from "./types.js";
2
+ export declare const boundariesOf: (text: string, options: ParagraphOptions) => Boundary[];
3
+ export declare const candidatesFrom: (text: string, points: Boundary[], start: number, { width, measure, measureRange }: ParagraphOptions) => Generator<LineCandidate>;
@@ -0,0 +1,86 @@
1
+ import { graphemesOf, isBreakableSpace, visibleText, wordBoundariesOf } from "./segmentation.js";
2
+ const cjk = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;
3
+ const opening = /[([{〈《「『【〔〖〘〚“‘(\[{]$/u;
4
+ const closing = /^[、。,.!?;:)]}〉》」』】〕〗〙〛”’、.,!?;:%)\]}ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮー々]/u;
5
+ const glue = /[\u00a0\u202f\u2060]/u;
6
+ const cjkBoundaries = (text, options) => {
7
+ const units = graphemesOf(text);
8
+ const words = wordBoundariesOf(text, options.locale === "ja" ? "ja" : "zh-Hans");
9
+ const points = [{ offset: 0, emergency: false }];
10
+ for (let i = 1; i < units.length; i++) {
11
+ const left = units[i - 1].segment;
12
+ const right = units[i].segment;
13
+ const offset = units[i].index;
14
+ if (opening.test(left) || closing.test(right) || glue.test(left) || glue.test(right) || isBreakableSpace(right))
15
+ continue;
16
+ if (isBreakableSpace(left) || cjk.test(left) || cjk.test(right) || words.has(offset)) {
17
+ points.push({ offset, emergency: !words.has(offset) && !isBreakableSpace(left) });
18
+ }
19
+ }
20
+ points.push({ offset: text.length, emergency: false });
21
+ if (!options.breakLongWords)
22
+ return points;
23
+ const expanded = [];
24
+ let cursor = 0;
25
+ for (let i = 0; i < points.length - 1; i++) {
26
+ const start = points[i].offset;
27
+ const end = points[i + 1].offset;
28
+ expanded.push(points[i]);
29
+ const fragment = visibleText(text.slice(start, end));
30
+ const measured = options.measureRange ? options.measureRange(start, start + fragment.length) : options.measure(fragment);
31
+ while (cursor < units.length && units[cursor].index <= start)
32
+ cursor++;
33
+ while (cursor < units.length && units[cursor].index < end) {
34
+ if (measured > options.width)
35
+ expanded.push({ offset: units[cursor].index, emergency: true });
36
+ cursor++;
37
+ }
38
+ }
39
+ expanded.push(points.at(-1));
40
+ return expanded;
41
+ };
42
+ export const boundariesOf = (text, options) => {
43
+ const { width, measure, measureRange, breakLongWords, locale } = options;
44
+ if (locale === "ja" || locale === "zh" || locale === "zh-Hans")
45
+ return cjkBoundaries(text, options);
46
+ const points = [{ offset: 0, emergency: false }];
47
+ const graphemes = graphemesOf(text);
48
+ let cursor = 0;
49
+ while (cursor < graphemes.length) {
50
+ while (cursor < graphemes.length && isBreakableSpace(graphemes[cursor].segment))
51
+ cursor++;
52
+ const start = cursor;
53
+ if (points.length === 1 && start > 0 && start < graphemes.length)
54
+ points.push({ offset: graphemes[start].index, emergency: true });
55
+ while (cursor < graphemes.length && !isBreakableSpace(graphemes[cursor].segment))
56
+ cursor++;
57
+ const end = cursor;
58
+ while (cursor < graphemes.length && isBreakableSpace(graphemes[cursor].segment))
59
+ cursor++;
60
+ if (breakLongWords && start < end) {
61
+ const wordStart = graphemes[start].index;
62
+ const wordEnd = graphemes[end]?.index ?? text.length;
63
+ if ((measureRange ? measureRange(wordStart, wordEnd) : measure(text.slice(wordStart, wordEnd))) > width) {
64
+ for (let i = start + 1; i < end; i++)
65
+ points.push({ offset: graphemes[i].index, emergency: true });
66
+ }
67
+ }
68
+ const offset = graphemes[cursor]?.index ?? text.length;
69
+ if (offset > points[points.length - 1].offset)
70
+ points.push({ offset, emergency: false });
71
+ }
72
+ return points;
73
+ };
74
+ export const candidatesFrom = function* (text, points, start, { width, measure, measureRange }) {
75
+ for (let next = start + 1; next < points.length; next++) {
76
+ const boundary = points[next];
77
+ const fragment = visibleText(text.slice(points[start].offset, boundary.offset));
78
+ const offset = points[start].offset;
79
+ const measured = measureRange ? measureRange(offset, offset + fragment.length) : measure(fragment);
80
+ if (measured > width && next > start + 1)
81
+ break;
82
+ yield { next, width: measured, fragment, emergency: boundary.emergency };
83
+ if (measured > width)
84
+ break;
85
+ }
86
+ };
@@ -0,0 +1,2 @@
1
+ import type { ParagraphOptions, PlannedLine } from "./types.js";
2
+ export declare const planParagraph: (text: string, options: ParagraphOptions) => PlannedLine[];
@@ -0,0 +1,56 @@
1
+ import { boundariesOf, candidatesFrom } from "./boundaries.js";
2
+ import { visibleText } from "./segmentation.js";
3
+ import { lineCost } from "./scoring.js";
4
+ const greedyPlan = (text, points, options) => {
5
+ const lines = [];
6
+ for (let start = 0; start < points.length - 1;) {
7
+ let chosen;
8
+ for (const candidate of candidatesFrom(text, points, start, options))
9
+ chosen = candidate;
10
+ if (!chosen)
11
+ throw new Error("No line candidate");
12
+ lines.push({ start: points[start].offset, end: points[chosen.next].offset, width: chosen.width });
13
+ start = chosen.next;
14
+ }
15
+ return lines;
16
+ };
17
+ const balancedPlan = (text, points, options) => {
18
+ const last = points.length - 1;
19
+ const choices = [];
20
+ const nextWords = (options.locale ?? "ko") === "ko"
21
+ ? points.map(({ offset }) => text.slice(offset).match(/^\S+/u)?.[0] ?? "")
22
+ : [];
23
+ choices[last] = { count: 0, cost: 0, next: last, width: 0 };
24
+ for (let start = last - 1; start >= 0; start--) {
25
+ let best;
26
+ for (const candidate of candidatesFrom(text, points, start, options)) {
27
+ const tail = choices[candidate.next];
28
+ const choice = {
29
+ count: tail.count + 1,
30
+ cost: tail.cost + lineCost(candidate, options.width, candidate.next === last, nextWords[candidate.next], options.locale),
31
+ next: candidate.next,
32
+ width: candidate.width,
33
+ };
34
+ if (!best || choice.count < best.count || (choice.count === best.count && choice.cost < best.cost))
35
+ best = choice;
36
+ }
37
+ if (!best)
38
+ throw new Error("No line candidate");
39
+ choices[start] = best;
40
+ }
41
+ const lines = [];
42
+ for (let start = 0; start < last;) {
43
+ const choice = choices[start];
44
+ lines.push({ start: points[start].offset, end: points[choice.next].offset, width: choice.width });
45
+ start = choice.next;
46
+ }
47
+ return lines;
48
+ };
49
+ export const planParagraph = (text, options) => {
50
+ const visible = visibleText(text);
51
+ 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 }];
54
+ const points = boundariesOf(text, options);
55
+ return options.strategy === "greedy" ? greedyPlan(text, points, options) : balancedPlan(text, points, options);
56
+ };
@@ -0,0 +1,7 @@
1
+ import type { WrapLocale, WrapOptions } from "../types.js";
2
+ export type LocaleWrapOptions = Omit<WrapOptions, "locale">;
3
+ export declare const createLocale: (locale: WrapLocale) => {
4
+ wrap: (text: string, options: LocaleWrapOptions) => import("../types.js").WrappedLine[];
5
+ segmentSentences: (text: string) => import("../types.js").TextSegment[];
6
+ splitLines: (text: string, offsets?: readonly number[]) => import("../types.js").WrappedLine[];
7
+ };
@@ -0,0 +1,7 @@
1
+ import { manualLines, segmentSentences as sentences } from "../segmentation.js";
2
+ import { wrap as wrapText } from "../wrap.js";
3
+ export const createLocale = (locale) => ({
4
+ wrap: (text, options) => wrapText(text, { ...options, locale }),
5
+ segmentSentences: (text) => sentences(text, locale),
6
+ splitLines: manualLines,
7
+ });
@@ -0,0 +1,3 @@
1
+ export type { LocaleWrapOptions as WrapOptions } from "./create.js";
2
+ export type { Measure, WrappedLine, TextSegment } from "../types.js";
3
+ export declare const wrap: (text: string, options: import("./create.js").LocaleWrapOptions) => import("../types.js").WrappedLine[], segmentSentences: (text: string) => import("../types.js").TextSegment[], splitLines: (text: string, offsets?: readonly number[]) => import("../types.js").WrappedLine[];
@@ -0,0 +1,2 @@
1
+ import { createLocale } from "./create.js";
2
+ export const { wrap, segmentSentences, splitLines } = createLocale("en");
@@ -0,0 +1,3 @@
1
+ export type { LocaleWrapOptions as WrapOptions } from "./create.js";
2
+ export type { Measure, WrappedLine, TextSegment } from "../types.js";
3
+ export declare const wrap: (text: string, options: import("./create.js").LocaleWrapOptions) => import("../types.js").WrappedLine[], segmentSentences: (text: string) => import("../types.js").TextSegment[], splitLines: (text: string, offsets?: readonly number[]) => import("../types.js").WrappedLine[];
@@ -0,0 +1,2 @@
1
+ import { createLocale } from "./create.js";
2
+ export const { wrap, segmentSentences, splitLines } = createLocale("ja");
@@ -0,0 +1,3 @@
1
+ export type { LocaleWrapOptions as WrapOptions } from "./create.js";
2
+ export type { Measure, WrappedLine, TextSegment } from "../types.js";
3
+ export declare const wrap: (text: string, options: import("./create.js").LocaleWrapOptions) => import("../types.js").WrappedLine[], segmentSentences: (text: string) => import("../types.js").TextSegment[], splitLines: (text: string, offsets?: readonly number[]) => import("../types.js").WrappedLine[];
@@ -0,0 +1,2 @@
1
+ import { createLocale } from "./create.js";
2
+ export const { wrap, segmentSentences, splitLines } = createLocale("ko");
@@ -0,0 +1,3 @@
1
+ export type { LocaleWrapOptions as WrapOptions } from "./create.js";
2
+ export type { Measure, WrappedLine, TextSegment } from "../types.js";
3
+ export declare const wrap: (text: string, options: import("./create.js").LocaleWrapOptions) => import("../types.js").WrappedLine[], segmentSentences: (text: string) => import("../types.js").TextSegment[], splitLines: (text: string, offsets?: readonly number[]) => import("../types.js").WrappedLine[];
@@ -0,0 +1,2 @@
1
+ import { createLocale } from "./create.js";
2
+ export const { wrap, segmentSentences, splitLines } = createLocale("zh-Hans");
@@ -0,0 +1,2 @@
1
+ import type { LineCandidate, WrapLocale } from "./types.js";
2
+ export declare const lineCost: (candidate: LineCandidate, availableWidth: number, isLast: boolean, nextWord?: string, locale?: WrapLocale) => number;