@oddmash/kowrap 0.2.0 → 0.3.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 +29 -19
- package/dist/adapters/react/wrap-text.d.ts +4 -2
- package/dist/adapters/react/wrap-text.js +58 -2
- package/dist/adapters/svelte/index.d.ts +4 -4
- package/dist/adapters/vue/index.d.ts +4 -3
- package/dist/adapters/vue/index.js +1 -0
- package/dist/core/boundaries.d.ts +2 -2
- package/dist/core/boundaries.js +5 -4
- package/dist/core/layout.js +2 -1
- package/dist/core/scoring.js +1 -1
- package/dist/core/types.d.ts +2 -0
- package/dist/core/wrap.js +6 -1
- package/dist/dom/index.d.ts +1 -1
- package/dist/dom/inline.d.ts +24 -0
- package/dist/dom/inline.js +117 -0
- package/dist/dom/measure.d.ts +2 -0
- package/dist/dom/measure.js +7 -2
- package/dist/dom/observe-element.d.ts +2 -0
- package/dist/dom/observe-element.js +48 -12
- package/dist/dom/observe.js +4 -0
- package/dist/dom/render.d.ts +2 -2
- package/dist/dom/render.js +10 -0
- package/dist/dom/types.d.ts +8 -1
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -1,32 +1,42 @@
|
|
|
1
1
|
# kowrap
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
한국어를 읽는 흐름에 맞춰 자연스럽게 줄바꿈하는 라이브러리입니다.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
실제 글자 폭과 한국어 어절 및 문장 경계를 고려하여 제목과 문장의 줄바꿈을 최적화합니다.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
[체험하기](https://oddmash.github.io/kowrap/#playground) | [문서](https://oddmash.github.io/kowrap/docs/) | [npm](https://www.npmjs.com/package/@oddmash/kowrap)
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
[](https://oddmash.github.io/kowrap/#playground)
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
| --- | --- |
|
|
13
|
-
| 오늘은 모든 사람이 함께<br>자연스러운 한국어 줄바꿈을<br>경험합니다. | 오늘은 모든 사람이<br>함께 자연스러운 한국어<br>줄바꿈을 경험합니다. |
|
|
11
|
+
## HTML에서 바로 실행하기
|
|
14
12
|
|
|
15
|
-
|
|
13
|
+
아래 코드를 `index.html`로 저장하고 인터넷에 연결된 브라우저에서 열면 jsDelivr가 Kowrap `0.3.0`을 불러옵니다.
|
|
16
14
|
|
|
17
|
-
|
|
15
|
+
```html
|
|
16
|
+
<!doctype html>
|
|
17
|
+
<html lang="ko">
|
|
18
|
+
<meta charset="utf-8">
|
|
19
|
+
<title>Kowrap 예제</title>
|
|
20
|
+
<p id="title" style="max-width: 220px; font-size: 24px">팀의 모든 문서를 한곳에서 관리하세요</p>
|
|
21
|
+
<script type="module">
|
|
22
|
+
import { mountKowrap } from 'https://cdn.jsdelivr.net/npm/@oddmash/kowrap@0.3.0/dist/dom/index.js/+esm';
|
|
18
23
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
const title = document.getElementById('title');
|
|
25
|
+
mountKowrap(title, { text: title.textContent });
|
|
26
|
+
</script>
|
|
27
|
+
</html>
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## 특징
|
|
31
|
+
|
|
32
|
+
- 한국어 어절을 보존하는 균형 잡힌 줄바꿈
|
|
33
|
+
- 화면 폭 변화에 따른 자동 재계산
|
|
34
|
+
- 의도적인 개행 위치 지정
|
|
35
|
+
- 강조, 링크 등 인라인 마크업 유지
|
|
36
|
+
- React, Next.js, Vue, Svelte 및 일반 HTML 지원
|
|
27
37
|
|
|
28
38
|
## 지원 범위
|
|
29
39
|
|
|
30
|
-
kowrap은 제목과 짧은
|
|
40
|
+
kowrap은 제목과 짧은 문장에 적합합니다. 강조와 링크를 포함한 중첩 인라인 텍스트도 지원합니다.
|
|
31
41
|
|
|
32
|
-
[
|
|
42
|
+
[기여 안내](CONTRIBUTING.md)
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
1
2
|
import type { WrapOptions } from "../../core/types.js";
|
|
2
3
|
import type { TextProps } from "./types.js";
|
|
3
|
-
export interface WrapTextProps extends TextProps {
|
|
4
|
+
export interface WrapTextProps extends Omit<TextProps, "children"> {
|
|
5
|
+
children: ReactNode;
|
|
4
6
|
strategy?: WrapOptions["strategy"];
|
|
5
7
|
breakLongWords?: boolean;
|
|
6
8
|
forcedBreaks?: readonly number[];
|
|
7
9
|
}
|
|
8
|
-
export declare const WrapText: (
|
|
10
|
+
export declare const WrapText: (props: WrapTextProps) => import("react").JSX.Element;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
-
import { Fragment } from "react";
|
|
3
|
+
import { Children, cloneElement, Fragment, isValidElement, useEffect, useRef, useState } from "react";
|
|
4
4
|
import { useWrapLayout } from "./use-wrap-layout.js";
|
|
5
|
+
import { breakOffsets, inlineBreakAttribute, observeInline } from "../../dom/inline.js";
|
|
6
|
+
import { manualLines } from "../../core/segmentation.js";
|
|
5
7
|
const baseStyle = {
|
|
6
8
|
display: "block",
|
|
7
9
|
whiteSpace: "pre-wrap",
|
|
@@ -9,7 +11,61 @@ const baseStyle = {
|
|
|
9
11
|
overflowWrap: "anywhere",
|
|
10
12
|
textWrap: "pretty",
|
|
11
13
|
};
|
|
12
|
-
|
|
14
|
+
const PlainText = ({ children, as: Tag = "span", strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, ...props }) => {
|
|
13
15
|
const { ref, lines } = useWrapLayout({ text: children, strategy, breakLongWords, forcedBreaks, style, className, tag: Tag });
|
|
14
16
|
return _jsx(Tag, { ...props, 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 });
|
|
15
17
|
};
|
|
18
|
+
const inlineText = (children) => Children.toArray(children).map((child) => {
|
|
19
|
+
if (typeof child === "string" || typeof child === "number" || typeof child === "bigint")
|
|
20
|
+
return String(child);
|
|
21
|
+
if (isValidElement(child))
|
|
22
|
+
return child.type === "br" ? "\n" : inlineText(child.props.children);
|
|
23
|
+
return "";
|
|
24
|
+
}).join("");
|
|
25
|
+
const renderInline = (children, offsets) => {
|
|
26
|
+
let cursor = 0;
|
|
27
|
+
const visit = (nodes) => Children.map(nodes, (child) => {
|
|
28
|
+
if (typeof child === "string" || typeof child === "number" || typeof child === "bigint") {
|
|
29
|
+
const text = String(child);
|
|
30
|
+
const start = cursor;
|
|
31
|
+
cursor += text.length;
|
|
32
|
+
const breaks = offsets.filter((offset) => start < offset && offset <= cursor);
|
|
33
|
+
if (!breaks.length)
|
|
34
|
+
return child;
|
|
35
|
+
let left = 0;
|
|
36
|
+
const parts = [];
|
|
37
|
+
for (const offset of breaks) {
|
|
38
|
+
parts.push(text.slice(left, offset - start), _jsx("br", { [inlineBreakAttribute]: "" }, offset));
|
|
39
|
+
left = offset - start;
|
|
40
|
+
}
|
|
41
|
+
parts.push(text.slice(left));
|
|
42
|
+
return _jsx(Fragment, { children: parts });
|
|
43
|
+
}
|
|
44
|
+
if (isValidElement(child)) {
|
|
45
|
+
if (child.type === "br") {
|
|
46
|
+
cursor++;
|
|
47
|
+
return child;
|
|
48
|
+
}
|
|
49
|
+
return cloneElement(child, undefined, visit(child.props.children));
|
|
50
|
+
}
|
|
51
|
+
return child;
|
|
52
|
+
});
|
|
53
|
+
return visit(children);
|
|
54
|
+
};
|
|
55
|
+
const InlineText = ({ children, as: Tag = "span", strategy = "balanced", breakLongWords = true, forcedBreaks, style, className, ...props }) => {
|
|
56
|
+
const ref = useRef(null);
|
|
57
|
+
const text = inlineText(children);
|
|
58
|
+
const key = `${text}:${forcedBreaks?.join(",") ?? ""}`;
|
|
59
|
+
const [layout, setLayout] = useState();
|
|
60
|
+
const offsets = layout?.key === key ? layout.offsets : breakOffsets(manualLines(text, forcedBreaks));
|
|
61
|
+
useEffect(() => {
|
|
62
|
+
if (!ref.current)
|
|
63
|
+
return;
|
|
64
|
+
const observer = observeInline(ref.current, () => ({ inline: true, strategy, breakLongWords, forcedBreaks }), (next) => {
|
|
65
|
+
setLayout((previous) => previous?.key === key && previous.offsets.join(",") === next.join(",") ? previous : { key, offsets: next });
|
|
66
|
+
});
|
|
67
|
+
return observer.destroy;
|
|
68
|
+
}, [key, children, strategy, breakLongWords, style, className, Tag]);
|
|
69
|
+
return _jsx(Tag, { ...props, className: className, style: { ...baseStyle, overflowWrap: breakLongWords ? "anywhere" : "normal", ...style }, ref: (element) => { ref.current = element; }, children: renderInline(children, offsets) });
|
|
70
|
+
};
|
|
71
|
+
export const WrapText = (props) => typeof props.children === "string" ? _jsx(PlainText, { ...props, children: props.children }) : _jsx(InlineText, { ...props });
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export declare const kowrap: (element: HTMLElement, options:
|
|
3
|
-
update: (options:
|
|
1
|
+
import type { MountKowrapOptions } from "../../dom/types.js";
|
|
2
|
+
export declare const kowrap: (element: HTMLElement, options: MountKowrapOptions) => {
|
|
3
|
+
update: (options: MountKowrapOptions) => void;
|
|
4
4
|
destroy: () => void;
|
|
5
5
|
};
|
|
6
|
-
export type { KowrapOptions } from "../../dom/types.js";
|
|
6
|
+
export type { KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "../../dom/types.js";
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { MountKowrapOptions } from "../../dom/types.js";
|
|
2
2
|
interface Binding {
|
|
3
|
-
value:
|
|
3
|
+
value: MountKowrapOptions;
|
|
4
4
|
}
|
|
5
5
|
export declare const kowrapDirective: {
|
|
6
6
|
mounted: (element: HTMLElement, binding: Binding) => void;
|
|
7
7
|
updated: (element: HTMLElement, binding: Binding) => void | undefined;
|
|
8
|
+
beforeUpdate: (element: HTMLElement) => void | undefined;
|
|
8
9
|
beforeUnmount: (element: HTMLElement) => void;
|
|
9
10
|
};
|
|
10
|
-
export type { KowrapOptions } from "../../dom/types.js";
|
|
11
|
+
export type { KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "../../dom/types.js";
|
|
@@ -6,6 +6,7 @@ export const kowrapDirective = {
|
|
|
6
6
|
mounted.set(element, mountKowrap(element, binding.value));
|
|
7
7
|
},
|
|
8
8
|
updated: (element, binding) => mounted.get(element)?.update(binding.value),
|
|
9
|
+
beforeUpdate: (element) => mounted.get(element)?.restore?.(),
|
|
9
10
|
beforeUnmount: (element) => {
|
|
10
11
|
mounted.get(element)?.destroy();
|
|
11
12
|
mounted.delete(element);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { Boundary, LineCandidate, ParagraphOptions } from "./types.js";
|
|
2
|
-
export declare const boundariesOf: (text: string, { width, measure, breakLongWords }: ParagraphOptions) => Boundary[];
|
|
3
|
-
export declare const candidatesFrom: (text: string, points: Boundary[], start: number, { width, measure }: ParagraphOptions) => Generator<LineCandidate>;
|
|
2
|
+
export declare const boundariesOf: (text: string, { width, measure, measureRange, breakLongWords }: ParagraphOptions) => Boundary[];
|
|
3
|
+
export declare const candidatesFrom: (text: string, points: Boundary[], start: number, { width, measure, measureRange }: ParagraphOptions) => Generator<LineCandidate>;
|
package/dist/core/boundaries.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { graphemesOf, isBreakableSpace, visibleText } from "./segmentation.js";
|
|
2
|
-
export const boundariesOf = (text, { width, measure, breakLongWords }) => {
|
|
2
|
+
export const boundariesOf = (text, { width, measure, measureRange, breakLongWords }) => {
|
|
3
3
|
const points = [{ offset: 0, emergency: false }];
|
|
4
4
|
const graphemes = graphemesOf(text);
|
|
5
5
|
let cursor = 0;
|
|
@@ -17,7 +17,7 @@ export const boundariesOf = (text, { width, measure, breakLongWords }) => {
|
|
|
17
17
|
if (breakLongWords && start < end) {
|
|
18
18
|
const wordStart = graphemes[start].index;
|
|
19
19
|
const wordEnd = graphemes[end]?.index ?? text.length;
|
|
20
|
-
if (measure(text.slice(wordStart, wordEnd)) > width) {
|
|
20
|
+
if ((measureRange ? measureRange(wordStart, wordEnd) : measure(text.slice(wordStart, wordEnd))) > width) {
|
|
21
21
|
for (let i = start + 1; i < end; i++)
|
|
22
22
|
points.push({ offset: graphemes[i].index, emergency: true });
|
|
23
23
|
}
|
|
@@ -28,11 +28,12 @@ export const boundariesOf = (text, { width, measure, breakLongWords }) => {
|
|
|
28
28
|
}
|
|
29
29
|
return points;
|
|
30
30
|
};
|
|
31
|
-
export const candidatesFrom = function* (text, points, start, { width, measure }) {
|
|
31
|
+
export const candidatesFrom = function* (text, points, start, { width, measure, measureRange }) {
|
|
32
32
|
for (let next = start + 1; next < points.length; next++) {
|
|
33
33
|
const boundary = points[next];
|
|
34
34
|
const fragment = visibleText(text.slice(points[start].offset, boundary.offset));
|
|
35
|
-
const
|
|
35
|
+
const offset = points[start].offset;
|
|
36
|
+
const measured = measureRange ? measureRange(offset, offset + fragment.length) : measure(fragment);
|
|
36
37
|
if (measured > width && next > start + 1)
|
|
37
38
|
break;
|
|
38
39
|
yield { next, width: measured, fragment, emergency: boundary.emergency };
|
package/dist/core/layout.js
CHANGED
|
@@ -44,7 +44,8 @@ const balancedPlan = (text, points, options) => {
|
|
|
44
44
|
return lines;
|
|
45
45
|
};
|
|
46
46
|
export const planParagraph = (text, options) => {
|
|
47
|
-
const
|
|
47
|
+
const visible = visibleText(text);
|
|
48
|
+
const fullWidth = options.measureRange ? options.measureRange(0, visible.length) : options.measure(visible);
|
|
48
49
|
if (!text || fullWidth <= options.width)
|
|
49
50
|
return [{ start: 0, end: text.length, width: fullWidth }];
|
|
50
51
|
const points = boundariesOf(text, options);
|
package/dist/core/scoring.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const sentenceEnd = /[.!?。!?…][”’"')\]]*$/u;
|
|
2
2
|
const clauseEnd = /[,;:,、;:]$/u;
|
|
3
|
-
const boundModifier = /(?:^|\s)(
|
|
3
|
+
const boundModifier = /(?:^|\s)(?:이|그|저|각|모든|어떤|이런|그런|저런|다음|해당|본|여러|\S+(?:로운|스러운|적인|들의|에서의|로서의|으로의|와의|과의|사이의))$/u;
|
|
4
4
|
const boundaryCost = ({ fragment, emergency }) => {
|
|
5
5
|
if (emergency)
|
|
6
6
|
return 0.75;
|
package/dist/core/types.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export type Measure = (text: string) => number;
|
|
|
2
2
|
export interface WrapOptions {
|
|
3
3
|
width: number;
|
|
4
4
|
measure: Measure;
|
|
5
|
+
measureRange?: (start: number, end: number) => number;
|
|
5
6
|
strategy?: "balanced" | "greedy";
|
|
6
7
|
breakLongWords?: boolean;
|
|
7
8
|
forcedBreaks?: readonly number[];
|
|
@@ -21,6 +22,7 @@ export interface TextSegment {
|
|
|
21
22
|
export interface ParagraphOptions {
|
|
22
23
|
width: number;
|
|
23
24
|
measure: Measure;
|
|
25
|
+
measureRange?: (start: number, end: number) => number;
|
|
24
26
|
strategy: NonNullable<WrapOptions["strategy"]>;
|
|
25
27
|
breakLongWords: boolean;
|
|
26
28
|
}
|
package/dist/core/wrap.js
CHANGED
|
@@ -19,7 +19,12 @@ export const wrap = (text, options) => {
|
|
|
19
19
|
};
|
|
20
20
|
const lines = [];
|
|
21
21
|
for (const paragraph of segmentsWithBreaks(text, options.forcedBreaks)) {
|
|
22
|
-
const plan = planParagraph(paragraph.text, paragraphOptions)
|
|
22
|
+
const plan = planParagraph(paragraph.text, { ...paragraphOptions, measureRange: options.measureRange ? (start, end) => {
|
|
23
|
+
const result = options.measureRange(paragraph.start + start, paragraph.start + end);
|
|
24
|
+
if (!Number.isFinite(result) || result < 0)
|
|
25
|
+
throw new RangeError("measureRange must return a non-negative finite number");
|
|
26
|
+
return result;
|
|
27
|
+
} : undefined });
|
|
23
28
|
for (const [index, line] of plan.entries()) {
|
|
24
29
|
lines.push({
|
|
25
30
|
text: paragraph.text.slice(line.start, line.end),
|
package/dist/dom/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type { CanvasMeasureOptions } from "./measure.js";
|
|
2
2
|
export { createCanvasMeasure } from "./measure.js";
|
|
3
|
-
export type { KowrapController, KowrapLayout, KowrapOptions } from "./types.js";
|
|
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";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { WrappedLine } from "../core/types.js";
|
|
2
|
+
import type { InlineKowrapOptions } from "./types.js";
|
|
3
|
+
export declare const inlineBreakAttribute = "data-kowrap-break";
|
|
4
|
+
interface Run {
|
|
5
|
+
node: Text;
|
|
6
|
+
start: number;
|
|
7
|
+
end: number;
|
|
8
|
+
}
|
|
9
|
+
export declare const readInline: (element: HTMLElement) => {
|
|
10
|
+
text: string;
|
|
11
|
+
runs: Run[];
|
|
12
|
+
};
|
|
13
|
+
export declare const breakOffsets: (lines: WrappedLine[]) => number[];
|
|
14
|
+
export declare const observeInline: (element: HTMLElement, getOptions: () => InlineKowrapOptions, onBreaks: (offsets: number[]) => void) => {
|
|
15
|
+
refresh: () => void;
|
|
16
|
+
destroy: () => void;
|
|
17
|
+
};
|
|
18
|
+
export declare const mountInline: (element: HTMLElement, initial: InlineKowrapOptions) => {
|
|
19
|
+
update: (next: InlineKowrapOptions) => void;
|
|
20
|
+
refresh: () => void;
|
|
21
|
+
destroy: () => void;
|
|
22
|
+
restore: () => void;
|
|
23
|
+
};
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { manualLines } from "../core/segmentation.js";
|
|
2
|
+
import { wrap } from "../core/wrap.js";
|
|
3
|
+
import { createLocalizedCanvasMeasure, languageOf } from "./measure.js";
|
|
4
|
+
import { fontOf, observeElementLayout } from "./observe-element.js";
|
|
5
|
+
export const inlineBreakAttribute = "data-kowrap-break";
|
|
6
|
+
export const readInline = (element) => {
|
|
7
|
+
let text = "";
|
|
8
|
+
const runs = [];
|
|
9
|
+
const visit = (node) => {
|
|
10
|
+
if (node.nodeType === 3) {
|
|
11
|
+
const value = node.data;
|
|
12
|
+
runs.push({ node: node, start: text.length, end: text.length + value.length });
|
|
13
|
+
text += value;
|
|
14
|
+
}
|
|
15
|
+
else if (node.nodeType === 1) {
|
|
16
|
+
const child = node;
|
|
17
|
+
if (child.hasAttribute(inlineBreakAttribute))
|
|
18
|
+
return;
|
|
19
|
+
if (child.tagName === "BR")
|
|
20
|
+
text += "\n";
|
|
21
|
+
else
|
|
22
|
+
child.childNodes.forEach(visit);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
element.childNodes.forEach(visit);
|
|
26
|
+
return { text, runs };
|
|
27
|
+
};
|
|
28
|
+
export const breakOffsets = (lines) => lines.slice(0, -1).filter((line) => !line.breakAfter).map((line) => line.end);
|
|
29
|
+
export const observeInline = (element, getOptions, onBreaks) => observeElementLayout(element, (layout) => {
|
|
30
|
+
const { text, runs } = readInline(element);
|
|
31
|
+
const options = getOptions();
|
|
32
|
+
if (!layout) {
|
|
33
|
+
onBreaks(breakOffsets(manualLines(text, options.forcedBreaks)));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const view = element.ownerDocument.defaultView;
|
|
37
|
+
const measures = new Map();
|
|
38
|
+
const styled = [];
|
|
39
|
+
for (const run of runs) {
|
|
40
|
+
const parent = run.node.parentElement;
|
|
41
|
+
const font = fontOf(view.getComputedStyle(parent));
|
|
42
|
+
const language = languageOf(parent);
|
|
43
|
+
const key = JSON.stringify([font, language]);
|
|
44
|
+
let measure = measures.get(key);
|
|
45
|
+
if (!measure) {
|
|
46
|
+
measure = createLocalizedCanvasMeasure(font, element.ownerDocument, language);
|
|
47
|
+
measures.set(key, measure);
|
|
48
|
+
}
|
|
49
|
+
const previous = styled.at(-1);
|
|
50
|
+
if (previous?.key === key && previous.end === run.start)
|
|
51
|
+
previous.end = run.end;
|
|
52
|
+
else
|
|
53
|
+
styled.push({ start: run.start, end: run.end, key, measure });
|
|
54
|
+
}
|
|
55
|
+
const measureRange = (start, end) => styled.reduce((width, run) => {
|
|
56
|
+
const left = Math.max(start, run.start);
|
|
57
|
+
const right = Math.min(end, run.end);
|
|
58
|
+
return left < right ? width + run.measure(text.slice(left, right)) : width;
|
|
59
|
+
}, 0);
|
|
60
|
+
onBreaks(breakOffsets(wrap(text, { ...options, ...layout, measureRange })));
|
|
61
|
+
});
|
|
62
|
+
export const mountInline = (element, initial) => {
|
|
63
|
+
let options = initial;
|
|
64
|
+
let undo = [];
|
|
65
|
+
let previous = [];
|
|
66
|
+
let mutations;
|
|
67
|
+
const restore = () => {
|
|
68
|
+
undo.reverse().forEach((apply) => apply());
|
|
69
|
+
undo = [];
|
|
70
|
+
previous = [];
|
|
71
|
+
mutations?.takeRecords();
|
|
72
|
+
};
|
|
73
|
+
const render = (offsets) => {
|
|
74
|
+
if (offsets.join(",") === previous.join(","))
|
|
75
|
+
return;
|
|
76
|
+
restore();
|
|
77
|
+
const { runs } = readInline(element);
|
|
78
|
+
for (const offset of [...offsets].reverse()) {
|
|
79
|
+
const run = runs.find(({ start, end }) => start < offset && offset <= end);
|
|
80
|
+
if (!run)
|
|
81
|
+
continue;
|
|
82
|
+
const { node, start } = run;
|
|
83
|
+
const br = element.ownerDocument.createElement("br");
|
|
84
|
+
br.setAttribute(inlineBreakAttribute, "");
|
|
85
|
+
const position = offset - start;
|
|
86
|
+
if (position === node.length) {
|
|
87
|
+
node.after(br);
|
|
88
|
+
undo.push(() => br.remove());
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
const left = node.data.slice(0, position);
|
|
92
|
+
const tail = node.splitText(position);
|
|
93
|
+
node.after(br);
|
|
94
|
+
undo.push(() => {
|
|
95
|
+
if (node.data === left && node.parentNode === tail.parentNode)
|
|
96
|
+
node.appendData(tail.data);
|
|
97
|
+
tail.remove();
|
|
98
|
+
br.remove();
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
previous = offsets;
|
|
103
|
+
mutations?.takeRecords();
|
|
104
|
+
};
|
|
105
|
+
const observer = observeInline(element, () => options, render);
|
|
106
|
+
const Mutation = element.ownerDocument.defaultView?.MutationObserver;
|
|
107
|
+
if (Mutation) {
|
|
108
|
+
mutations = new Mutation(() => { restore(); observer.refresh(); });
|
|
109
|
+
mutations.observe(element, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["class", "style", "lang"] });
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
update: (next) => { restore(); options = next; observer.refresh(); },
|
|
113
|
+
refresh: () => { restore(); observer.refresh(); },
|
|
114
|
+
destroy: () => { observer.destroy(); mutations?.disconnect(); restore(); },
|
|
115
|
+
restore,
|
|
116
|
+
};
|
|
117
|
+
};
|
package/dist/dom/measure.d.ts
CHANGED
|
@@ -5,4 +5,6 @@ export interface CanvasMeasureOptions {
|
|
|
5
5
|
wordSpacing?: string;
|
|
6
6
|
fontKerning?: CanvasFontKerning;
|
|
7
7
|
}
|
|
8
|
+
export declare const createLocalizedCanvasMeasure: (options: CanvasMeasureOptions, ownerDocument: Document, language: string | undefined) => Measure;
|
|
8
9
|
export declare const createCanvasMeasure: (options: CanvasMeasureOptions, ownerDocument?: Document) => Measure;
|
|
10
|
+
export declare const languageOf: (element: HTMLElement) => string | undefined;
|
package/dist/dom/measure.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
export const
|
|
2
|
-
const
|
|
1
|
+
export const createLocalizedCanvasMeasure = (options, ownerDocument, language) => {
|
|
2
|
+
const canvas = ownerDocument.createElement("canvas");
|
|
3
|
+
if (language !== undefined)
|
|
4
|
+
canvas.lang = language;
|
|
5
|
+
const context = canvas.getContext("2d");
|
|
3
6
|
if (!context)
|
|
4
7
|
throw new Error("Canvas 2D measurement is unavailable");
|
|
5
8
|
context.font = options.font;
|
|
@@ -11,3 +14,5 @@ export const createCanvasMeasure = (options, ownerDocument = document) => {
|
|
|
11
14
|
context.fontKerning = options.fontKerning;
|
|
12
15
|
return (text) => context.measureText(text).width;
|
|
13
16
|
};
|
|
17
|
+
export const createCanvasMeasure = (options, ownerDocument = document) => createLocalizedCanvasMeasure(options, ownerDocument, ownerDocument.documentElement?.lang);
|
|
18
|
+
export const languageOf = (element) => element.closest("[lang]")?.getAttribute("lang") ?? undefined;
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { CanvasMeasureOptions } from "./measure.js";
|
|
1
2
|
import type { Measure } from "../core/types.js";
|
|
2
3
|
export interface ElementLayout {
|
|
3
4
|
width: number;
|
|
4
5
|
measure: Measure;
|
|
5
6
|
}
|
|
7
|
+
export declare const fontOf: (computed: CSSStyleDeclaration) => CanvasMeasureOptions;
|
|
6
8
|
export declare const observeElementLayout: (element: HTMLElement, onLayout: (layout: ElementLayout | undefined) => void) => {
|
|
7
9
|
refresh: () => void;
|
|
8
10
|
destroy: () => void;
|
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
const
|
|
1
|
+
import { createLocalizedCanvasMeasure, languageOf } from "./measure.js";
|
|
2
|
+
const numericLength = (value) => {
|
|
3
3
|
const parsed = Number.parseFloat(value);
|
|
4
4
|
return Number.isFinite(parsed) ? parsed : 0;
|
|
5
5
|
};
|
|
6
|
+
const computedContentWidth = (computed, padding, roundedWidth) => {
|
|
7
|
+
if (!computed.width.endsWith("px"))
|
|
8
|
+
return undefined;
|
|
9
|
+
const border = numericLength(computed.borderLeftWidth) + numericLength(computed.borderRightWidth);
|
|
10
|
+
const inset = computed.boxSizing === "border-box" ? padding + border : 0;
|
|
11
|
+
const width = Number.parseFloat(computed.width) - inset;
|
|
12
|
+
return width > 0 && Math.abs(width - roundedWidth) <= 0.5 ? width : undefined;
|
|
13
|
+
};
|
|
6
14
|
const spacing = (value) => value === "normal" || !value ? "0px" : value;
|
|
7
|
-
const fontOf = (computed) => ({
|
|
15
|
+
export const fontOf = (computed) => ({
|
|
8
16
|
font: computed.font || `${computed.fontStyle} ${computed.fontWeight} ${computed.fontSize} ${computed.fontFamily}`,
|
|
9
17
|
letterSpacing: spacing(computed.letterSpacing),
|
|
10
18
|
wordSpacing: spacing(computed.wordSpacing),
|
|
@@ -20,24 +28,36 @@ export const observeElementLayout = (element, onLayout) => {
|
|
|
20
28
|
let active = true;
|
|
21
29
|
let previousFont;
|
|
22
30
|
let measure;
|
|
23
|
-
|
|
31
|
+
let observedWidth;
|
|
32
|
+
let frame;
|
|
33
|
+
const update = (contentWidth) => {
|
|
24
34
|
if (!active)
|
|
25
35
|
return;
|
|
26
36
|
let layout;
|
|
27
37
|
try {
|
|
28
38
|
const computed = view.getComputedStyle(element);
|
|
29
|
-
const
|
|
39
|
+
const padding = numericLength(computed.paddingLeft) + numericLength(computed.paddingRight);
|
|
40
|
+
const fallback = element.clientWidth - padding;
|
|
41
|
+
if (contentWidth !== undefined)
|
|
42
|
+
observedWidth = { fallback, exact: contentWidth };
|
|
43
|
+
if (observedWidth?.fallback !== fallback)
|
|
44
|
+
observedWidth = undefined;
|
|
45
|
+
// clientWidth is rounded. Use it to validate the computed width until the observer delivers.
|
|
46
|
+
const width = observedWidth?.exact ?? (fallback > 0
|
|
47
|
+
? computedContentWidth(computed, padding, fallback) ?? Math.max(1, fallback - 1)
|
|
48
|
+
: 0);
|
|
30
49
|
if (!(width > 0)) {
|
|
31
50
|
layout = undefined;
|
|
32
51
|
}
|
|
33
52
|
else {
|
|
34
53
|
const font = fontOf(computed);
|
|
35
|
-
const
|
|
54
|
+
const language = languageOf(element);
|
|
55
|
+
const signature = JSON.stringify([font, language]);
|
|
36
56
|
if (!measure || previousFont !== signature) {
|
|
37
|
-
measure =
|
|
57
|
+
measure = createLocalizedCanvasMeasure(font, doc, language);
|
|
38
58
|
previousFont = signature;
|
|
39
59
|
}
|
|
40
|
-
layout = { width
|
|
60
|
+
layout = { width, measure };
|
|
41
61
|
}
|
|
42
62
|
}
|
|
43
63
|
catch {
|
|
@@ -45,22 +65,38 @@ export const observeElementLayout = (element, onLayout) => {
|
|
|
45
65
|
}
|
|
46
66
|
onLayout(layout);
|
|
47
67
|
};
|
|
68
|
+
const refresh = () => update();
|
|
48
69
|
const onFonts = () => {
|
|
49
70
|
measure = undefined;
|
|
50
71
|
update();
|
|
51
72
|
};
|
|
52
73
|
const Observer = view.ResizeObserver ?? globalThis.ResizeObserver;
|
|
53
|
-
const observer = Observer ? new Observer(
|
|
74
|
+
const observer = Observer ? new Observer((entries) => {
|
|
75
|
+
const width = entries?.[0]?.contentRect.width;
|
|
76
|
+
if (width === undefined || !view.requestAnimationFrame) {
|
|
77
|
+
update(width);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (frame !== undefined)
|
|
81
|
+
view.cancelAnimationFrame(frame);
|
|
82
|
+
// Rendering can change the observed element's height.
|
|
83
|
+
frame = view.requestAnimationFrame(() => {
|
|
84
|
+
frame = undefined;
|
|
85
|
+
update(width);
|
|
86
|
+
});
|
|
87
|
+
}) : undefined;
|
|
54
88
|
observer?.observe(element);
|
|
55
|
-
view.addEventListener("resize",
|
|
89
|
+
view.addEventListener("resize", refresh);
|
|
56
90
|
doc.fonts?.addEventListener("loadingdone", onFonts);
|
|
57
91
|
void doc.fonts?.ready.then(onFonts);
|
|
58
92
|
update();
|
|
59
93
|
const destroy = () => {
|
|
60
94
|
active = false;
|
|
95
|
+
if (frame !== undefined)
|
|
96
|
+
view.cancelAnimationFrame(frame);
|
|
61
97
|
observer?.disconnect();
|
|
62
|
-
view.removeEventListener("resize",
|
|
98
|
+
view.removeEventListener("resize", refresh);
|
|
63
99
|
doc.fonts?.removeEventListener("loadingdone", onFonts);
|
|
64
100
|
};
|
|
65
|
-
return { refresh
|
|
101
|
+
return { refresh, destroy };
|
|
66
102
|
};
|
package/dist/dom/observe.js
CHANGED
|
@@ -2,6 +2,8 @@ import { manualLines } from "../core/segmentation.js";
|
|
|
2
2
|
import { wrap } from "../core/wrap.js";
|
|
3
3
|
import { observeElementLayout } from "./observe-element.js";
|
|
4
4
|
export const observeKowrap = (element, initial, onLayout) => {
|
|
5
|
+
if (initial.inline)
|
|
6
|
+
throw new TypeError("Use mountKowrap for inline content");
|
|
5
7
|
let options = initial;
|
|
6
8
|
let active = true;
|
|
7
9
|
let fallback = manualLines(options.text, options.forcedBreaks);
|
|
@@ -17,6 +19,8 @@ export const observeKowrap = (element, initial, onLayout) => {
|
|
|
17
19
|
update: (next) => {
|
|
18
20
|
if (!active)
|
|
19
21
|
return;
|
|
22
|
+
if (next.inline)
|
|
23
|
+
throw new TypeError("Use mountKowrap for inline content");
|
|
20
24
|
fallback = manualLines(next.text, next.forcedBreaks);
|
|
21
25
|
options = next;
|
|
22
26
|
observer.refresh();
|
package/dist/dom/render.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import type { KowrapController,
|
|
2
|
-
export declare const mountKowrap: (element: HTMLElement, initial:
|
|
1
|
+
import type { KowrapController, MountKowrapOptions } from "./types.js";
|
|
2
|
+
export declare const mountKowrap: (element: HTMLElement, initial: MountKowrapOptions) => KowrapController;
|
package/dist/dom/render.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { manualLines } from "../core/segmentation.js";
|
|
2
2
|
import { observeKowrap } from "./observe.js";
|
|
3
|
+
import { mountInline } from "./inline.js";
|
|
3
4
|
const wrapStyles = {
|
|
4
5
|
whiteSpace: "pre-wrap",
|
|
5
6
|
wordBreak: "keep-all",
|
|
@@ -19,6 +20,13 @@ const renderLines = (element, lines) => {
|
|
|
19
20
|
};
|
|
20
21
|
const sameLines = (previous, next) => previous?.length === next.length && previous.every((line, index) => line.text === next[index]?.text && line.breakAfter === next[index]?.breakAfter);
|
|
21
22
|
export const mountKowrap = (element, initial) => {
|
|
23
|
+
if (initial.inline) {
|
|
24
|
+
const previous = { whiteSpace: element.style.whiteSpace, wordBreak: element.style.wordBreak, overflowWrap: element.style.overflowWrap };
|
|
25
|
+
Object.assign(element.style, wrapStyles, { overflowWrap: initial.breakLongWords === false ? "normal" : "anywhere" });
|
|
26
|
+
const controller = mountInline(element, initial);
|
|
27
|
+
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); } };
|
|
29
|
+
}
|
|
22
30
|
const initialLines = manualLines(initial.text, initial.forcedBreaks);
|
|
23
31
|
const style = element.style;
|
|
24
32
|
const previousStyles = { whiteSpace: style.whiteSpace, wordBreak: style.wordBreak, overflowWrap: style.overflowWrap };
|
|
@@ -38,6 +46,8 @@ export const mountKowrap = (element, initial) => {
|
|
|
38
46
|
update: (next) => {
|
|
39
47
|
if (!active)
|
|
40
48
|
return;
|
|
49
|
+
if (next.inline)
|
|
50
|
+
throw new TypeError("Cannot change inline mode");
|
|
41
51
|
manualLines(next.text, next.forcedBreaks);
|
|
42
52
|
options = next;
|
|
43
53
|
applyStyles();
|
package/dist/dom/types.d.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import type { WrapOptions, WrappedLine } from "../core/types.js";
|
|
2
2
|
export interface KowrapOptions extends Pick<WrapOptions, "strategy" | "breakLongWords" | "forcedBreaks"> {
|
|
3
3
|
text: string;
|
|
4
|
+
inline?: false;
|
|
4
5
|
}
|
|
6
|
+
export interface InlineKowrapOptions extends Pick<WrapOptions, "strategy" | "breakLongWords" | "forcedBreaks"> {
|
|
7
|
+
inline: true;
|
|
8
|
+
text?: never;
|
|
9
|
+
}
|
|
10
|
+
export type MountKowrapOptions = KowrapOptions | InlineKowrapOptions;
|
|
5
11
|
export interface KowrapController {
|
|
6
|
-
update: (options:
|
|
12
|
+
update: (options: MountKowrapOptions) => void;
|
|
7
13
|
refresh: () => void;
|
|
8
14
|
destroy: () => void;
|
|
15
|
+
restore?: () => void;
|
|
9
16
|
}
|
|
10
17
|
export interface KowrapLayout {
|
|
11
18
|
lines: WrappedLine[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oddmash/kowrap",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Korean-aware text wrapping for JavaScript, HTML and frontend frameworks",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -26,6 +26,8 @@
|
|
|
26
26
|
"test:frameworks": "npm run build && npm --prefix test/framework-app test",
|
|
27
27
|
"test:browser": "npm run test:next && npm --prefix test/next-app run test:browser",
|
|
28
28
|
"test:package": "npm run build && node --test test/package.mjs",
|
|
29
|
+
"build:site": "npm run build && npm --prefix site run build",
|
|
30
|
+
"test:site": "npm run build:site && node --test test/site.mjs",
|
|
29
31
|
"prepack": "npm run build"
|
|
30
32
|
},
|
|
31
33
|
"engines": { "node": ">=20" },
|