-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Configurable Markup parsing and transformatin #7
Draft
renoirb
wants to merge
4
commits into
traceypooh:main
Choose a base branch
from
renoirb:renoirb/un-markup
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
import { ContextRequest_DateConversion } from './context-date-conversion.js' | ||
import { ContextRequestEvent } from './context.js' | ||
import { isNotNullOrEmptyString } from './utils-wc.js' | ||
|
||
class DateTimeElement extends HTMLElement { | ||
|
||
static get observedAttributes() { | ||
return ['datetime'] | ||
} | ||
|
||
set datetime(input = '') { | ||
if (isNotNullOrEmptyString(input)) { | ||
const currentValue = this.getAttribute('datetime') | ||
const changed = currentValue !== input | ||
changed && this.setAttribute('datetime', input) | ||
} | ||
} | ||
|
||
constructor() { | ||
super() | ||
const shadowRoot = this.attachShadow({ mode: 'open' }) | ||
const template = shadowRoot.ownerDocument.createElement('template') | ||
template.innerHTML = ` | ||
<style> | ||
:host { | ||
display: inline; | ||
} | ||
</style> | ||
<time>...</time> | ||
` | ||
const innerHtml = template.content.cloneNode(true) | ||
shadowRoot.appendChild(innerHtml) | ||
} | ||
|
||
|
||
connectedCallback() { | ||
const datetime = this.getAttribute('datetime') | ||
this.datetime = datetime | ||
if (datetime) { | ||
this.dispatchEvent( | ||
new ContextRequestEvent( | ||
ContextRequest_DateConversion, | ||
this._onContextResponse_DateConversion, | ||
), | ||
) | ||
} | ||
} | ||
|
||
_onContextResponse_DateConversion = (data /*: DateConversion */) => { | ||
const { dateIsoString, dateUnix, dateHuman } = data | ||
const timeEl = this.shadowRoot.querySelector('time') | ||
if (dateIsoString) { | ||
timeEl.setAttribute('datetime', dateIsoString) | ||
} | ||
if (dateUnix) { | ||
// timeEl.setAttribute('data-unix-epoch', dateUnix) | ||
timeEl.dataset.unixEpoch = dateUnix | ||
} | ||
if (dateHuman) { | ||
timeEl.textContent = dateHuman | ||
} | ||
} | ||
|
||
attributeChangedCallback(name, oldValue, newValue) { | ||
const changedWithValue = | ||
oldValue !== newValue && isNotNullOrEmptyString(newValue) | ||
if (changedWithValue) { | ||
if (name === 'datetime') { | ||
this.dispatchEvent( | ||
new ContextRequestEvent( | ||
ContextRequest_DateConversion, | ||
this._onContextResponse_DateConversion, | ||
), | ||
) | ||
} | ||
} | ||
} | ||
} | ||
|
||
export default DateTimeElement |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
import { ContextRequestEvent } from './context.js' | ||
import { ContextRequest_TransformMakup } from './context-markup.js' | ||
|
||
|
||
const SVG_SKELETON_SPINNER = ` | ||
<svg | ||
width="24" | ||
height="24" | ||
viewBox="0 0 24 24" | ||
xmlns="http://www.w3.org/2000/svg" | ||
> | ||
<style> | ||
.spinner_ajPY { | ||
transform-origin: center; | ||
animation: spinner_AtaB .75s infinite linear; | ||
} | ||
@keyframes spinner_AtaB { | ||
100% { | ||
transform: rotate(360deg); | ||
} | ||
} | ||
</style> | ||
<path | ||
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z" | ||
opacity=".25" | ||
/> | ||
<path | ||
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z" | ||
class="spinner_ajPY" | ||
/> | ||
</svg> | ||
` | ||
|
||
/** | ||
* Take markup language (e.g. Markdown, Rst), and get it transformed into HTML. | ||
*/ | ||
class UnMarkupElement extends HTMLElement { | ||
constructor() { | ||
super() | ||
const shadowRoot = this.attachShadow({ mode: 'open' }) | ||
const template = document.createElement('template') | ||
template.innerHTML = ` | ||
<style> | ||
:host { | ||
display: block; | ||
} | ||
#markup-loading { | ||
width: 100%; | ||
} | ||
#markup-source { | ||
display: none; | ||
} | ||
.is-not-transformed #markup-loading { | ||
display: block; | ||
} | ||
.is-not-transformed #markup-transformed { | ||
display: none; | ||
} | ||
.is-transformed #markup-loading { | ||
display: none; | ||
} | ||
.is-transformed #markup-transformed { | ||
display: block; | ||
} | ||
</style> | ||
<div class="disposition-parent"> | ||
<div | ||
id="markup-viewer" | ||
part="markup-viewer" | ||
class="disposition-item is-not-transformed" | ||
> | ||
<div | ||
id="markup-loading" | ||
part="markup-loading" | ||
> | ||
<slot name="skeleton"> | ||
${SVG_SKELETON_SPINNER} | ||
</slot> | ||
</div> | ||
<div id="markup-transformed"></div> | ||
</div> | ||
<div | ||
id="markup-source" | ||
part="markup-source" | ||
class="disposition-item" | ||
> | ||
<pre> | ||
<slot></slot> | ||
</pre> | ||
</div> | ||
</div> | ||
` | ||
const innerHtml = template.content.cloneNode(true) | ||
shadowRoot.appendChild(innerHtml) | ||
let slot = this.shadowRoot.querySelector('slot:not([name])') | ||
slot.addEventListener('slotchange', this._onSlotChange) | ||
} | ||
|
||
_applyTransformedMarkup = (html = '') => { | ||
const transformed = html !== '' | ||
const elMarkupViewer = this.shadowRoot.querySelector('#markup-viewer') | ||
const elTransformed = this.shadowRoot.querySelector( | ||
'#markup-transformed', | ||
) | ||
if (transformed) { | ||
elTransformed.innerHTML = html | ||
elMarkupViewer.classList.remove('is-not-transformed') | ||
elMarkupViewer.classList.add('is-transformed') | ||
} else { | ||
elTransformed.innerHTML = '' | ||
elMarkupViewer.classList.add('is-not-transformed') | ||
elMarkupViewer.classList.remove('is-transformed') | ||
} | ||
} | ||
|
||
/** | ||
* Listen on changes only on default slot, that's the trigger to ask for HTML. | ||
*/ | ||
_onSlotChange = (_event /*: HTMLElementEventMap['slotchange'] */) => { | ||
this.dispatchEvent( | ||
new ContextRequestEvent( | ||
ContextRequest_TransformMakup, | ||
this._onContextResponse_UnMarkup, | ||
), | ||
) | ||
} | ||
|
||
_onContextResponse_UnMarkup = ({ html = '' }) => { | ||
this._applyTransformedMarkup(html) | ||
} | ||
} | ||
|
||
|
||
export default UnMarkupElement |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Can use Symbol, but let's not make this more complex. | ||
/** | ||
* Context Request event for signaling we want to get other formats of the same date. | ||
*/ | ||
export const ContextRequest_DateConversion = 'date-conversion' | ||
|
||
|
||
const KEYS_DateConversion = ['date', 'dateIsoString', 'dateUnix', 'dateHuman'] | ||
|
||
|
||
export const isContextRequest_DateConveresion = (event) => | ||
event.context === ContextRequest_DateConversion | ||
|
||
|
||
export const assertContextRequest_DateConversion = (event) => { | ||
if (!isContextRequest_DateConveresion(event)) { | ||
const message = `Unexpected error, we expected a "ContextRequest_DateConversion" context event` | ||
throw new Error(message) | ||
} | ||
} | ||
|
||
|
||
export const getFromContext_DateConversion = (event) => { | ||
assertContextRequest_DateConversion(event) | ||
const maybeDate = event.originalTarget.getAttribute('datetime') | ||
const dateHumanFormat = event.originalTarget.dataset.dateHumanFormat ?? 'MMM D, YYYY' /* data-date-human-format */ | ||
const date = maybeDate ?? null | ||
return Object.freeze({ | ||
date, | ||
dateHumanFormat, | ||
}) | ||
} | ||
|
||
|
||
export const isValidContextResponse_DateConversion = (payload) => { | ||
const _keys = Object.keys(payload) | ||
const found = _keys.filter((currentValue) => | ||
KEYS_DateConversion.includes(currentValue), | ||
) | ||
return found.length === KEYS_DateConversion.length | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
/** | ||
* Context Request event for signaling Markdown needing to be parsed. | ||
*/ | ||
export const ContextRequest_TransformMakup = 'transform-markup-context' | ||
|
||
|
||
export const isContextRequest_TransformMakup = (event) => | ||
event.context === ContextRequest_TransformMakup | ||
|
||
|
||
export const assertContextRequest_TransformMakup = (event) => { | ||
if (!isContextRequest_TransformMakup(event)) { | ||
const message = `Unexpected error, we expected a "ContextRequest_TransformMakup" context event` | ||
throw new Error(message) | ||
} | ||
} | ||
|
||
|
||
export const markdownReplaceYouTubeShortCodes = (markdownText) => markdownText.replace( | ||
// replace any youtube shortcodes | ||
/{{<\s*youtube\s+([^\s>}]+)\s*>}}/g, | ||
'<iframe width="848" height="477" src="https://www.youtube.com/embed/$1" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>', | ||
) | ||
|
||
|
||
export class TransformMarkupSource { | ||
|
||
frontMatterString /*: string */ = '' | ||
|
||
markup /*: string */ = '' | ||
|
||
frontMatter /*?: Record<string, unknown> */ = void 0 | ||
|
||
html /*?: string */ = void 0 | ||
|
||
get [Symbol.toStringTag]() { | ||
return 'TransformMarkupSource'; | ||
} | ||
|
||
constructor(source /*: string */ = '') { | ||
const isThreeDashesLine = line => /^---$/.test(line) | ||
const lines = source.split('\n') | ||
// Line numbers of frontMatter. | ||
const [fmBeginLn, fmEndLn] = lines.map((ln, lnNbr) => isThreeDashesLine(ln) ? lnNbr : false).filter(i => i) | ||
// Probably bogus | ||
this.frontMatterString = lines.slice(fmBeginLn + 1, fmEndLn).join('\n') | ||
this.markup = lines.slice(fmEndLn + 1).join('\n') | ||
} | ||
} | ||
|
||
|
||
export const getFromContext_TransformMakup = (event) => { | ||
assertContextRequest_TransformMakup(event) | ||
const innerHTML = event.originalTarget.innerHTML | ||
return new TransformMarkupSource(innerHTML) | ||
} | ||
|
||
|
||
export const isValidContextResponse_TransformMakup = (payload) => { | ||
return /TransformMarkupSource/.test('' + payload) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/** | ||
* An event fired by a context requester to signal it desires a specified context with the given key. | ||
* | ||
* A provider should inspect the `context` property of the event to determine if it has a value that can | ||
* satisfy the request, calling the `callback` with the requested value if so. | ||
* | ||
* If the requested context event contains a truthy `subscribe` value, then a provider can call the callback | ||
* multiple times if the value is changed, if this is the case the provider should pass an `unsubscribe` | ||
* method to the callback which consumers can invoke to indicate they no longer wish to receive these updates. | ||
* | ||
* If no `subscribe` value is present in the event, then the provider can assume that this is a 'one time' | ||
* request for the context and can therefore not track the consumer. | ||
* | ||
* To read more, refer to {@link https://github.com/webcomponents-cg/community-protocols/blob/main/proposals/context.md} | ||
*/ | ||
export class ContextRequestEvent extends Event { | ||
/** | ||
* @param context the context key to request | ||
* @param callback the callback that should be invoked when the context with the specified key is available | ||
* @param subscribe an optional argument, if true indicates we want to subscribe to future updates | ||
*/ | ||
constructor(context, callback, subscribe) { | ||
super('context-request', { bubbles: true, composed: true }) | ||
this.context = context | ||
this.callback = callback | ||
this.subscribe = subscribe | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
|
||
const DEP_SHOWDOWN_VERSION = '2.1.0' | ||
const IMPORT_DEP_SHOWDOWN = `https://esm.archive.org/showdown@${DEP_SHOWDOWN_VERSION}` | ||
// const IMPORT_DEP_SHOWDOWN = `https://ga.jspm.io/npm:showdown@${DEP_SHOWDOWN_VERSION}/dist/showdown.js` | ||
|
||
/** | ||
* By default, markup is in Markdown, but could be in another. | ||
*/ | ||
export const markupParser = async (opts = {}) => { | ||
const imported = await import(IMPORT_DEP_SHOWDOWN) | ||
const showdown = imported?.default | ||
const converter = new showdown.Converter({ tables: true, simplifiedAutoLink: true, ...opts }) | ||
converter.setOption('openLinksInNewWindow', true) | ||
|
||
return converter | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Apply replacing contents with parsed markdown without doing it. Let the component handle what to do, trust that the something else calling us back did do the markdown to HTML conversion.