@oddmash/juliya 0.0.0-stage → 0.4.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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +7 -0
  3. package/README.md +72 -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 +51 -4
@@ -0,0 +1,50 @@
1
+ const sentenceEnd = /[.!?。!?…][”’"')\]]*$/u;
2
+ const clauseEnd = /[,;:,、;:]$/u;
3
+ const boundModifier = /(?:^|\s)(?:이|그|저|각|모든|어떤|이런|그런|저런|다음|해당|본|여러|다른|같은|기존|\S*(?:로운|스러운|적인|들의|에서의|로서의|으로의|와의|과의|사이의|하는|되는|있는|없는|않는|않은|했던|하던|보이는|필요한|위한|열린|닫는))$/u;
4
+ const technicalPrefix = /^(?:[A-Z][A-Z0-9]{1,}|[A-Z][a-z]+(?:[A-Z][a-z]+)+|[a-z]+\.[a-z]+)$/u;
5
+ const technicalHead = /^(?:import|export|module|runtime|client|server|layer|token|hook|input|output|API|CLI|SDK|파일|모듈|출력|레이어|토큰|컴포넌트|런타임|훅|스타일)(?:[가-힣]*|[.,;:]?)$/u;
6
+ const numeralModifier = /^(?:한|두|세|네|다섯|여섯|일곱|여덟|아홉|열|스무|\d+(?:[.,]\d+)?)$/u;
7
+ const counterHead = /^(?:개|명|건|번|권|회|종|가지|대|장|쪽|줄|단계|시간|분|초|일|개월|년|주)(?:의|이|가|을|를|은|는|에|로|으로|와|과|도|만|부터|까지|에서|에게|이나|나|씩|마다|으로는|로는)?[.,!?。!?…]?$/u;
8
+ const compounds = {
9
+ 공통: ["패키지", "코드", "컴포넌트", "모듈"],
10
+ 디자인: ["시스템", "토큰"],
11
+ 배포: ["구조", "단위", "경계", "결과"],
12
+ 사용: ["범위", "경험", "환경"],
13
+ 런타임: ["의존성", "검증"],
14
+ 퇴출: ["모션", "완료"],
15
+ 완료: ["처리", "콜백"],
16
+ 전체: ["스타일", "CSS", "코드"],
17
+ 실제: ["사용", "화면", "입력"],
18
+ 숨겨진: ["입력", "요소", "폼"],
19
+ 키보드: ["포커스", "입력"],
20
+ 접근: ["가능한"],
21
+ };
22
+ const protectedPair = (fragment, nextWord) => {
23
+ const left = fragment.match(/\S+$/u)?.[0] ?? "";
24
+ if (numeralModifier.test(left) && counterHead.test(nextWord))
25
+ return true;
26
+ if (technicalPrefix.test(left) && technicalHead.test(nextWord))
27
+ return true;
28
+ return Object.hasOwn(compounds, left) && compounds[left].some((head) => nextWord.startsWith(head));
29
+ };
30
+ const englishModifier = /(?:^|\s)(?:a|an|the|this|that|these|those|every|each|some|my|your|our|their|its|to|of|for|with|from|in|on|at|as)$/iu;
31
+ const boundaryCost = ({ fragment, emergency }, nextWord, locale = "ko") => {
32
+ if (emergency)
33
+ return 0.75;
34
+ if (sentenceEnd.test(fragment))
35
+ return 0;
36
+ if (clauseEnd.test(fragment))
37
+ return 0.02;
38
+ if (locale === "ko" && protectedPair(fragment, nextWord))
39
+ return 0.65;
40
+ if (locale === "ko" && boundModifier.test(fragment))
41
+ return 0.45;
42
+ if (locale === "en" && englishModifier.test(fragment))
43
+ return 0.45;
44
+ return 0.06;
45
+ };
46
+ export const lineCost = (candidate, availableWidth, isLast, nextWord = "", locale = "ko") => {
47
+ const slack = (availableWidth - Math.min(candidate.width, availableWidth)) / availableWidth;
48
+ const overflow = Math.max(0, candidate.width - availableWidth) / availableWidth;
49
+ return slack ** 2 + overflow ** 2 * 4 + (isLast ? 0 : boundaryCost(candidate, nextWord, locale));
50
+ };
@@ -0,0 +1,17 @@
1
+ import type { TextSegment, WrappedLine } from "./types.js";
2
+ export declare const graphemesOf: (text: string) => Intl.SegmentData[];
3
+ export declare const wordBoundariesOf: (text: string, locale: string) => Set<number>;
4
+ export declare const isBreakableSpace: (segment: string) => boolean;
5
+ export declare const visibleText: (text: string) => string;
6
+ export declare const paragraphsOf: (text: string) => Generator<{
7
+ text: string;
8
+ start: number;
9
+ breakAfter: string;
10
+ }, void, unknown>;
11
+ export declare const segmentsWithBreaks: (text: string, offsets?: readonly number[]) => Generator<{
12
+ text: string;
13
+ start: number;
14
+ breakAfter: string;
15
+ }, void, unknown>;
16
+ export declare const manualLines: (text: string, offsets?: readonly number[]) => WrappedLine[];
17
+ export declare const segmentSentences: (text: string, locale?: string) => TextSegment[];
@@ -0,0 +1,53 @@
1
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
2
+ const breakableSpace = /[ \t\f\v\u2000-\u2006\u2008-\u200a\u205f\u3000]/u;
3
+ const trailingSpace = /[ \t\f\v\u2000-\u2006\u2008-\u200a\u205f\u3000]+$/u;
4
+ const hardBreak = /\r\n|[\r\n\u2028\u2029]/gu;
5
+ export const graphemesOf = (text) => Array.from(graphemeSegmenter.segment(text));
6
+ export const wordBoundariesOf = (text, locale) => {
7
+ const segmenter = new Intl.Segmenter(locale, { granularity: "word" });
8
+ return new Set(Array.from(segmenter.segment(text), ({ index, segment }) => index + segment.length));
9
+ };
10
+ export const isBreakableSpace = (segment) => breakableSpace.test(segment);
11
+ export const visibleText = (text) => text.replace(trailingSpace, "");
12
+ export const paragraphsOf = function* (text) {
13
+ let start = 0;
14
+ for (const match of text.matchAll(hardBreak)) {
15
+ yield { text: text.slice(start, match.index), start, breakAfter: match[0] };
16
+ start = match.index + match[0].length;
17
+ }
18
+ yield { text: text.slice(start), start, breakAfter: "" };
19
+ };
20
+ const validBreaks = (text, offsets) => {
21
+ if (offsets.length === 0)
22
+ return [];
23
+ const boundaries = new Set(graphemesOf(text).map(({ index }) => index));
24
+ for (const offset of offsets) {
25
+ if (!Number.isInteger(offset) || offset <= 0 || offset >= text.length || !boundaries.has(offset)) {
26
+ throw new RangeError("forcedBreaks must contain interior UTF-16 grapheme boundaries");
27
+ }
28
+ }
29
+ return [...new Set(offsets)].sort((left, right) => left - right);
30
+ };
31
+ export const segmentsWithBreaks = function* (text, offsets = []) {
32
+ const breaks = validBreaks(text, offsets);
33
+ let cursor = 0;
34
+ for (const paragraph of paragraphsOf(text)) {
35
+ const end = paragraph.start + paragraph.text.length;
36
+ let start = paragraph.start;
37
+ while (cursor < breaks.length && breaks[cursor] <= start)
38
+ cursor++;
39
+ while (cursor < breaks.length && breaks[cursor] < end) {
40
+ const offset = breaks[cursor++];
41
+ yield { text: text.slice(start, offset), start, breakAfter: "" };
42
+ start = offset;
43
+ }
44
+ yield { text: text.slice(start, end), start, breakAfter: paragraph.breakAfter };
45
+ }
46
+ };
47
+ export const manualLines = (text, offsets) => Array.from(segmentsWithBreaks(text, offsets), ({ text: line, start, breakAfter }) => ({
48
+ text: line, start, end: start + line.length, width: 0, breakAfter,
49
+ }));
50
+ export const segmentSentences = (text, locale = "ko") => {
51
+ const sentences = new Intl.Segmenter(locale, { granularity: "sentence" });
52
+ return Array.from(sentences.segment(text), ({ segment, index }) => ({ text: segment, start: index, end: index + segment.length }));
53
+ };
@@ -0,0 +1,46 @@
1
+ export type Measure = (text: string) => number;
2
+ export type WrapLocale = "ko" | "en" | "ja" | "zh" | "zh-Hans";
3
+ export interface WrapOptions {
4
+ locale?: WrapLocale;
5
+ width: number;
6
+ measure: Measure;
7
+ measureRange?: (start: number, end: number) => number;
8
+ strategy?: "balanced" | "greedy";
9
+ breakLongWords?: boolean;
10
+ forcedBreaks?: readonly number[];
11
+ }
12
+ export interface WrappedLine {
13
+ text: string;
14
+ start: number;
15
+ end: number;
16
+ width: number;
17
+ breakAfter: string;
18
+ }
19
+ export interface TextSegment {
20
+ text: string;
21
+ start: number;
22
+ end: number;
23
+ }
24
+ export interface ParagraphOptions {
25
+ locale?: WrapLocale;
26
+ width: number;
27
+ measure: Measure;
28
+ measureRange?: (start: number, end: number) => number;
29
+ strategy: NonNullable<WrapOptions["strategy"]>;
30
+ breakLongWords: boolean;
31
+ }
32
+ export interface Boundary {
33
+ offset: number;
34
+ emergency: boolean;
35
+ }
36
+ export interface LineCandidate {
37
+ next: number;
38
+ width: number;
39
+ fragment: string;
40
+ emergency: boolean;
41
+ }
42
+ export interface PlannedLine {
43
+ start: number;
44
+ end: number;
45
+ width: number;
46
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { WrapOptions, WrappedLine } from "./types.js";
2
+ export declare const wrap: (text: string, options: WrapOptions) => WrappedLine[];
@@ -0,0 +1,40 @@
1
+ import { planParagraph } from "./layout.js";
2
+ import { segmentsWithBreaks } from "./segmentation.js";
3
+ const checkedMeasure = (measure) => (value) => {
4
+ if (!value)
5
+ return 0;
6
+ const result = measure(value);
7
+ if (!Number.isFinite(result) || result < 0)
8
+ throw new RangeError("measure must return a non-negative finite number");
9
+ return result;
10
+ };
11
+ export const wrap = (text, options) => {
12
+ if (!Number.isFinite(options.width) || options.width <= 0)
13
+ throw new RangeError("width must be positive and finite");
14
+ const paragraphOptions = {
15
+ locale: options.locale ?? "ko",
16
+ width: options.width,
17
+ measure: checkedMeasure(options.measure),
18
+ strategy: options.strategy ?? "balanced",
19
+ breakLongWords: options.breakLongWords !== false,
20
+ };
21
+ const lines = [];
22
+ for (const paragraph of segmentsWithBreaks(text, options.forcedBreaks)) {
23
+ const plan = planParagraph(paragraph.text, { ...paragraphOptions, measureRange: options.measureRange ? (start, end) => {
24
+ const result = options.measureRange(paragraph.start + start, paragraph.start + end);
25
+ if (!Number.isFinite(result) || result < 0)
26
+ throw new RangeError("measureRange must return a non-negative finite number");
27
+ return result;
28
+ } : undefined });
29
+ for (const [index, line] of plan.entries()) {
30
+ lines.push({
31
+ text: paragraph.text.slice(line.start, line.end),
32
+ start: paragraph.start + line.start,
33
+ end: paragraph.start + line.end,
34
+ width: line.width,
35
+ breakAfter: index === plan.length - 1 ? paragraph.breakAfter : "",
36
+ });
37
+ }
38
+ }
39
+ return lines;
40
+ };
@@ -0,0 +1,5 @@
1
+ export type { CanvasMeasureOptions } from "./measure.js";
2
+ export { createCanvasMeasure } from "./measure.js";
3
+ export type { KowrapController, KowrapLayout, KowrapOptions, InlineKowrapOptions, MountKowrapOptions } from "./types.js";
4
+ export { observeKowrap } from "./observe.js";
5
+ export { mountKowrap } from "./render.js";
@@ -0,0 +1,3 @@
1
+ export { createCanvasMeasure } from "./measure.js";
2
+ export { observeKowrap } from "./observe.js";
3
+ 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
+ };
@@ -0,0 +1,10 @@
1
+ import type { Measure } from "../core/types.js";
2
+ export interface CanvasMeasureOptions {
3
+ font: string;
4
+ letterSpacing?: string;
5
+ wordSpacing?: string;
6
+ fontKerning?: CanvasFontKerning;
7
+ }
8
+ export declare const createLocalizedCanvasMeasure: (options: CanvasMeasureOptions, ownerDocument: Document, language: string | undefined) => Measure;
9
+ export declare const createCanvasMeasure: (options: CanvasMeasureOptions, ownerDocument?: Document) => Measure;
10
+ export declare const languageOf: (element: HTMLElement) => string | undefined;
@@ -0,0 +1,18 @@
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");
6
+ if (!context)
7
+ throw new Error("Canvas 2D measurement is unavailable");
8
+ context.font = options.font;
9
+ if (options.letterSpacing && "letterSpacing" in context)
10
+ context.letterSpacing = options.letterSpacing;
11
+ if (options.wordSpacing && "wordSpacing" in context)
12
+ context.wordSpacing = options.wordSpacing;
13
+ if (options.fontKerning)
14
+ context.fontKerning = options.fontKerning;
15
+ return (text) => context.measureText(text).width;
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;
@@ -0,0 +1,11 @@
1
+ import type { CanvasMeasureOptions } from "./measure.js";
2
+ import type { Measure } from "../core/types.js";
3
+ export interface ElementLayout {
4
+ width: number;
5
+ measure: Measure;
6
+ }
7
+ export declare const fontOf: (computed: CSSStyleDeclaration) => CanvasMeasureOptions;
8
+ export declare const observeElementLayout: (element: HTMLElement, onLayout: (layout: ElementLayout | undefined) => void) => {
9
+ refresh: () => void;
10
+ destroy: () => void;
11
+ };
@@ -0,0 +1,102 @@
1
+ import { createLocalizedCanvasMeasure, languageOf } from "./measure.js";
2
+ const numericLength = (value) => {
3
+ const parsed = Number.parseFloat(value);
4
+ return Number.isFinite(parsed) ? parsed : 0;
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
+ };
14
+ const spacing = (value) => value === "normal" || !value ? "0px" : value;
15
+ export const fontOf = (computed) => ({
16
+ font: computed.font || `${computed.fontStyle} ${computed.fontWeight} ${computed.fontSize} ${computed.fontFamily}`,
17
+ letterSpacing: spacing(computed.letterSpacing),
18
+ wordSpacing: spacing(computed.wordSpacing),
19
+ fontKerning: computed.fontKerning,
20
+ });
21
+ export const observeElementLayout = (element, onLayout) => {
22
+ const doc = element.ownerDocument;
23
+ const view = doc.defaultView;
24
+ if (!view) {
25
+ onLayout(undefined);
26
+ return { refresh: () => onLayout(undefined), destroy: () => { } };
27
+ }
28
+ let active = true;
29
+ let previousFont;
30
+ let measure;
31
+ let observedWidth;
32
+ let frame;
33
+ const update = (contentWidth) => {
34
+ if (!active)
35
+ return;
36
+ let layout;
37
+ try {
38
+ const computed = view.getComputedStyle(element);
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);
49
+ if (!(width > 0)) {
50
+ layout = undefined;
51
+ }
52
+ else {
53
+ const font = fontOf(computed);
54
+ const language = languageOf(element);
55
+ const signature = JSON.stringify([font, language]);
56
+ if (!measure || previousFont !== signature) {
57
+ measure = createLocalizedCanvasMeasure(font, doc, language);
58
+ previousFont = signature;
59
+ }
60
+ layout = { width, measure };
61
+ }
62
+ }
63
+ catch {
64
+ layout = undefined;
65
+ }
66
+ onLayout(layout);
67
+ };
68
+ const refresh = () => update();
69
+ const onFonts = () => {
70
+ measure = undefined;
71
+ update();
72
+ };
73
+ const Observer = view.ResizeObserver ?? globalThis.ResizeObserver;
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;
88
+ observer?.observe(element);
89
+ view.addEventListener("resize", refresh);
90
+ doc.fonts?.addEventListener("loadingdone", onFonts);
91
+ void doc.fonts?.ready.then(onFonts);
92
+ update();
93
+ const destroy = () => {
94
+ active = false;
95
+ if (frame !== undefined)
96
+ view.cancelAnimationFrame(frame);
97
+ observer?.disconnect();
98
+ view.removeEventListener("resize", refresh);
99
+ doc.fonts?.removeEventListener("loadingdone", onFonts);
100
+ };
101
+ return { refresh, destroy };
102
+ };
@@ -0,0 +1,2 @@
1
+ import type { KowrapController, KowrapLayout, KowrapOptions } from "./types.js";
2
+ export declare const observeKowrap: (element: HTMLElement, initial: KowrapOptions, onLayout: (layout: KowrapLayout) => void) => KowrapController;
@@ -0,0 +1,37 @@
1
+ import { manualLines } from "../core/segmentation.js";
2
+ import { wrap } from "../core/wrap.js";
3
+ import { observeElementLayout } from "./observe-element.js";
4
+ export const observeKowrap = (element, initial, onLayout) => {
5
+ if (initial.inline)
6
+ throw new TypeError("Use mountKowrap for inline content");
7
+ let options = initial;
8
+ let active = true;
9
+ let fallback = manualLines(options.text, options.forcedBreaks);
10
+ const observer = observeElementLayout(element, (measurement) => {
11
+ if (!measurement) {
12
+ onLayout({ lines: fallback, measured: false });
13
+ return;
14
+ }
15
+ const lines = wrap(options.text, { ...options, ...measurement });
16
+ onLayout({ lines, measured: true });
17
+ });
18
+ return {
19
+ update: (next) => {
20
+ if (!active)
21
+ return;
22
+ if (next.inline)
23
+ throw new TypeError("Use mountKowrap for inline content");
24
+ fallback = manualLines(next.text, next.forcedBreaks);
25
+ options = next;
26
+ observer.refresh();
27
+ },
28
+ refresh: () => { if (active)
29
+ observer.refresh(); },
30
+ destroy: () => {
31
+ if (!active)
32
+ return;
33
+ active = false;
34
+ observer.destroy();
35
+ },
36
+ };
37
+ };
@@ -0,0 +1,2 @@
1
+ import type { KowrapController, MountKowrapOptions } from "./types.js";
2
+ export declare const mountKowrap: (element: HTMLElement, initial: MountKowrapOptions) => KowrapController;
@@ -0,0 +1,66 @@
1
+ import { manualLines } from "../core/segmentation.js";
2
+ import { observeKowrap } from "./observe.js";
3
+ import { mountInline } from "./inline.js";
4
+ const wrapStyles = {
5
+ whiteSpace: "pre-wrap",
6
+ wordBreak: "keep-all",
7
+ overflowWrap: "anywhere",
8
+ };
9
+ const renderLines = (element, lines) => {
10
+ const doc = element.ownerDocument;
11
+ const fragment = doc.createDocumentFragment();
12
+ lines.forEach((line, index) => {
13
+ fragment.append(doc.createTextNode(line.text));
14
+ if (line.breakAfter)
15
+ fragment.append(doc.createTextNode(line.breakAfter));
16
+ else if (index < lines.length - 1)
17
+ fragment.append(doc.createElement("br"));
18
+ });
19
+ element.replaceChildren(fragment);
20
+ };
21
+ 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) => {
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
+ }
30
+ const initialLines = manualLines(initial.text, initial.forcedBreaks);
31
+ const style = element.style;
32
+ const previousStyles = { whiteSpace: style.whiteSpace, wordBreak: style.wordBreak, overflowWrap: style.overflowWrap };
33
+ let options = initial;
34
+ let previousLines;
35
+ let active = true;
36
+ const applyStyles = () => Object.assign(style, wrapStyles, { overflowWrap: options.breakLongWords === false ? "normal" : "anywhere" });
37
+ const render = (lines) => {
38
+ if (!sameLines(previousLines, lines))
39
+ renderLines(element, lines);
40
+ previousLines = lines;
41
+ };
42
+ applyStyles();
43
+ render(initialLines);
44
+ const observer = observeKowrap(element, initial, ({ lines }) => render(lines));
45
+ return {
46
+ update: (next) => {
47
+ if (!active)
48
+ return;
49
+ if (next.inline)
50
+ throw new TypeError("Cannot change inline mode");
51
+ manualLines(next.text, next.forcedBreaks);
52
+ options = next;
53
+ applyStyles();
54
+ observer.update(next);
55
+ },
56
+ refresh: observer.refresh,
57
+ destroy: () => {
58
+ if (!active)
59
+ return;
60
+ active = false;
61
+ observer.destroy();
62
+ Object.assign(style, previousStyles);
63
+ element.textContent = options.text;
64
+ },
65
+ };
66
+ };
@@ -0,0 +1,20 @@
1
+ import type { WrapOptions, WrappedLine } from "../core/types.js";
2
+ export interface KowrapOptions extends Pick<WrapOptions, "strategy" | "breakLongWords" | "forcedBreaks" | "locale"> {
3
+ text: string;
4
+ inline?: false;
5
+ }
6
+ export interface InlineKowrapOptions extends Pick<WrapOptions, "strategy" | "breakLongWords" | "forcedBreaks" | "locale"> {
7
+ inline: true;
8
+ text?: never;
9
+ }
10
+ export type MountKowrapOptions = KowrapOptions | InlineKowrapOptions;
11
+ export interface KowrapController {
12
+ update: (options: MountKowrapOptions) => void;
13
+ refresh: () => void;
14
+ destroy: () => void;
15
+ restore?: () => void;
16
+ }
17
+ export interface KowrapLayout {
18
+ lines: WrappedLine[];
19
+ measured: boolean;
20
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export type { Measure, TextSegment, WrapOptions, WrappedLine, WrapLocale } from "./core/types.js";
2
+ export { manualLines as splitLines, segmentSentences } from "./core/segmentation.js";
3
+ export { wrap } from "./core/wrap.js";