Merge pull request #381 from IBM/fix-code-snippet

CodeSnippet: showMoreLess should update if code is dynamically updated
This commit is contained in:
Eric Liu 2020-10-30 11:00:56 -07:00 committed by GitHub
commit fba37e4d1d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 71 additions and 1 deletions

View file

@ -51,6 +51,20 @@ let comment = `
<CodeSnippet wrapText type="multi" code="{comment}" />
### Dynamic multi-line code
For dynamically updated code, you must use the `code` prop instead of the default slot.
<FileSource src="/framed/CodeSnippet/DynamicCodeSnippet" />
### Hidden multi-line code
There may be cases where your code snippet is hidden in the DOM. The logic to render the "Show more" button relies on the element's computed height. For hidden content, the button will not appear because the computed height is `0`.
The recommended workaround is to re-render the component. See the example below.
<FileSource src="/framed/CodeSnippet/HiddenCodeSnippet" />
### Skeleton
The default skeleton type is `"single"`.

View file

@ -0,0 +1,15 @@
<script>
import { ToggleSmall, CodeSnippet } from "carbon-components-svelte";
let toggled = false;
$: length = toggled ? 20 : 10;
$: code = Array.from({ length }, (_, i) => i + 1).join("\n");
</script>
<ToggleSmall
style="margin-bottom: var(--cds-spacing-05)"
labelText="Trigger snippet overflow"
bind:toggled
/>
<CodeSnippet type="multi" code="{code}" />

View file

@ -0,0 +1,34 @@
<script>
import { ToggleSmall, CodeSnippet } from "carbon-components-svelte";
let toggled = false;
const code = Array.from({ length: 20 }, (_, i) => i + 1).join("\n");
</script>
<style>
.hidden {
display: none;
}
</style>
<ToggleSmall
style="margin-bottom: var(--cds-spacing-05)"
labelText="Show code snippets"
bind:toggled
/>
{#if toggled}
<h5>"Show more" will not render</h5><br />
{/if}
<div class:hidden="{!toggled}">
<CodeSnippet type="multi" code="{code}" />
</div>
{#if toggled}
<br /><br />
<h5>"Show more" will render</h5><br />
<div class:hidden="{!toggled}">
<CodeSnippet type="multi" code="{code}" />
</div>
{/if}

View file

@ -99,15 +99,22 @@
*/
export let ref = null;
import { tick } from "svelte";
import ChevronDown16 from "carbon-icons-svelte/lib/ChevronDown16";
import { Button } from "../Button";
import { Copy } from "../Copy";
import { CopyButton } from "../CopyButton";
import CodeSnippetSkeleton from "./CodeSnippet.Skeleton.svelte";
function setShowMoreLess() {
const { height } = ref.getBoundingClientRect();
if (height > 0) showMoreLess = ref.getBoundingClientRect().height > 255;
}
$: expandText = expanded ? showLessText : showMoreText;
$: if (type === "multi" && ref) {
showMoreLess = ref.getBoundingClientRect().height > 255;
if (code === undefined) setShowMoreLess();
if (code) tick().then(setShowMoreLess);
}
</script>