@oddmash/kowrap 0.0.0-stage → 0.1.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
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # kowrap
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
+ 한국어 웹 서비스에서 제목과 문장이 어색하게 끊기지 않도록 돕는 줄바꿈 라이브러리입니다. 어절은 보존하고, 문장부호와 수식 관계를 고려하며, 주어진 폭에서 줄의 균형을 조절합니다.
4
+
5
+ 반응형 제목, 카드 설명, 알림 메시지처럼 좁은 화면에서도 자연스럽게 읽혀야 하는 텍스트를 위한 도구입니다.
6
+
7
+ ## 실제 줄바꿈 예시
8
+
9
+ 동일한 문장을 같은 폭(문자 수 기준 14)에서 줄바꿈한 kowrap 엔진의 실제 출력입니다.
10
+
11
+ | 일반적인 순차 줄바꿈 | kowrap 균형 줄바꿈 |
12
+ | --- | --- |
13
+ | 오늘은 모든 사람이 함께<br>자연스러운 한국어 줄바꿈을<br>경험합니다. | 오늘은 모든 사람이<br>함께 자연스러운 한국어<br>줄바꿈을 경험합니다. |
14
+
15
+ 같은 세 줄을 사용하면서 마지막 줄에 짧은 어절만 남는 현상을 줄입니다.
16
+
17
+ ## 주요 기능
18
+
19
+ - 한국어 어절 보존과 문장 경계 고려
20
+ - 줄 길이 균형 최적화 및 긴 어절 처리
21
+ - React 없이 사용할 수 있는 독립 JavaScript·TypeScript 엔진
22
+ - 실제 글자 폭을 반영하는 React 반응형 줄바꿈
23
+ - SSR 및 Next.js App Router의 Server Component 지원
24
+ - JavaScript 없이도 동작하는 문장 단위 CSS 줄바꿈
25
+
26
+ ## 지원 범위
27
+
28
+ kowrap은 제목과 짧은 일반 텍스트의 줄바꿈을 우선 최적화합니다. SSR의 최초 화면은 CSS 줄바꿈을 사용하며 하이드레이션 후 줄 위치가 달라질 수 있습니다. 인라인 JSX 마크업은 현재 지원하지 않습니다.
29
+
30
+ [사용 및 기여 안내](https://github.com/Oddmash/kowrap/blob/main/CONTRIBUTING.md) · [GitHub](https://github.com/Oddmash/kowrap)
@@ -0,0 +1,8 @@
1
+ import type { Measure } from "./index.js";
2
+ export interface CanvasMeasureOptions {
3
+ font: string;
4
+ letterSpacing?: string;
5
+ wordSpacing?: string;
6
+ fontKerning?: CanvasFontKerning;
7
+ }
8
+ export declare const createCanvasMeasure: (options: CanvasMeasureOptions, ownerDocument?: Document) => Measure;
@@ -0,0 +1,13 @@
1
+ export const createCanvasMeasure = (options, ownerDocument = document) => {
2
+ const context = ownerDocument.createElement("canvas").getContext("2d");
3
+ if (!context)
4
+ throw new Error("Canvas 2D measurement is unavailable");
5
+ context.font = options.font;
6
+ if (options.letterSpacing && "letterSpacing" in context)
7
+ context.letterSpacing = options.letterSpacing;
8
+ if (options.wordSpacing && "wordSpacing" in context)
9
+ context.wordSpacing = options.wordSpacing;
10
+ if (options.fontKerning)
11
+ context.fontKerning = options.fontKerning;
12
+ return (text) => context.measureText(text).width;
13
+ };
@@ -0,0 +1,21 @@
1
+ export type Measure = (text: string) => number;
2
+ export interface WrapOptions {
3
+ width: number;
4
+ measure: Measure;
5
+ strategy?: "balanced" | "greedy";
6
+ breakLongWords?: boolean;
7
+ }
8
+ export interface WrappedLine {
9
+ text: string;
10
+ start: number;
11
+ end: number;
12
+ width: number;
13
+ breakAfter: string;
14
+ }
15
+ export interface TextSegment {
16
+ text: string;
17
+ start: number;
18
+ end: number;
19
+ }
20
+ export declare const segmentSentences: (text: string, locale?: string) => TextSegment[];
21
+ export declare const wrap: (text: string, options: WrapOptions) => WrappedLine[];
package/dist/index.js ADDED
@@ -0,0 +1,103 @@
1
+ export const segmentSentences = (text, locale = "ko") => {
2
+ const sentences = new Intl.Segmenter(locale, { granularity: "sentence" });
3
+ return Array.from(sentences.segment(text), ({ segment, index }) => ({ text: segment, start: index, end: index + segment.length }));
4
+ };
5
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
6
+ const breakable = /[ \t\f\v\u2000-\u2006\u2008-\u200a\u205f\u3000]/u;
7
+ const trailing = /[ \t\f\v\u2000-\u2006\u2008-\u200a\u205f\u3000]+$/u;
8
+ const hardBreak = /\r\n|[\r\n\u2028\u2029]/gu;
9
+ const sentenceEnd = /[.!?。!?…][”’"')\]]*$/u;
10
+ const clauseEnd = /[,;:,、;:]$/u;
11
+ const boundModifier = /(?:^|\s)(?:이|그|저|각|모든|어떤|이런|그런|저런|새로운|다음|해당|본|여러|\S+(?:들의|에서의|로서의|으로의|와의|과의|사이의))$/u;
12
+ const visible = (text) => text.replace(trailing, "");
13
+ const boundariesOf = (text, width, measure, split) => {
14
+ const points = [{ offset: 0, emergency: false }];
15
+ const graphemes = [...segmenter.segment(text)];
16
+ let cursor = 0;
17
+ while (cursor < graphemes.length) {
18
+ while (cursor < graphemes.length && breakable.test(graphemes[cursor].segment))
19
+ cursor++;
20
+ const start = cursor;
21
+ if (points.length === 1 && start > 0 && start < graphemes.length)
22
+ points.push({ offset: graphemes[start].index, emergency: true });
23
+ while (cursor < graphemes.length && !breakable.test(graphemes[cursor].segment))
24
+ cursor++;
25
+ const end = cursor;
26
+ while (cursor < graphemes.length && breakable.test(graphemes[cursor].segment))
27
+ cursor++;
28
+ if (split && start < end) {
29
+ const wordStart = graphemes[start].index;
30
+ const wordEnd = graphemes[end]?.index ?? text.length;
31
+ if (measure(text.slice(wordStart, wordEnd)) > width) {
32
+ for (let i = start + 1; i < end; i++) {
33
+ points.push({ offset: graphemes[i].index, emergency: true });
34
+ }
35
+ }
36
+ }
37
+ const offset = graphemes[cursor]?.index ?? text.length;
38
+ if (offset > points[points.length - 1].offset)
39
+ points.push({ offset, emergency: false });
40
+ }
41
+ return points;
42
+ };
43
+ const wrapParagraph = (text, base, options, measure) => {
44
+ const width = options.width;
45
+ const fullWidth = measure(visible(text));
46
+ if (!text || fullWidth <= width)
47
+ return [{ text, start: base, end: base + text.length, width: fullWidth, breakAfter: "" }];
48
+ const points = boundariesOf(text, width, measure, options.breakLongWords !== false);
49
+ const last = points.length - 1;
50
+ const choices = [];
51
+ choices[last] = { count: 0, cost: 0, next: last, width: 0 };
52
+ for (let i = last - 1; i >= 0; i--) {
53
+ let best;
54
+ for (let j = i + 1; j <= last; j++) {
55
+ const fragment = visible(text.slice(points[i].offset, points[j].offset));
56
+ const measured = measure(fragment);
57
+ if (measured > width && j > i + 1)
58
+ break;
59
+ const tail = choices[j];
60
+ const slack = (width - Math.min(measured, width)) / width;
61
+ const overflow = Math.max(0, measured - width) / width;
62
+ const boundaryCost = points[j].emergency ? 0.75 : sentenceEnd.test(fragment) ? 0 : clauseEnd.test(fragment) ? 0.02 : boundModifier.test(fragment) ? 0.35 : 0.06;
63
+ const cost = tail.cost + slack ** 2 + overflow ** 2 * 4 + (j === last ? 0 : boundaryCost);
64
+ const next = { count: tail.count + 1, cost, next: j, width: measured };
65
+ if (options.strategy === "greedy" || !best || next.count < best.count || (next.count === best.count && next.cost < best.cost))
66
+ best = next;
67
+ if (measured > width)
68
+ break;
69
+ }
70
+ choices[i] = best;
71
+ }
72
+ const lines = [];
73
+ for (let i = 0; i < last;) {
74
+ const choice = choices[i];
75
+ const start = points[i].offset;
76
+ const end = points[choice.next].offset;
77
+ lines.push({ text: text.slice(start, end), start: base + start, end: base + end, width: choice.width, breakAfter: "" });
78
+ i = choice.next;
79
+ }
80
+ return lines;
81
+ };
82
+ export const wrap = (text, options) => {
83
+ if (!Number.isFinite(options.width) || options.width <= 0)
84
+ throw new RangeError("width must be positive and finite");
85
+ const measure = (value) => {
86
+ if (!value)
87
+ return 0;
88
+ const result = options.measure(value);
89
+ if (!Number.isFinite(result) || result < 0)
90
+ throw new RangeError("measure must return a non-negative finite number");
91
+ return result;
92
+ };
93
+ const lines = [];
94
+ let start = 0;
95
+ for (const match of text.matchAll(hardBreak)) {
96
+ const paragraph = wrapParagraph(text.slice(start, match.index), start, options, measure);
97
+ paragraph[paragraph.length - 1].breakAfter = match[0];
98
+ lines.push(...paragraph);
99
+ start = match.index + match[0].length;
100
+ }
101
+ lines.push(...wrapParagraph(text.slice(start), start, options, measure));
102
+ return lines;
103
+ };
@@ -0,0 +1,9 @@
1
+ import type { HTMLAttributes } from "react";
2
+ import type { WrapOptions } from "./index.js";
3
+ export interface WrapTextProps extends Omit<HTMLAttributes<HTMLElement>, "children" | "dangerouslySetInnerHTML"> {
4
+ children: string;
5
+ as?: "span" | "p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
6
+ strategy?: WrapOptions["strategy"];
7
+ breakLongWords?: boolean;
8
+ }
9
+ export declare const WrapText: ({ children, as: Tag, strategy, breakLongWords, style, className, ...props }: WrapTextProps) => import("react").JSX.Element;
package/dist/react.js ADDED
@@ -0,0 +1,61 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Fragment, useEffect, useRef, useState } from "react";
4
+ import { createCanvasMeasure } from "./browser.js";
5
+ import { wrap } from "./index.js";
6
+ const baseStyle = {
7
+ display: "block",
8
+ whiteSpace: "pre-wrap",
9
+ wordBreak: "keep-all",
10
+ overflowWrap: "anywhere",
11
+ textWrap: "pretty",
12
+ };
13
+ export const WrapText = ({ children, as: Tag = "span", strategy = "balanced", breakLongWords = true, style, className, ...props }) => {
14
+ const ref = useRef(null);
15
+ const [layout, setLayout] = useState();
16
+ useEffect(() => {
17
+ const element = ref.current;
18
+ if (!element)
19
+ return;
20
+ const doc = element.ownerDocument;
21
+ const view = doc.defaultView;
22
+ if (!view)
23
+ return;
24
+ let active = true;
25
+ const update = () => {
26
+ if (!active)
27
+ return;
28
+ const computed = view.getComputedStyle(element);
29
+ const width = element.clientWidth - parseFloat(computed.paddingLeft || "0") - parseFloat(computed.paddingRight || "0");
30
+ if (!(width > 0))
31
+ return;
32
+ try {
33
+ const measure = createCanvasMeasure({
34
+ font: computed.font || `${computed.fontStyle} ${computed.fontWeight} ${computed.fontSize} ${computed.fontFamily}`,
35
+ letterSpacing: computed.letterSpacing === "normal" ? "0px" : computed.letterSpacing,
36
+ wordSpacing: computed.wordSpacing === "normal" ? "0px" : computed.wordSpacing,
37
+ fontKerning: computed.fontKerning,
38
+ }, doc);
39
+ const lines = wrap(children, { width: Math.max(1, width - 1), measure, strategy, breakLongWords });
40
+ setLayout((previous) => previous?.text === children && previous.strategy === strategy && previous.breakLongWords === breakLongWords && previous.lines.length === lines.length && previous.lines.every((line, index) => line.end === lines[index]?.end) ? previous : { text: children, strategy, breakLongWords, lines });
41
+ }
42
+ catch {
43
+ setLayout(undefined);
44
+ }
45
+ };
46
+ const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(update);
47
+ observer?.observe(element);
48
+ view.addEventListener("resize", update);
49
+ doc.fonts?.addEventListener("loadingdone", update);
50
+ void doc.fonts?.ready.then(update);
51
+ update();
52
+ return () => {
53
+ active = false;
54
+ observer?.disconnect();
55
+ view.removeEventListener("resize", update);
56
+ doc.fonts?.removeEventListener("loadingdone", update);
57
+ };
58
+ }, [children, strategy, breakLongWords, style, className, Tag]);
59
+ const lines = layout?.text === children && layout.strategy === strategy && layout.breakLongWords === breakLongWords ? layout.lines : undefined;
60
+ return _jsx(Tag, { ...props, className: className, style: { ...baseStyle, overflowWrap: breakLongWords ? "anywhere" : "normal", ...style }, ref: (element) => { ref.current = element; }, children: lines && lines.length > 1 ? lines.map((line, index) => _jsxs(Fragment, { children: [line.text, line.breakAfter || (index < lines.length - 1 ? _jsx("br", {}) : null)] }, line.start)) : children });
61
+ };
@@ -0,0 +1,8 @@
1
+ import type { HTMLAttributes } from "react";
2
+ import type { WrapTextProps } from "./react.js";
3
+ export interface SentenceTextProps extends Omit<HTMLAttributes<HTMLElement>, "children" | "dangerouslySetInnerHTML"> {
4
+ children: string;
5
+ as?: WrapTextProps["as"];
6
+ locale?: string;
7
+ }
8
+ export declare const SentenceText: ({ children, as: Tag, locale, style, ...props }: SentenceTextProps) => import("react").JSX.Element;
package/dist/server.js ADDED
@@ -0,0 +1,10 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Fragment } from "react";
3
+ import { segmentSentences } from "./index.js";
4
+ export const SentenceText = ({ children, as: Tag = "span", locale = "ko", style, ...props }) => {
5
+ const segments = segmentSentences(children, locale);
6
+ return _jsx(Tag, { ...props, style: { whiteSpace: "pre-wrap", wordBreak: "keep-all", overflowWrap: "anywhere", ...style }, children: segments.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
+ }) });
10
+ };
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@oddmash/kowrap",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Korean-aware text wrapping for JavaScript and React",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
8
+ "./browser": { "types": "./dist/browser.d.ts", "import": "./dist/browser.js" },
9
+ "./react": { "types": "./dist/react.d.ts", "import": "./dist/react.js" },
10
+ "./react/server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" }
11
+ },
12
+ "files": ["dist", "README.md"],
13
+ "publishConfig": {
14
+ "access": "public",
15
+ "registry": "https://registry.npmjs.org/"
16
+ },
17
+ "sideEffects": false,
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "test": "npm run build && node --test test/*.test.mjs",
21
+ "test:next": "npm run build && npm --prefix test/next-app run build",
22
+ "test:hydration": "npm run build && npm --prefix test/next-app run test:hydration",
23
+ "test:browser": "npm run test:next && npm --prefix test/next-app run test:browser",
24
+ "test:package": "npm run build && node --test test/package.mjs",
25
+ "prepack": "npm run build"
26
+ },
27
+ "engines": { "node": ">=20" },
28
+ "peerDependencies": { "react": "^18.2.0 || ^19.0.0" },
29
+ "peerDependenciesMeta": { "react": { "optional": true } },
30
+ "devDependencies": {
31
+ "@types/react": "19.3.0",
32
+ "react": "19.3.1",
33
+ "react-dom": "19.3.1",
34
+ "typescript": "6.0.3"
35
+ },
36
+ "repository": { "type": "git", "url": "https://github.com/Oddmash/kowrap.git" }
37
+ }