@@ -319,9 +319,68 @@ pub const Document = struct {
319319 log .debug (.web_api , "not implemented" , .{ .feature = "Document hasFocus" });
320320 return true ;
321321 }
322+
323+ pub fn _open (_ : * parser.Document , page : * Page ) ! * parser.DocumentHTML {
324+ if (page .open ) {
325+ return page .window .document ;
326+ }
327+
328+ // This implementation is invalid.
329+ // According to MDN, we should cleanup registered listeners.
330+ // So we sould cleanup previous DOM memory.
331+ // But this implementation is more simple for now.
332+ const html_doc = try parser .documentHTMLParseFromStr ("" );
333+ try page .setDocument (html_doc );
334+ page .open = true ;
335+
336+ return page .window .document ;
337+ }
338+
339+ pub fn _close (_ : * parser.Document , page : * Page ) ! void {
340+ page .open = false ;
341+ }
342+
343+ pub fn _write (self : * parser.Document , str : []const u8 , page : * Page ) ! void {
344+ if (! page .open ) {
345+ _ = try _open (self , page );
346+ }
347+ const document = parser .documentHTMLToDocument (page .window .document );
348+ const fragment = try parser .documentParseFragmentFromStr (document , str );
349+ const fragment_node = parser .documentFragmentToNode (fragment );
350+
351+ const fragment_html = parser .nodeFirstChild (fragment_node ) orelse return ;
352+ const fragment_head = parser .nodeFirstChild (fragment_html ) orelse return ;
353+ const fragment_body = parser .nodeNextSibling (fragment_head ) orelse return ;
354+
355+ const document_node = parser .documentToNode (document );
356+ const document_html = parser .nodeFirstChild (document_node ) orelse return ;
357+ const document_head = parser .nodeFirstChild (document_html ) orelse return ;
358+ const document_body = parser .nodeNextSibling (document_head ) orelse return ;
359+
360+ {
361+ const children = try parser .nodeGetChildNodes (fragment_head );
362+ // always index 0, because nodeAppendChild moves the node out of
363+ // the nodeList and into the new tree
364+ while (parser .nodeListItem (children , 0 )) | child | {
365+ _ = try parser .nodeAppendChild (document_head , child );
366+ }
367+ }
368+
369+ {
370+ const children = try parser .nodeGetChildNodes (fragment_body );
371+ // always index 0, because nodeAppendChild moves the node out of
372+ // the nodeList and into the new tree
373+ while (parser .nodeListItem (children , 0 )) | child | {
374+ _ = try parser .nodeAppendChild (document_body , child );
375+ }
376+ }
377+ }
322378};
323379
324380const testing = @import ("../../testing.zig" );
325381test "Browser: DOM.Document" {
326382 try testing .htmlRunner ("dom/document.html" );
327383}
384+ test "Browser: DOM.Document.write" {
385+ try testing .htmlRunner ("dom/document_write.html" );
386+ }
0 commit comments