!7

// TODO: cache URLs + images

cmodule ImageSearcher > DynImageSurface {
  S typingText;
  transient S text;
  switchable bool listen;
  
  start {
    set zoomToWindowOnSetImage;
    dm_onTopInput_q(voidfunc(S s) {
      if (listen) show(s)
    });
  }
  
  enhanceFrame { minFrameSize(f, 300, 300); }

  visualize {
    ret northCenterSouthWithMargins(dm_bigInputAndSubmit('typingText, "Visualize", rThread { show(typingText) }),
      super.visualize(),
      vstackWithSpacing(
        centeredLiveValueLabel(dm_fieldLiveValue('text)),
        dm_rightAlignedCheckBox('listen)));
  }
  
  // API
  
  void show(S query) q {
    pcall {
      setField(typingText := query);
      BufferedImage img = loadImage2(random(qwantImageSearch(query)));
      if (img == null) ret;
      setImage(img);
      setField(text := query);
    }
  }
}