Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.1.098.9 KB2026-09-14
Version
0.1.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-09-14
Size
98.9 KB
Downloads
1
Checksum
bdac84a1e4fe4dd3505b93c2781b1f15833b5189c2e4ee976225fa3c512885cc
Dependencies
None

document.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! docx を作って読み戻すところ

use folio::document::{Block, Document, Writer};
use folio::paragraph::{Align, Paragraph, Run};
use folio::table::{Cell, Row, Table};
use std::path::PathBuf;


/// 試しに使うファイルの置き場。target の下なので消えても差し支えない
fn place(name: &str) -> PathBuf {
    let mut path = PathBuf::from("target");
    path.push(format!("document-{name}.docx"));
    path
}


/// 本文を読み切る
fn collect(document: &mut Document) -> Vec<Block> {
    let mut body = document.read().unwrap();
    let mut result = Vec::new();

    while let Some(block) = body.read().unwrap() {
        result.push(block);
    }

    result
}


/// 段落だけを取り出す
fn paragraph(block: &Block) -> &Paragraph {
    match block {
        Block::Paragraph(one) => one,
        Block::Table(_) => panic!("段落ではありません"),
    }
}


#[test]
fn paragraphs_come_back_as_they_were_written() {
    let path = place("paragraph");
    let mut writer = Writer::create(&path).unwrap();
    writer.paragraph(&Paragraph::styled("題", "Title")).unwrap();
    writer.paragraph(&Paragraph::styled("見出し", "Heading1")).unwrap();

    writer.paragraph(&Paragraph {
        style: String::new(),
        align: Align::Center,
        run: vec![
            Run::new("ふつう"),
            Run::bold("太字"),
            Run {text: "斜体".to_string(), italic: true, ..Run::default()},
            Run {text: "下線".to_string(), underline: true, ..Run::default()},
            Run {text: "取り消し".to_string(), strike: true, ..Run::default()},
            Run {text: "大きい".to_string(), size: 14.0, ..Run::default()},
            Run {text: "赤".to_string(), color: "FF0000".to_string(), ..Run::default()},
        ],
    }).unwrap();

    writer.finish().unwrap();

    let mut document = Document::open(&path).unwrap();
    let block = collect(&mut document);
    assert_eq!(block.len(), 3);

    assert_eq!(paragraph(&block[0]).style, "Title");
    assert_eq!(paragraph(&block[0]).text(), "題");
    assert_eq!(paragraph(&block[1]).style, "Heading1");

    let one = paragraph(&block[2]);
    assert_eq!(one.align, Align::Center);
    assert_eq!(one.run.len(), 7);
    assert!(one.run[1].bold);
    assert!(one.run[2].italic);
    assert!(one.run[3].underline);
    assert!(one.run[4].strike);
    assert_eq!(one.run[5].size, 14.0);
    assert_eq!(one.run[6].color, "FF0000");
    assert_eq!(one.text(), "ふつう太字斜体下線取り消し大きい赤");
}


#[test]
fn marks_and_breaks_survive_the_trip() {
    let path = place("mark");
    let mut writer = Writer::create(&path).unwrap();
    writer.paragraph(&Paragraph::new("記号 <&>\"' です")).unwrap();
    writer.paragraph(&Paragraph::new("改行\nと\tタブ")).unwrap();
    writer.finish().unwrap();

    let mut document = Document::open(&path).unwrap();
    let block = collect(&mut document);
    assert_eq!(paragraph(&block[0]).text(), "記号 <&>\"' です");
    assert_eq!(paragraph(&block[1]).text(), "改行\nと\tタブ");
}


#[test]
fn a_table_comes_back_with_its_cells() {
    let path = place("table");
    let mut writer = Writer::create(&path).unwrap();

    writer.table(&Table::new(vec![
        Row {
            cell: vec![
                Cell {span: 2, block: vec![Block::Paragraph(Paragraph::new("つながり"))]},
                Cell::new("三"),
            ],
        },
        Row::new(&["あ", "い", "う"]),
    ])).unwrap();

    writer.paragraph(&Paragraph::new("表のあと")).unwrap();
    writer.finish().unwrap();

    let mut document = Document::open(&path).unwrap();
    let block = collect(&mut document);

    let Block::Table(one) = &block[0] else {panic!("表ではありません")};
    assert!(one.border);
    assert_eq!(one.row.len(), 2);
    assert_eq!(one.row[0].cell[0].span, 2);
    assert_eq!(one.row[0].cell[0].text(), "つながり");
    assert_eq!(one.row[0].cell[1].text(), "三");
    assert_eq!(one.row[1].cell.len(), 3);
    assert_eq!(one.row[1].cell[2].text(), "う");
    assert_eq!(one.width(), 3);
}


#[test]
fn a_table_can_hold_another_table() {
    let path = place("nested");
    let inner = Table::new(vec![Row::new(&["おく"])]);

    let outer = Table::new(vec![Row {
        cell: vec![Cell {
            span: 1,
            block: vec![Block::Paragraph(Paragraph::new("そと")), Block::Table(inner)],
        }],
    }]);

    let mut writer = Writer::create(&path).unwrap();
    writer.table(&outer).unwrap();
    writer.finish().unwrap();

    let mut document = Document::open(&path).unwrap();
    let block = collect(&mut document);

    let Block::Table(one) = &block[0] else {panic!("表ではありません")};
    let inside = &one.row[0].cell[0].block;
    assert_eq!(inside.len(), 3, "段落、表、表のあとの空段落");

    let Block::Table(deep) = &inside[1] else {panic!("中に表がありません")};
    assert_eq!(deep.row[0].cell[0].text(), "おく");
}


#[test]
fn the_whole_text_can_be_taken_at_once() {
    let path = place("text");
    let mut writer = Writer::create(&path).unwrap();
    writer.paragraph(&Paragraph::new("一行目")).unwrap();
    writer.table(&Table::new(vec![Row::new(&["あ", "い"])])).unwrap();
    writer.paragraph(&Paragraph::new("三行目")).unwrap();
    writer.finish().unwrap();

    let mut document = Document::open(&path).unwrap();
    let text = document.text().unwrap();
    assert!(text.contains("一行目"));
    assert!(text.contains("あ\tい"));
    assert!(text.contains("三行目"));
}


#[test]
fn many_paragraphs_go_in_and_come_back() {
    let path = place("many");
    let count = 30000;

    let mut writer = Writer::create(&path).unwrap();

    for index in 0..count {
        writer.paragraph(&Paragraph::new(&format!("{index} 番目の段落です。"))).unwrap();
    }

    writer.finish().unwrap();

    let mut document = Document::open(&path).unwrap();
    let mut body = document.read().unwrap();
    let mut seen = 0;

    while let Some(block) = body.read().unwrap() {
        assert_eq!(block.text(), format!("{seen} 番目の段落です。"));
        seen += 1;
    }

    assert_eq!(seen, count);
}


/// 用紙の向きと、ヘッダのパートを持った docx を、手で組んで置く
///
/// folio は用紙もヘッダも作れないので、直しても残ることを確かめるにはこれが要る。
fn build_with_extras(path: &std::path::Path) {
    let head = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
    let main = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    let relation = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
    let base = "application/vnd.openxmlformats-officedocument.wordprocessingml";

    let body = format!(
        "{head}<w:document xmlns:w=\"{main}\" xmlns:r=\"{relation}\"><w:body>\
         <w:p><w:r><w:t>まえ</w:t></w:r></w:p>\
         <w:p><w:pPr><w:sectPr><w:pgSz w:w=\"1\" w:h=\"1\"/></w:sectPr></w:pPr></w:p>\
         <w:sectPr><w:headerReference r:id=\"rId2\" w:type=\"default\"/>\
         <w:pgSz w:w=\"16838\" w:h=\"11906\" w:orient=\"landscape\"/>\
         <w:pgMar w:top=\"567\" w:right=\"567\" w:bottom=\"567\" w:left=\"567\"/></w:sectPr>\
         </w:body></w:document>"
    );

    let header = format!(
        "{head}<w:hdr xmlns:w=\"{main}\"><w:p><w:r><w:t>ヘッダ</w:t></w:r></w:p></w:hdr>"
    );

    let types = format!(
        "{head}<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
         <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
         <Default Extension=\"xml\" ContentType=\"application/xml\"/>\
         <Override PartName=\"/word/document.xml\" ContentType=\"{base}.document.main+xml\"/>\
         <Override PartName=\"/word/header1.xml\" ContentType=\"{base}.header+xml\"/>\
         </Types>"
    );

    let root = format!(
        "{head}<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
         <Relationship Id=\"rId1\" Type=\"{relation}/officeDocument\" Target=\"word/document.xml\"/>\
         </Relationships>"
    );

    let link = format!(
        "{head}<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
         <Relationship Id=\"rId2\" Type=\"{relation}/header\" Target=\"header1.xml\"/>\
         </Relationships>"
    );

    let mut writer = folio::zip::Writer::create(path).unwrap();
    writer.add("[Content_Types].xml", types.as_bytes()).unwrap();
    writer.add("_rels/.rels", root.as_bytes()).unwrap();
    writer.add("word/_rels/document.xml.rels", link.as_bytes()).unwrap();
    writer.add("word/document.xml", body.as_bytes()).unwrap();
    writer.add("word/header1.xml", header.as_bytes()).unwrap();
    writer.finish().unwrap();
}


#[test]
fn editing_keeps_the_page_setup_and_the_other_parts() {
    let source_path = place("extras-source");
    let target_path = place("extras-target");
    build_with_extras(&source_path);

    let source = Document::open(&source_path).unwrap();
    let mut writer = Writer::edit(source, &target_path).unwrap();
    writer.paragraph(&Paragraph::new("あと")).unwrap();
    writer.finish().unwrap();

    let mut document = Document::open(&target_path).unwrap();
    let block = collect(&mut document);
    assert_eq!(block.len(), 1);
    assert_eq!(paragraph(&block[0]).text(), "あと");

    // 本文の後ろにある用紙の指定と、ヘッダのパートが残っている
    let body = String::from_utf8(document.package().unwrap().read("word/document.xml").unwrap()).unwrap();
    assert!(body.contains("w:orient=\"landscape\""), "{body}");
    assert!(body.contains("<w:headerReference r:id=\"rId2\""), "{body}");
    assert!(!body.contains("まえ"), "{body}");

    // 段落の中にあった途中の区切りは、本文と一緒に消える
    assert!(!body.contains("w:w=\"1\""), "{body}");

    let header = document.package().unwrap().read("word/header1.xml").unwrap();
    assert!(String::from_utf8(header).unwrap().contains("ヘッダ"));
}


#[test]
fn a_file_that_is_not_a_document_is_an_error() {
    let path = place("broken");
    std::fs::write(&path, "これは docx ではありません").unwrap();
    assert!(Document::open(&path).is_err());
}