-- Global hyperscript helpers.
--
-- Note: wc-input's base class promotes `name` to `id` on the inner <input>
-- (see wc-base-component.js `_handleNameToIdLinkage`). That means two open
-- editor tabs of the same kind share duplicate global IDs. The helpers that
-- resolve a target by id below scope their lookup to the closest <form>
-- first so multi-tab UIs don't cross-talk. They fall back to document-wide
-- lookup for legacy screens not inside a <form>.

def toLower(elt)
  set elt.value to elt.value.toLowerCase()
end

def toLowerUri(elt)
  set elt.value to elt.value.toLowerCase().replaceAll(" ", "/")
end

def toLowerSnake(elt)
  set elt.value to elt.value.toLowerCase().replaceAll(" ", "_").replaceAll("/", "_")
end

-- Resolve a target element by id, scoped to the same form as elt so multi-tab
-- UIs find their own tab's target (not the first-mounted duplicate).
def _scopedTarget(elt, tgt)
  set scope to elt.closest('form')
  if no scope
    set scope to document
  end
  set result to scope.querySelector('#' + tgt)
  if no result and scope is not document
    set result to document.querySelector('#' + tgt)
  end
  return result
end

def copyToByElementId(elt, tgt)
  set telem to _scopedTarget(elt, tgt)
  if telem
    set telem.value to elt.value
    trigger input on telem
  end
end

def copyToLower(elt, tgt)
  set telem to _scopedTarget(elt, tgt)
  if telem
    set telem.value to elt.value.toLowerCase()
    trigger input on telem
  end
end

def copyToLowerUri(elt, tgt)
  set telem to _scopedTarget(elt, tgt)
  if telem
    set telem.value to elt.value.toLowerCase().replaceAll(" ", "/")
    trigger input on telem
  end
end

def copyToInnerText(elt, tgt)
  set telem to _scopedTarget(elt, tgt)
  if telem
    set telem.innerText to elt.value
    trigger input on telem
  end
end

def copyToLowerSnake(elt, tgt)
  set telem to _scopedTarget(elt, tgt)
  if telem
    set telem.value to elt.value.toLowerCase().replaceAll(" ", "_")
    trigger input on telem
  end
end

def refreshEditorById(element_id)
  -- It is necessary to use querySelector as this is
  -- attached to the body of the DOM.
  set elt to document.querySelector('#' + element_id)
  if elt and elt.editor
    elt.editor.refresh()
    elt.editor.focus()
  end
end

def refreshEditor(elt)
  if elt and elt.editor
    elt.editor.refresh()
    elt.editor.focus()
  end
end


behavior HandleCodeMirrorTabChange()
  on tabchange from me.closest('.wc-tab-item')
    WaveHelpers.waitForPropertyPolling(me, 'editor')
    me.refresh()
    me.editor.focus()
  end
end
