prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import fs, { readFileSync, writeFileSync } from "fs";
import { argv } from "process";
import readline from "readline";
import events from "events";
import { InstructionSet, parseArchLine } from "./lib/bass";
import { parseNumber } from "./lib/util";
import * as path from "path";
import { AssembledProgram } from "./lib/types";
import { commentRegex, labelRegex } from "./lib/regex";
import { outputInstructions } from "./lib/opcodeOutput";
import { log } from "./lib/log";
import { readArch, readByLines } from "./lib/fs";
interface ComamndEntry {
regex: RegExp;
action: (
line: { line: string; lineNumber: number },
matches: RegExpExecArray,
program: AssembledProgram
) => void;
}
// The commands supported by the assembler (separate from opcodes)
const commands: ComamndEntry[] = [
{
regex: /origin\s+((?:0x)?[a-f0-9]+)/,
action: ({ lineNumber }, [_2, address], program) => {
if (address === undefined) {
log("Could not parse origin", lineNumber);
return;
}
program.currentAddress = parseNumber(address);
},
},
{
regex: /constant\s+(?:(0x[a-f0-9]+|[0-9]+)|([a-z0-9_]+))/,
action: ({ line, lineNumber }, [_, constant, label], program) => {
const address = program.currentAddress;
if (constant !== undefined) {
const value = parseNumber(constant);
if (value > 4095) {
log(
`Constant ${constant} is too large to fit into 12 bits`,
lineNumber
);
return;
}
program.matchedInstructions.push({
type: "constant",
subtype: "literal",
value,
line,
lineNumber,
address,
});
} else if (label !== undefined) {
program.matchedInstructions.push({
type: "constant",
subtype: "label",
label,
line,
lineNumber,
address,
});
} else {
log("Unknown constant error", lineNumber);
return;
}
program.currentAddress += 1;
},
},
];
const parseAsmLine = (
line: string,
lineNumber: number,
instructionSet: InstructionSet,
program: AssembledProgram
) => {
if (line.length == 0 || line.startsWith("//") || line.startsWith(";")) {
// Comment. Skip
return;
}
for (const command of commands) {
const matches = command.regex.exec(line);
if (!!matches && matches.length > 0) {
command.action({ lineNumber, line }, matches, program);
return;
}
}
let hasInstruction = false;
// Match line against all known instructions from the BASS arch
for (const instruction of instructionSet.instructions) {
const matches = instruction.regex.exec(line);
const address = program.currentAddress;
if (!!matches && matches.length > 0) {
if (matches[1] !== undefined) {
// immediate
if (instruction.type !== "immediate") {
log(
"Attempted to match content with non-immediate instruction",
lineNumber
);
return;
}
program.matchedInstructions.push({
type: "immediate",
line,
immediate: parseNumber(matches[1]),
opcodeString: instruction.opcodeString,
bitCount: instruction.immediate.bitCount,
lineNumber,
address,
});
} else if (matches[2] !== undefined) {
// potential label
if (instruction.type !== "immediate") {
log(
"Attempted to match content with non-immediate instruction",
lineNumber
);
return;
}
program.matchedInstructions.push({
type: "label",
line,
label: matches[2],
opcodeString: instruction.opcodeString,
bitCount: instruction.immediate.bitCount,
lineNumber,
address,
});
} else {
// literal only
program.matchedInstructions.push({
type: "literal",
line,
opcodeString: instruction.opcodeString,
lineNumber,
address,
});
}
hasInstruction = true;
program.currentAddress += 1;
break;
}
}
if (hasInstruction && program.unmatchedLabels.length > 0) {
// Add queued labels
for (const label of program.unmatchedLabels) {
const existingLabel = program.matchedLabels[label.label];
if (existingLabel) {
log(
`Label "${label.label}" already exists. Was created on line ${existingLabel.lineNumber}`,
lineNumber
);
return;
}
program.matchedLabels[label.label] = {
lineNumber,
instructionIndex: program.matchedInstructions.length - 1,
address: program.currentAddress - 1,
};
}
// We've processed all labels
program.unmatchedLabels = [];
}
let lineWithoutLabel = line;
const matches = labelRegex.exec(line);
if (!!matches && matches.length > 0 && matches[1]) {
lineWithoutLabel =
lineWithoutLabel.substring(0, matches.index) +
lineWithoutLabel.substring(matches.index + matches[0].length);
const label = matches[1];
const existingLabel = program.matchedLabels[label];
if (existingLabel) {
log(
`Label "${label}" already exists. Was created on line ${existingLabel.lineNumber}`,
lineNumber
);
return;
}
if (hasInstruction) {
// Instruction on this line, pair them up
program.matchedLabels[label] = {
lineNumber,
instructionIndex: program.matchedInstructions.length - 1,
address: program.currentAddress - 1,
};
} else {
// Will pair with some future instruction. Queue it
program.unmatchedLabels.push({
label,
lineNumber,
});
}
}
lineWithoutLabel = lineWithoutLabel.replace(commentRegex, "").trim();
if (!hasInstruction && lineWithoutLabel.length > 0) {
log(`Unknown instruction "${lineWithoutLabel}"`, lineNumber);
}
};
if (argv.length != 4 && argv.length != 5) {
console.log(`Received ${argv.length - 2} arguments. Expected 2-3\n`);
console.log(
"Usage: node assembler.js [input.asm] [output.bin] {true|false: 12 bit output}"
);
process.exit(1);
}
const archPath = path.join(__dirname, "../bass/6200.arch");
const inputFile = argv[2] as string;
const outputFile = argv[3] as string;
const word16Align = argv[4] !== "true";
const build = async () => {
const program: AssembledProgram = {
currentAddress: 0,
matchedInstructions: [],
matchedLabels: {},
unmatchedLabels: [],
};
const instructionSet = await readArch(archPath);
await | readByLines(inputFile, (line, lineNumber) =>
parseAsmLine(line, lineNumber, instructionSet, program)
); |
const outputBuffer = outputInstructions(program, word16Align);
if (outputBuffer.type === "some") {
writeFileSync(outputFile, outputBuffer.value);
} else {
console.log("Could not generate output binary");
}
};
build();
| src/assembler.ts | agg23-tamagotchi-disassembled-421eacb | [
{
"filename": "src/lib/fs.ts",
"retrieved_chunk": " await readByLines(path, (line, lineNumber) =>\n parseArchLine(line, lineNumber, instructionSet)\n );\n return instructionSet;\n};",
"score": 0.8589311242103577
},
{
"filename": "src/lib/bass.ts",
"retrieved_chunk": " * @param config The global instruction set config\n * @returns\n */\nexport const parseArchLine = (\n line: string,\n lineNumber: number,\n config: InstructionSet\n) => {\n if (line.length == 0 || line.startsWith(\"//\") || line.startsWith(\"#\")) {\n // Comment. Skip",
"score": 0.8269684910774231
},
{
"filename": "src/lib/disassembly.ts",
"retrieved_chunk": " let labelCount = 0;\n const namedLabels: Array<\n | {\n name: string;\n instructions: DisassembledInstruction[];\n }\n | undefined\n > = unsetLabels.map((instructions) => {\n if (!!instructions) {\n return {",
"score": 0.824080765247345
},
{
"filename": "src/lib/disassembly.ts",
"retrieved_chunk": " name: `label_${labelCount++}`,\n instructions,\n };\n }\n return undefined;\n });\n // Build list of instructions that will replace the immedates with these labels, and build labels\n const labelUsageMap: Array<string | undefined> = new Array(8192);\n for (const namedLabel of namedLabels) {\n if (namedLabel) {",
"score": 0.8237888813018799
},
{
"filename": "src/lib/fs.ts",
"retrieved_chunk": "};\n/**\n * Reads and parses the BASS arch file\n * @param path The path of the arch file\n * @returns The InstructionSet resulting from parsing the arch file\n */\nexport const readArch = async (path: string): Promise<InstructionSet> => {\n const instructionSet: InstructionSet = {\n instructions: [],\n };",
"score": 0.8163011074066162
}
] | typescript | readByLines(inputFile, (line, lineNumber) =>
parseAsmLine(line, lineNumber, instructionSet, program)
); |
import { log } from "./log";
import { AssembledProgram, Option } from "./types";
import { maskOfSize } from "./util";
/**
* Builds the output buffer from the matched instructions
* @param program The configured program we have built
* @param word16Align If true, align the 12 bit opcodes to 16 bit words. The lowest nibble will be 0
* @returns The output buffer that should be written to the assembled binary
*/
export const outputInstructions = (
program: AssembledProgram,
word16Align: boolean
): Option<Buffer> => {
// This buffer stores each nibble of the program separately, and we will combine this later into the output buffer
const threeNibbleBuffer: number[] = new Array(8192 * 3);
// Fill array with 0xF
for (let i = 0; i < threeNibbleBuffer.length; i++) {
threeNibbleBuffer[i] = 0xf;
}
for (const instruction of program.matchedInstructions) {
let opcode = 0;
switch (instruction.type) {
case "literal": {
opcode = buildOpcode(instruction.opcodeString, 0, 0);
break;
}
case "immediate": {
opcode = buildOpcode(
instruction.opcodeString,
instruction.bitCount,
instruction.immediate
);
break;
}
case "label": {
const label = | program.matchedLabels[instruction.label]; |
if (!label) {
log(`Unknown label ${instruction.label}`, instruction.lineNumber);
return { type: "none" };
}
opcode = buildOpcode(
instruction.opcodeString,
instruction.bitCount,
label.address
);
break;
}
case "constant": {
if (instruction.subtype === "literal") {
opcode = instruction.value;
} else {
// Label
const label = program.matchedLabels[instruction.label];
if (!label) {
log(`Unknown label ${instruction.label}`, instruction.lineNumber);
return { type: "none" };
}
console.log(`${label.address.toString(16)}`);
opcode = label.address;
}
break;
}
}
const low = opcode & 0xf;
const mid = (opcode & 0xf0) >> 4;
const high = (opcode & 0xf00) >> 8;
const baseAddress = instruction.address * 3;
// We use reverse order because that's how the nibbles are in the ROM
threeNibbleBuffer[baseAddress] = high;
threeNibbleBuffer[baseAddress + 1] = mid;
threeNibbleBuffer[baseAddress + 2] = low;
}
return {
type: "some",
value: copyToOutputBuffer(threeNibbleBuffer, word16Align),
};
};
const copyToOutputBuffer = (
threeNibbleBuffer: number[],
word16Align: boolean
): Buffer => {
const bufferSize = word16Align ? 8192 * 2 : (8192 * 3) / 2;
const buffer = Buffer.alloc(bufferSize);
let byteBuffer = 0;
let bufferAddress = 0;
let lowNibble = false;
let evenByte = true;
for (let i = 0; i < threeNibbleBuffer.length; i++) {
const nibble = threeNibbleBuffer[i]!;
const writeSpacerValue = word16Align && !lowNibble && evenByte;
if (lowNibble || writeSpacerValue) {
// "Second", lower value of byte, or we're writing the spacer now
byteBuffer |= nibble;
buffer[bufferAddress] = byteBuffer;
bufferAddress += 1;
byteBuffer = 0;
evenByte = !evenByte;
} else {
// "First", upper value of byte
byteBuffer |= nibble << 4;
}
if (!writeSpacerValue) {
// We've moved to the next byte if we wrote a spacer, so stay at !lowNibble
lowNibble = !lowNibble;
}
}
return buffer;
};
/**
* Comsumes the opcode template from the BASS arch file and produces the actual output word
* @param template The opcode template from the BASS arch file
* @param argSize The number of bits in an argument to the opcode, if any
* @param argument The actual data to pass as an argument to the opcode, if any
* @returns The output opcode as a 12 bit word
*/
export const buildOpcode = (
template: string,
argSize: number,
argument: number
) => {
let index = 0;
let outputWord = 0;
while (index < template.length) {
const char = template[index];
if (char === "%") {
// Consume chars until whitespace
let data = 0;
let count = 0;
for (let i = 1; i < Math.min(13, template.length - index); i++) {
const nextChar = template[index + i]!;
if (nextChar !== "1" && nextChar !== "0") {
// Stop consuming
break;
}
data <<= 1;
data |= nextChar === "1" ? 1 : 0;
count += 1;
}
// Consume the next four chars as bits
outputWord <<= count;
outputWord |= data;
index += count + 1;
} else if (char === "=") {
if (template[index + 1] !== "a") {
console.log(
`ERROR: Unexpected char after = in instruction definition "${template}"`
);
return 0;
}
outputWord <<= argSize;
outputWord |= maskOfSize(argSize) & argument;
index += 2;
} else {
index += 1;
}
}
return outputWord;
};
| src/lib/opcodeOutput.ts | agg23-tamagotchi-disassembled-421eacb | [
{
"filename": "src/assembler.ts",
"retrieved_chunk": " program.matchedInstructions.push({\n type: \"label\",\n line,\n label: matches[2],\n opcodeString: instruction.opcodeString,\n bitCount: instruction.immediate.bitCount,\n lineNumber,\n address,\n });\n } else {",
"score": 0.8663920164108276
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " lineNumber,\n address,\n });\n } else if (label !== undefined) {\n program.matchedInstructions.push({\n type: \"constant\",\n subtype: \"label\",\n label,\n line,\n lineNumber,",
"score": 0.8431950807571411
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " // literal only\n program.matchedInstructions.push({\n type: \"literal\",\n line,\n opcodeString: instruction.opcodeString,\n lineNumber,\n address,\n });\n }\n hasInstruction = true;",
"score": 0.8401477932929993
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " const matches = instruction.regex.exec(line);\n const address = program.currentAddress;\n if (!!matches && matches.length > 0) {\n if (matches[1] !== undefined) {\n // immediate\n if (instruction.type !== \"immediate\") {\n log(\n \"Attempted to match content with non-immediate instruction\",\n lineNumber\n );",
"score": 0.8343341946601868
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " `Constant ${constant} is too large to fit into 12 bits`,\n lineNumber\n );\n return;\n }\n program.matchedInstructions.push({\n type: \"constant\",\n subtype: \"literal\",\n value,\n line,",
"score": 0.8305165767669678
}
] | typescript | program.matchedLabels[instruction.label]; |
import { DisassembledInstruction } from "./types";
import { isLetterChar, maskOfSize } from "./util";
export const buildDisassembledInstructionString = (
{ instruction, actualWord, address }: DisassembledInstruction,
immediateLabel: string | undefined
) => {
let instructionString = instruction.originalInstruction;
if (instruction.type === "immediate") {
const { bitCount, stringIndex, stringLength } = instruction.immediate;
const immediatePrefix = instructionString.substring(0, stringIndex);
const immediateSuffix = instructionString.substring(
stringIndex + stringLength
);
let immediate = "";
if (immediateLabel) {
immediate = immediateLabel;
} else {
const argument = maskOfSize(bitCount) & actualWord;
if (isLetterChar(immediatePrefix.charAt(immediatePrefix.length - 1))) {
// If letter, treat as decimal
immediate = argument.toString();
} else {
// Otherwise, treat as hex
immediate = `0x${argument.toString(16).toUpperCase()}`;
}
}
instructionString = `${immediatePrefix}${immediate}${immediateSuffix}`;
}
// Separate out instruction so that it formats nicely
// Four total columns
// Opcode - Source - Dest - Comments
const splitInstruction = instructionString.split(/\s+/);
let lastPadWidth = 0;
for (let i = 2; i >= splitInstruction.length - 1; i--) {
lastPadWidth += columnPadWidth(i);
}
const formattedInstructionString = splitInstruction
.map(( | s, i) => { |
const pad =
i === splitInstruction.length - 1 ? lastPadWidth : columnPadWidth(i);
return s.padEnd(pad);
})
.join("");
const comment = `// 0x${address
.toString(16)
.toUpperCase()
.padEnd(4)} (0x${actualWord.toString(16).toUpperCase()})`;
return `${formattedInstructionString.padEnd(81)}${comment}`;
};
const columnPadWidth = (column: number) => {
switch (column) {
case 0:
return 6;
case 1:
return 5;
case 2:
return 10;
}
return 0;
};
| src/lib/display.ts | agg23-tamagotchi-disassembled-421eacb | [
{
"filename": "src/lib/bass.ts",
"retrieved_chunk": " });\n }\n};\nconst buildSortableOpcode = (template: string, bitCount: number) =>\n buildOpcode(template, bitCount, 0);\nconst cleanAndFinishInstructionRegex = (instruction: string): RegExp => {\n const cleaned = instruction\n .trim()\n .replace(whitespaceRegex, whitespaceRegex.source);\n // Force nothing but whitespace from beginning of string to instruction",
"score": 0.8535762429237366
},
{
"filename": "src/lib/disassembly.ts",
"retrieved_chunk": "};\nconst findWordInstruction = (word: number, instructions: Instruction[]) => {\n // Naive because it doesn't really matter\n let bestMatch = instructions[0]!;\n for (let i = 0; i < instructions.length; i++) {\n const instruction = instructions[i]!;\n if (instruction.sortableOpcode <= word) {\n bestMatch = instruction;\n } else {\n // We've passed the best solution, end",
"score": 0.8478375673294067
},
{
"filename": "src/lib/opcodeOutput.ts",
"retrieved_chunk": " let index = 0;\n let outputWord = 0;\n while (index < template.length) {\n const char = template[index];\n if (char === \"%\") {\n // Consume chars until whitespace\n let data = 0;\n let count = 0;\n for (let i = 1; i < Math.min(13, template.length - index); i++) {\n const nextChar = template[index + i]!;",
"score": 0.8441192507743835
},
{
"filename": "src/lib/bass.ts",
"retrieved_chunk": " const [originalInstruction, opcode] = sections;\n if (!originalInstruction || !opcode) {\n log(\"Unknown input\", lineNumber);\n return;\n }\n const opcodeString = opcode.trim();\n let numberMatch = originalInstruction.match(bassNumberRegex);\n if (!!numberMatch && numberMatch.index) {\n // This instruction contains a star followed by a number\n // This is an immediate",
"score": 0.8365297317504883
},
{
"filename": "src/assembler.ts",
"retrieved_chunk": " for (const command of commands) {\n const matches = command.regex.exec(line);\n if (!!matches && matches.length > 0) {\n command.action({ lineNumber, line }, matches, program);\n return;\n }\n }\n let hasInstruction = false;\n // Match line against all known instructions from the BASS arch\n for (const instruction of instructionSet.instructions) {",
"score": 0.8357698917388916
}
] | typescript | s, i) => { |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.geometry = Plane(device);
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: | { buffer: camera.getBuffer() },
},
],
}); |
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { lines } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,\n resource: { buffer },\n },\n ],",
"score": 0.9563202857971191
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " });\n this.bindings = {\n data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: data },\n },\n {",
"score": 0.9522155523300171
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " },\n {\n binding: 2,\n resource: { buffer: uniforms },\n },\n ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [",
"score": 0.9450139403343201
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " binding: 1,\n resource: { buffer: uniforms },\n },\n ],\n }),\n points: points.map((buffer, i) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,",
"score": 0.9403854608535767
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: joints },\n },\n {\n binding: 1,\n resource: { buffer: lines },",
"score": 0.9193938970565796
}
] | typescript | { buffer: camera.getBuffer() },
},
],
}); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) isize: f32,
@location(4) iuv: vec2<f32>,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vertex.isize + vertex.iposition, 0, 1);
out.size = vertex.isize;
out.uv = (vertex.uv - 0.5) * 2;
out.uv2 = vertex.iuv;
return out;
}
`;
const Fragment = /* wgsl */`
struct FragmentInput {
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(1) var texture: texture_2d<f32>;
@group(0) @binding(2) var textureSampler: sampler;
fn linearTosRGB(linear: vec3<f32>) -> vec3<f32> {
if (all(linear <= vec3<f32>(0.0031308))) {
return linear * 12.92;
}
return (pow(abs(linear), vec3<f32>(1.0/2.4)) * 1.055) - vec3<f32>(0.055);
}
@fragment
fn main(fragment: FragmentInput) -> @location(0) vec4<f32> {
let l = min(length(fragment.uv), 1);
var uv = fragment.uv2 + (fragment.uv / fragment.size / 33);
return vec4<f32>(linearTosRGB(
textureSample(texture, textureSampler, uv).xyz + smoothstep(0.5, 1, l) * 0.1
), smoothstep(1, 0.8, l));
}
`;
class Points {
private readonly bindings: GPUBindGroup;
private readonly device: GPUDevice;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
private readonly texture: GPUTexture;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.device = device;
| this.geometry = Plane(device, 2, 2); |
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 3,
offset: 1 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{
format,
blend: {
color: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
alpha: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
},
}],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.texture = device.createTexture({
dimension: '2d',
format: 'rgba8unorm-srgb',
size: [512, 512],
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
{
binding: 1,
resource: this.texture.createView(),
},
{
binding: 2,
resource: device.createSampler({ minFilter: 'linear', magFilter: 'linear' }),
},
],
});
this.simulation = simulation;
this.generateDefaultTexture();
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { count, data, points } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, points);
pass.setVertexBuffer(2, data);
pass.draw(6, count, 0, 0);
}
setTexture(file: Blob) {
const image = new Image();
image.addEventListener('load', () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
let x = 0;
let y = 0;
let w = canvas.width = 512;
let h = canvas.height = 512;
if (image.width / image.height > w / h) {
w = image.width * canvas.height / image.height;
x = (canvas.width - w) * 0.5;
} else {
h = image.height * canvas.width / image.width;
y = (canvas.height - h) * 0.5;
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);
this.updateTexture(canvas);
});
image.src = URL.createObjectURL(file);
}
private generateDefaultTexture() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = canvas.height = 512;
for (let i = 0; i < 256; i++) {
ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;
ctx.beginPath();
ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);
ctx.fill();
}
this.updateTexture(canvas);
}
private async updateTexture(canvas: HTMLCanvasElement) {
const { device, texture } = this;
const source = await createImageBitmap(canvas)
device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]);
}
}
export default Points;
| src/render/points.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/lines.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.geometry = Plane(device);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {\n buffers: [",
"score": 0.9174891114234924
},
{
"filename": "src/compute/simulation/index.ts",
"retrieved_chunk": " step: StepSimulation,\n };\n private step: number = 0;\n private readonly uniforms: UniformsBuffer;\n constructor(device: GPUDevice) {\n this.device = device;\n this.uniforms = new UniformsBuffer(device);\n }\n compute(\n command: GPUCommandEncoder,",
"score": 0.887808084487915
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');",
"score": 0.8779371976852417
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " private readonly workgroups: number;\n constructor(\n device: GPUDevice,\n joints: GPUBuffer,\n numJoints: number,\n lines: GPUBuffer,\n points: GPUBuffer[],\n numPoints: number,\n uniforms: GPUBuffer\n ) {",
"score": 0.8554661273956299
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " this.animation.loop = loop;\n }\n setSize(width: number, height: number) {\n const {\n camera,\n canvas,\n descriptor: { colorAttachments: [color] },\n device,\n format,\n samples,",
"score": 0.8503270745277405
}
] | typescript | this.geometry = Plane(device, 2, 2); |
import { vec2 } from 'gl-matrix';
import Camera from '../render/camera';
class Input {
private hotkeys: Record<string, () => void> = {};
private readonly pointer: {
id: number;
button: number;
normalized: vec2;
position: vec2;
};
constructor(target: HTMLCanvasElement) {
this.pointer = {
id: -1,
button: 0,
normalized: vec2.fromValues(-1, -1),
position: vec2.create(),
};
window.addEventListener('keydown', this.onKeyDown.bind(this));
target.addEventListener('pointerdown', this.onPointerDown.bind(this));
window.addEventListener('pointermove', this.onPointerMove.bind(this));
target.addEventListener('pointerup', this.onPointerUp.bind(this));
{
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = 20;
canvas.height = 20;
ctx.lineWidth = 5;
ctx.strokeStyle = '#111';
ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 3;
ctx.strokeStyle = '#eee';
ctx.stroke();
canvas.toBlob((blob) => {
if (blob) {
document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`;
}
});
}
}
getPointer(camera: | Camera) { |
const { pointer } = this;
vec2.transformMat4(
pointer.position,
pointer.normalized,
camera.getMatrixInverse()
);
return pointer;
}
setHotkeys(hotkeys: Record<string, () => void>) {
this.hotkeys = hotkeys;
}
private onKeyDown({ key, repeat, target }: KeyboardEvent) {
const { hotkeys } = this;
const handler = hotkeys[key.toLowerCase()];
if (
handler
&& !repeat
&& !['input', 'textarea', 'select'].includes(
(target as HTMLElement).tagName.toLowerCase()
)
) {
handler();
}
}
private onPointerDown({ buttons, pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).setPointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== -1) {
return;
}
pointer.id = pointerId;
pointer.button = buttons;
}
private onPointerMove({ pointerId, clientX, clientY }: PointerEvent) {
const { pointer } = this;
if (pointer.id !== -1 && pointer.id !== pointerId) {
return;
}
vec2.set(
pointer.normalized,
(clientX / window.innerWidth) * 2 - 1,
-(clientY / window.innerHeight) * 2 + 1
);
}
private onPointerUp({ pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).releasePointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== pointerId) {
return;
}
pointer.id = -1;
pointer.button = 0;
}
}
export default Input;
| src/compute/input.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/main.ts",
"retrieved_chunk": " points.setTexture(file);\n }\n });\n window.addEventListener('resize', () => (\n renderer.setSize(window.innerWidth, window.innerHeight)\n ));\n window.addEventListener('wheel', ({ deltaY }) => (\n camera.setZoom(Math.min(Math.max(camera.getZoom() * (1 + deltaY * 0.001), 200), 400))\n ));\n};",
"score": 0.771067202091217
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " ctx.fill();\n }\n this.updateTexture(canvas);\n }\n private async updateTexture(canvas: HTMLCanvasElement) {\n const { device, texture } = this;\n const source = await createImageBitmap(canvas)\n device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]);\n }\n}",
"score": 0.7501084208488464
},
{
"filename": "src/main.ts",
"retrieved_chunk": " 3: () => simulation.load(Ropes()),\n 4: () => simulation.load(Cloth(true, false)),\n 5: () => simulation.load(Cloth(true, true)),\n escape: () => simulation.reset(),\n '?': () => document.getElementById('help')?.classList.toggle('hidden'), \n });\n window.addEventListener('drop', (e) => {\n e.preventDefault();\n const [file] = e.dataTransfer?.files || [];\n if (file && file.type.indexOf('image/') === 0) {",
"score": 0.7431517243385315
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " pass.setVertexBuffer(2, data);\n pass.draw(6, count, 0, 0);\n }\n setTexture(file: Blob) {\n const image = new Image();\n image.addEventListener('load', () => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");",
"score": 0.7349271178245544
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " y = (canvas.height - h) * 0.5;\n }\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);\n this.updateTexture(canvas);\n });\n image.src = URL.createObjectURL(file);\n }\n private generateDefaultTexture() {",
"score": 0.723669171333313
}
] | typescript | Camera) { |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.geometry = Plane(device);
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
],
});
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { | lines } = simulation.getBuffers(); |
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " this.simulation = simulation;\n this.generateDefaultTexture();\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { count, data, points } = simulation.getBuffers();\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings);\n pass.setVertexBuffer(0, geometry);\n pass.setVertexBuffer(1, points);",
"score": 0.8731337785720825
},
{
"filename": "src/compute/simulation/index.ts",
"retrieved_chunk": " numPoints,\n this.uniforms.getBuffer()\n ),\n };\n }\n reset() {\n const { buffers, device, initial } = this;\n if (!buffers || !initial) {\n return;\n }",
"score": 0.8595871329307556
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " }\n private render(command: GPUCommandEncoder) {\n const {\n context,\n descriptor,\n objects,\n } = this;\n const { colorAttachments: [color] } = descriptor;\n color!.resolveTarget = context.getCurrentTexture().createView();\n const pass = command.beginRenderPass(descriptor);",
"score": 0.8555238842964172
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {",
"score": 0.8460768461227417
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " {\n binding: 0,\n resource: { buffer },\n },\n ],\n })),\n };\n this.workgroups = Math.ceil(numJoints / 256);\n }\n compute(pass: GPUComputePassEncoder, step: number) {",
"score": 0.8401266932487488
}
] | typescript | lines } = simulation.getBuffers(); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this. | geometry = Plane(device); |
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
],
});
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { lines } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {",
"score": 0.9210299253463745
},
{
"filename": "src/compute/simulation/index.ts",
"retrieved_chunk": " step: StepSimulation,\n };\n private step: number = 0;\n private readonly uniforms: UniformsBuffer;\n constructor(device: GPUDevice) {\n this.device = device;\n this.uniforms = new UniformsBuffer(device);\n }\n compute(\n command: GPUCommandEncoder,",
"score": 0.8886329531669617
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');",
"score": 0.8638205528259277
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " private readonly workgroups: number;\n constructor(\n device: GPUDevice,\n joints: GPUBuffer,\n numJoints: number,\n lines: GPUBuffer,\n points: GPUBuffer[],\n numPoints: number,\n uniforms: GPUBuffer\n ) {",
"score": 0.860231876373291
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,",
"score": 0.8553609251976013
}
] | typescript | geometry = Plane(device); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) irotation: f32,
@location(4) isize: f32,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
fn rotate(rad: f32) -> mat2x2<f32> {
var c: f32 = cos(rad);
var s: f32 = sin(rad);
return mat2x2<f32>(c, s, -s, c);
}
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vec2<f32>(1, vertex.isize) * rotate(vertex.irotation) + vertex.iposition, 0, 1);
return out;
}
`;
const Fragment = /* wgsl */`
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(vec3(0.125), 1);
}
`;
class Lines {
private readonly bindings: GPUBindGroup;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
| this.geometry = Plane(device); |
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 3,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 3 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{ format }],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: { buffer: camera.getBuffer() },
},
],
});
this.simulation = simulation;
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { lines } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, lines, 16);
pass.drawIndirect(lines, 0);
}
}
export default Lines;
| src/render/lines.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " device: GPUDevice,\n format: GPUTextureFormat,\n samples: number,\n simulation: Simulation,\n ) {\n this.device = device;\n this.geometry = Plane(device, 2, 2);\n this.pipeline = device.createRenderPipeline({\n layout: 'auto',\n vertex: {",
"score": 0.9111255407333374
},
{
"filename": "src/compute/simulation/index.ts",
"retrieved_chunk": " step: StepSimulation,\n };\n private step: number = 0;\n private readonly uniforms: UniformsBuffer;\n constructor(device: GPUDevice) {\n this.device = device;\n this.uniforms = new UniformsBuffer(device);\n }\n compute(\n command: GPUCommandEncoder,",
"score": 0.8942488431930542
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " private readonly descriptor: GPURenderPassDescriptor;\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];\n private readonly samples: number = 4;\n private target: GPUTexture = undefined as unknown as GPUTexture;\n constructor(camera: Camera, device: GPUDevice) {\n this.camera = camera;\n this.canvas = document.createElement('canvas');\n const context = this.canvas.getContext('webgpu');",
"score": 0.8860450983047485
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": "`;\nclass Points {\n private readonly bindings: GPUBindGroup;\n private readonly device: GPUDevice;\n private readonly geometry: GPUBuffer;\n private readonly pipeline: GPURenderPipeline;\n private readonly simulation: Simulation;\n private readonly texture: GPUTexture;\n constructor(\n camera: Camera,",
"score": 0.8836076855659485
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " data: GPUBindGroup,\n points: GPUBindGroup[],\n };\n private readonly pipeline: GPUComputePipeline;\n private readonly workgroups: number;\n constructor(\n device: GPUDevice,\n data: GPUBuffer,\n points: GPUBuffer[],\n numPoints: number,",
"score": 0.8633000254631042
}
] | typescript | this.geometry = Plane(device); |
import { Joint, JointBuffer, Point, PointBuffers } from '../simulation/types';
export default (large: boolean = false, tension: boolean = false) => {
const width = large ? 65 : 33;
const height = large ? 65 : 33;
const gap = 4;
const points: Point[] = [];
const joints: Joint[] = [];
for (let i = 0, y = 0; y < height; y++) {
for (let x = 0; x < width; x++, i++) {
points.push({
locked: tension ? (
((y === 0 || y === height - 1) && (x % 8 === 0))
|| ((x === 0 || x === width - 1) && (y % 8 === 0))
) : (
y === height - 1 && (x % 8 === 0)
),
position: {
x: (x - width * 0.5 + 0.5) * gap * 1.125 + gap * (Math.random() - 0.25) * 0.125,
y: (y - height * 0.5 + 0.5) * gap + gap * (Math.random() - 0.5) * 0.125 + height * gap * 0.2,
},
size: 1.5 + Math.random() * 0.5,
uv: {
x: (x + 0.5) / width,
y: (y + 0.5) / height,
},
});
if (x < width - 1) {
joints.push({
enabled: true,
a: i,
b: i + 1,
length: 0,
});
}
if (y > 0) {
joints.push({
enabled: true,
a: i,
b: i - width,
length: 0,
});
}
}
}
joints.forEach((joint) => {
const a = points | [joint.a].position; |
const b = points[joint.b].position;
joint.length = Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
});
if (tension || large) {
points.forEach(({ position }) => {
if (tension) position.x *= 1.25;
position.y = (position.y - height * gap * 0.2) * 1.4;
});
}
return {
...PointBuffers(points),
joints: JointBuffer(joints),
numJoints: joints.length,
numPoints: points.length,
};
}
| src/compute/generation/cloth.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/generation/ropes.ts",
"retrieved_chunk": " a: o + a,\n b: o + b,\n length: 8,\n }));\n }\n return {\n ...PointBuffers(points),\n joints: JointBuffer(joints),\n numJoints: joints.length,\n numPoints: points.length,",
"score": 0.8338941335678101
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " if (data[joint.a].locked == 0) {\n points[joint.a] = origin + edge;\n }\n if (data[joint.b].locked == 0) {\n points[joint.b] = origin - edge;\n }\n }\n }\n}\n`;",
"score": 0.8306076526641846
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " {\n binding: 0,\n resource: { buffer },\n },\n ],\n })),\n };\n this.workgroups = Math.ceil(numJoints / 256);\n }\n compute(pass: GPUComputePassEncoder, step: number) {",
"score": 0.7986390590667725
},
{
"filename": "src/compute/generation/ropes.ts",
"retrieved_chunk": " points[o + 2].position.x -= 4;\n points[o + 1].position.x += 4;\n [\n [3, 2],\n [3, 1],\n [2, 1],\n [2, 0],\n [1, 0],\n ].forEach(([a, b]) => joints.push({\n enabled: true,",
"score": 0.7818101644515991
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " resource: { buffer },\n },\n {\n binding: 1,\n resource: { buffer: points[(i + 1) % 2] },\n },\n ],\n })),\n };\n this.workgroups = Math.ceil(numPoints / 256);",
"score": 0.7806244492530823
}
] | typescript | [joint.a].position; |
import ConstrainSimulation from './constrain';
import ComputeLines from './lines';
import StepSimulation from './step';
import { LineBuffer, UniformsBuffer } from './types';
class Simulation {
private buffers?: {
data: GPUBuffer;
joints: GPUBuffer;
lines: GPUBuffer;
points: GPUBuffer[];
};
private count: number = 0;
private device: GPUDevice;
private initial?: {
joints: ArrayBuffer;
points: ArrayBuffer;
};
private pipelines?: {
constraint: ConstrainSimulation,
lines: ComputeLines,
step: StepSimulation,
};
private step: number = 0;
private readonly uniforms: UniformsBuffer;
constructor(device: GPUDevice) {
this.device = device;
this.uniforms = new UniformsBuffer(device);
}
compute(
command: GPUCommandEncoder,
delta: number,
pointer: { button: number; position: [number, number] | Float32Array; },
radius: number
) {
const { buffers, pipelines, step, uniforms } = this;
if (!buffers || !pipelines) {
return;
}
uniforms.delta = delta;
uniforms.button = pointer.button;
uniforms.pointer = pointer.position;
uniforms.radius = radius;
uniforms.update();
const pass = command.beginComputePass();
pipelines. | step.compute(pass, step); |
this.step = (this.step + 1) % 2;
pipelines.constraint.compute(pass, this.step);
pipelines.lines.compute(pass, this.step);
pass.end();
}
getBuffers() {
const { buffers, count, step } = this;
if (!buffers) {
throw new Error("Simulation is not loaded");
}
return {
count,
data: buffers.data,
lines: buffers.lines,
points: buffers.points[step],
};
}
load(
{ data, joints, numJoints, points, numPoints }: {
data: ArrayBuffer;
joints: ArrayBuffer;
numJoints: number;
points: ArrayBuffer;
numPoints: number;
}
) {
const { device } = this;
const createBuffer = (data: ArrayBuffer, usage: number) => {
const buffer = device.createBuffer({
mappedAtCreation: true,
size: data.byteLength,
usage,
});
new Uint32Array(buffer.getMappedRange()).set(new Uint32Array(data));
buffer.unmap();
return buffer;
};
if (this.buffers) {
this.buffers.data.destroy();
this.buffers.joints.destroy();
this.buffers.lines.destroy();
this.buffers.points.forEach((buffer) => buffer.destroy());
}
this.buffers = {
data: createBuffer(
data,
GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX
),
joints: createBuffer(
joints,
GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE
),
lines: LineBuffer(device, numJoints),
points: Array.from({ length: 2 }, () => createBuffer(
points,
GPUBufferUsage.COPY_DST
| GPUBufferUsage.STORAGE
| GPUBufferUsage.VERTEX
)),
};
this.count = numPoints;
this.initial = { joints, points };
this.pipelines = {
constraint: new ConstrainSimulation(
device,
this.buffers.data,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints
),
lines: new ComputeLines(
device,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
step: new StepSimulation(
device,
this.buffers.data,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
};
}
reset() {
const { buffers, device, initial } = this;
if (!buffers || !initial) {
return;
}
device.queue.writeBuffer(buffers.joints, 0, initial.joints);
buffers.points.forEach((buffer) => (
device.queue.writeBuffer(buffer, 0, initial.points)
));
}
}
export default Simulation;
| src/compute/simulation/index.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " let index: u32 = id.x;\n if (index >= ${numPoints}) {\n return;\n }\n var point = input[index];\n if (data[index].locked == 0) {\n point += point - output[index];\n point += vec2<f32>(0, -8) * uniforms.delta;\n if (uniforms.button != 2) {\n var d = point - uniforms.pointer;",
"score": 0.770727276802063
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " if (length(d) < min(uniforms.radius * 4, 24)) {\n point += d * uniforms.radius * uniforms.delta;\n }\n }\n }\n output[index] = point;\n}\n`;\nclass StepSimulation {\n private readonly bindings: {",
"score": 0.7591146230697632
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " this.simulation = simulation;\n this.generateDefaultTexture();\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { count, data, points } = simulation.getBuffers();\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings);\n pass.setVertexBuffer(0, geometry);\n pass.setVertexBuffer(1, points);",
"score": 0.7525990009307861
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " })),\n };\n }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(1);\n }",
"score": 0.7453408241271973
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " }\n var joint = joints[index];\n if (joint.enabled == 0) {\n return;\n }\n if (uniforms.button == 2) {\n if (\n sdSegment(uniforms.pointer, points[joint.a], points[joint.b]) <= uniforms.radius * 0.25\n ) {\n joints[index].enabled = 0;",
"score": 0.7426780462265015
}
] | typescript | step.compute(pass, step); |
import { vec2 } from 'gl-matrix';
import Camera from '../render/camera';
class Input {
private hotkeys: Record<string, () => void> = {};
private readonly pointer: {
id: number;
button: number;
normalized: vec2;
position: vec2;
};
constructor(target: HTMLCanvasElement) {
this.pointer = {
id: -1,
button: 0,
normalized: vec2.fromValues(-1, -1),
position: vec2.create(),
};
window.addEventListener('keydown', this.onKeyDown.bind(this));
target.addEventListener('pointerdown', this.onPointerDown.bind(this));
window.addEventListener('pointermove', this.onPointerMove.bind(this));
target.addEventListener('pointerup', this.onPointerUp.bind(this));
{
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = 20;
canvas.height = 20;
ctx.lineWidth = 5;
ctx.strokeStyle = '#111';
ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 3;
ctx.strokeStyle = '#eee';
ctx.stroke();
canvas.toBlob((blob) => {
if (blob) {
document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`;
}
});
}
}
getPointer(camera: Camera) {
const { pointer } = this;
vec2.transformMat4(
pointer.position,
pointer.normalized,
| camera.getMatrixInverse()
); |
return pointer;
}
setHotkeys(hotkeys: Record<string, () => void>) {
this.hotkeys = hotkeys;
}
private onKeyDown({ key, repeat, target }: KeyboardEvent) {
const { hotkeys } = this;
const handler = hotkeys[key.toLowerCase()];
if (
handler
&& !repeat
&& !['input', 'textarea', 'select'].includes(
(target as HTMLElement).tagName.toLowerCase()
)
) {
handler();
}
}
private onPointerDown({ buttons, pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).setPointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== -1) {
return;
}
pointer.id = pointerId;
pointer.button = buttons;
}
private onPointerMove({ pointerId, clientX, clientY }: PointerEvent) {
const { pointer } = this;
if (pointer.id !== -1 && pointer.id !== pointerId) {
return;
}
vec2.set(
pointer.normalized,
(clientX / window.innerWidth) * 2 - 1,
-(clientY / window.innerHeight) * 2 + 1
);
}
private onPointerUp({ pointerId, target }: PointerEvent) {
(target as HTMLCanvasElement).releasePointerCapture(pointerId);
const { pointer } = this;
if (pointer.id !== pointerId) {
return;
}
pointer.id = -1;
pointer.button = 0;
}
}
export default Input;
| src/compute/input.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/camera.ts",
"retrieved_chunk": " private readonly position: vec2;\n constructor(device: GPUDevice) {\n this.aspect = 1;\n this.near = -100;\n this.far = 100;\n this.zoom = 200;\n this.position = vec2.create();\n this.matrix = mat4.create();\n this.matrixInverse = mat4.create();\n this.device = device;",
"score": 0.7999034523963928
},
{
"filename": "src/render/camera.ts",
"retrieved_chunk": " mat4.ortho(\n matrix,\n position[0] - x, position[0] + x,\n position[1] - y, position[1] + y,\n near, far\n );\n mat4.invert(matrixInverse, matrix);\n device.queue.writeBuffer(buffer, 0, matrix as Float32Array);\n }\n}",
"score": 0.7975865006446838
},
{
"filename": "src/compute/generation/cloth.ts",
"retrieved_chunk": " points.forEach(({ position }) => {\n if (tension) position.x *= 1.25;\n position.y = (position.y - height * gap * 0.2) * 1.4;\n });\n }\n return {\n ...PointBuffers(points),\n joints: JointBuffer(joints),\n numJoints: joints.length,\n numPoints: points.length,",
"score": 0.7701719403266907
},
{
"filename": "src/render/camera.ts",
"retrieved_chunk": " this.buffer = device.createBuffer({\n size: (this.matrix as Float32Array).byteLength,\n usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM,\n });\n }\n getBuffer() {\n return this.buffer;\n }\n getMatrixInverse() {\n return this.matrixInverse;",
"score": 0.7675628662109375
},
{
"filename": "src/render/camera.ts",
"retrieved_chunk": " this.update();\n }\n private update() {\n const {\n device, buffer,\n matrix, matrixInverse,\n aspect, near, far, zoom, position,\n } = this;\n const x = zoom * aspect * 0.5;\n const y = zoom * 0.5;",
"score": 0.7620186805725098
}
] | typescript | camera.getMatrixInverse()
); |
import ConstrainSimulation from './constrain';
import ComputeLines from './lines';
import StepSimulation from './step';
import { LineBuffer, UniformsBuffer } from './types';
class Simulation {
private buffers?: {
data: GPUBuffer;
joints: GPUBuffer;
lines: GPUBuffer;
points: GPUBuffer[];
};
private count: number = 0;
private device: GPUDevice;
private initial?: {
joints: ArrayBuffer;
points: ArrayBuffer;
};
private pipelines?: {
constraint: ConstrainSimulation,
lines: ComputeLines,
step: StepSimulation,
};
private step: number = 0;
private readonly uniforms: UniformsBuffer;
constructor(device: GPUDevice) {
this.device = device;
this.uniforms = new UniformsBuffer(device);
}
compute(
command: GPUCommandEncoder,
delta: number,
pointer: { button: number; position: [number, number] | Float32Array; },
radius: number
) {
const { buffers, pipelines, step, uniforms } = this;
if (!buffers || !pipelines) {
return;
}
uniforms.delta = delta;
uniforms.button = pointer.button;
uniforms.pointer = pointer.position;
uniforms.radius = radius;
uniforms.update();
const pass = command.beginComputePass();
pipelines.step.compute(pass, step);
this.step = (this.step + 1) % 2;
| pipelines.constraint.compute(pass, this.step); |
pipelines.lines.compute(pass, this.step);
pass.end();
}
getBuffers() {
const { buffers, count, step } = this;
if (!buffers) {
throw new Error("Simulation is not loaded");
}
return {
count,
data: buffers.data,
lines: buffers.lines,
points: buffers.points[step],
};
}
load(
{ data, joints, numJoints, points, numPoints }: {
data: ArrayBuffer;
joints: ArrayBuffer;
numJoints: number;
points: ArrayBuffer;
numPoints: number;
}
) {
const { device } = this;
const createBuffer = (data: ArrayBuffer, usage: number) => {
const buffer = device.createBuffer({
mappedAtCreation: true,
size: data.byteLength,
usage,
});
new Uint32Array(buffer.getMappedRange()).set(new Uint32Array(data));
buffer.unmap();
return buffer;
};
if (this.buffers) {
this.buffers.data.destroy();
this.buffers.joints.destroy();
this.buffers.lines.destroy();
this.buffers.points.forEach((buffer) => buffer.destroy());
}
this.buffers = {
data: createBuffer(
data,
GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX
),
joints: createBuffer(
joints,
GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE
),
lines: LineBuffer(device, numJoints),
points: Array.from({ length: 2 }, () => createBuffer(
points,
GPUBufferUsage.COPY_DST
| GPUBufferUsage.STORAGE
| GPUBufferUsage.VERTEX
)),
};
this.count = numPoints;
this.initial = { joints, points };
this.pipelines = {
constraint: new ConstrainSimulation(
device,
this.buffers.data,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints
),
lines: new ComputeLines(
device,
this.buffers.joints,
numJoints,
this.buffers.lines,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
step: new StepSimulation(
device,
this.buffers.data,
this.buffers.points,
numPoints,
this.uniforms.getBuffer()
),
};
}
reset() {
const { buffers, device, initial } = this;
if (!buffers || !initial) {
return;
}
device.queue.writeBuffer(buffers.joints, 0, initial.joints);
buffers.points.forEach((buffer) => (
device.queue.writeBuffer(buffer, 0, initial.points)
));
}
}
export default Simulation;
| src/compute/simulation/index.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " let index: u32 = id.x;\n if (index >= ${numPoints}) {\n return;\n }\n var point = input[index];\n if (data[index].locked == 0) {\n point += point - output[index];\n point += vec2<f32>(0, -8) * uniforms.delta;\n if (uniforms.button != 2) {\n var d = point - uniforms.pointer;",
"score": 0.7837958335876465
},
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " }\n var joint = joints[index];\n if (joint.enabled == 0) {\n return;\n }\n if (uniforms.button == 2) {\n if (\n sdSegment(uniforms.pointer, points[joint.a], points[joint.b]) <= uniforms.radius * 0.25\n ) {\n joints[index].enabled = 0;",
"score": 0.7584888935089111
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " })),\n };\n }\n compute(pass: GPUComputePassEncoder, step: number) {\n const { bindings, pipeline } = this;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings.data);\n pass.setBindGroup(1, bindings.points[step]);\n pass.dispatchWorkgroups(1);\n }",
"score": 0.748868465423584
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " if (length(d) < min(uniforms.radius * 4, 24)) {\n point += d * uniforms.radius * uniforms.delta;\n }\n }\n }\n output[index] = point;\n}\n`;\nclass StepSimulation {\n private readonly bindings: {",
"score": 0.7465715408325195
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " this.simulation = simulation;\n this.generateDefaultTexture();\n }\n render(pass: GPURenderPassEncoder) {\n const { bindings, geometry, pipeline, simulation } = this;\n const { count, data, points } = simulation.getBuffers();\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindings);\n pass.setVertexBuffer(0, geometry);\n pass.setVertexBuffer(1, points);",
"score": 0.7409311532974243
}
] | typescript | pipelines.constraint.compute(pass, this.step); |
import Camera from './camera';
class Renderer {
private readonly animation: {
clock: number;
loop: (command: GPUCommandEncoder, delta: number, time: number) => void;
request: number;
};
private readonly camera: Camera;
private readonly canvas: HTMLCanvasElement;
private readonly context: GPUCanvasContext;
private readonly descriptor: GPURenderPassDescriptor;
private readonly device: GPUDevice;
private readonly format: GPUTextureFormat;
private readonly objects: { render: (pass: GPURenderPassEncoder) => void }[];
private readonly samples: number = 4;
private target: GPUTexture = undefined as unknown as GPUTexture;
constructor(camera: Camera, device: GPUDevice) {
this.camera = camera;
this.canvas = document.createElement('canvas');
const context = this.canvas.getContext('webgpu');
if (!context) {
throw new Error("Couldn't get GPUCanvasContext");
}
this.context = context;
this.format = navigator.gpu.getPreferredCanvasFormat();
this.context.configure({ alphaMode: 'opaque', device, format: this.format });
this.descriptor = {
colorAttachments: [
{
clearValue: { r: 0, g: 0, b: 0, a: 1 },
loadOp: 'clear',
storeOp: 'store',
view: undefined as unknown as GPUTextureView,
},
],
};
this.device = device;
this.objects = [];
this.animate = this.animate.bind(this);
this.animation = {
clock: performance.now() / 1000,
loop: () => {},
request: requestAnimationFrame(this.animate),
};
this.visibilitychange = this.visibilitychange.bind(this);
document.addEventListener('visibilitychange', this.visibilitychange);
}
add(object: { render: (pass: GPURenderPassEncoder) => void }) {
this.objects.push(object);
}
getCanvas() {
return this.canvas;
}
getFormat() {
return this.format;
}
getSamples() {
return this.samples;
}
setAnimationLoop(loop: (command: GPUCommandEncoder, delta: number, time: number) => void) {
this.animation.loop = loop;
}
setSize(width: number, height: number) {
const {
camera,
canvas,
descriptor: { colorAttachments: [color] },
device,
format,
samples,
target,
} = this;
const pixelRatio = window.devicePixelRatio || 1;
const size = [Math.floor(width * pixelRatio), Math.floor(height * pixelRatio)];
canvas.width = size[0];
canvas.height = size[1];
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
| camera.setAspect(width / height); |
if (target) {
target.destroy();
}
this.target = device.createTexture({
format,
sampleCount: samples,
size,
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
color!.view = this.target.createView();
}
private animate() {
const { animation, device } = this;
const time = performance.now() / 1000;
const delta = Math.min(time - animation.clock, 0.1);
animation.clock = time;
animation.request = requestAnimationFrame(this.animate);
const command = device.createCommandEncoder();
animation.loop(command, delta, time);
this.render(command);
device.queue.submit([command.finish()]);
}
private render(command: GPUCommandEncoder) {
const {
context,
descriptor,
objects,
} = this;
const { colorAttachments: [color] } = descriptor;
color!.resolveTarget = context.getCurrentTexture().createView();
const pass = command.beginRenderPass(descriptor);
objects.forEach((object) => object.render(pass));
pass.end();
}
private visibilitychange() {
const { animation } = this;
cancelAnimationFrame(animation.request);
if (document.visibilityState === 'visible') {
animation.clock = performance.now() / 1000;
animation.request = requestAnimationFrame(this.animate);
}
}
}
export default Renderer;
| src/render/renderer.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/render/points.ts",
"retrieved_chunk": " }\n let x = 0;\n let y = 0;\n let w = canvas.width = 512;\n let h = canvas.height = 512;\n if (image.width / image.height > w / h) {\n w = image.width * canvas.height / image.height;\n x = (canvas.width - w) * 0.5;\n } else {\n h = image.height * canvas.width / image.width;",
"score": 0.8452788591384888
},
{
"filename": "src/compute/input.ts",
"retrieved_chunk": " target.addEventListener('pointerup', this.onPointerUp.bind(this));\n {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = 20;\n canvas.height = 20;\n ctx.lineWidth = 5;",
"score": 0.821025550365448
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");\n }\n canvas.width = canvas.height = 512;\n for (let i = 0; i < 256; i++) {\n ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;\n ctx.beginPath();\n ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);",
"score": 0.7891647219657898
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " y = (canvas.height - h) * 0.5;\n }\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);\n this.updateTexture(canvas);\n });\n image.src = URL.createObjectURL(file);\n }\n private generateDefaultTexture() {",
"score": 0.7837512493133545
},
{
"filename": "src/compute/input.ts",
"retrieved_chunk": " ctx.strokeStyle = '#111';\n ctx.arc(canvas.width * 0.5, canvas.height * 0.5, 6, 0, Math.PI * 2);\n ctx.stroke();\n ctx.lineWidth = 3;\n ctx.strokeStyle = '#eee';\n ctx.stroke();\n canvas.toBlob((blob) => {\n if (blob) {\n document.body.style.cursor = `url(${URL.createObjectURL(blob)}) 10 10, default`;\n }",
"score": 0.7835503816604614
}
] | typescript | camera.setAspect(width / height); |
import './main.css';
import Camera from './render/camera';
import Input from './compute/input';
import Lines from './render/lines';
import Points from './render/points';
import Renderer from './render/renderer';
import Simulation from './compute/simulation';
import { Cloth, Ropes } from './compute/generation';
const Main = (device: GPUDevice) => {
const dom = document.getElementById('app');
if (!dom) {
throw new Error("Couldn't get app DOM node");
}
const camera = new Camera(device);
const renderer = new Renderer(camera, device);
const input = new Input(renderer.getCanvas());
const simulation = new Simulation(device);
dom.appendChild(renderer.getCanvas());
renderer.setAnimationLoop((command, delta) => (
simulation.compute(command, delta, input.getPointer(camera), camera.getZoom() * 0.02)
));
renderer.setSize(window.innerWidth, window.innerHeight);
simulation.load(Cloth());
const lines = new Lines(camera, device, renderer.getFormat(), renderer.getSamples(), simulation);
renderer.add(lines);
const points = new Points(camera, device, renderer.getFormat(), renderer.getSamples(), simulation);
renderer.add(points);
input.setHotkeys({
1: () => simulation.load(Cloth()),
2: () => simulation.load(Cloth(false, true)),
3: () => simulation.load(Ropes()),
4: () => simulation.load(Cloth(true, false)),
5: () => simulation.load(Cloth(true, true)),
escape: () => simulation.reset(),
'?': () => document.getElementById('help')?.classList.toggle('hidden'),
});
window.addEventListener('drop', (e) => {
e.preventDefault();
const [file] = e.dataTransfer?.files || [];
if (file && file.type.indexOf('image/') === 0) {
points | .setTexture(file); |
}
});
window.addEventListener('resize', () => (
renderer.setSize(window.innerWidth, window.innerHeight)
));
window.addEventListener('wheel', ({ deltaY }) => (
camera.setZoom(Math.min(Math.max(camera.getZoom() * (1 + deltaY * 0.001), 200), 400))
));
};
const GPU = async () => {
if (!navigator.gpu) {
throw new Error("Couldn't load WebGPU");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw new Error("Couldn't load WebGPU adapter");
}
const device = await adapter.requestDevice();
if (!device) {
throw new Error("Couldn't load WebGPU device");
}
return device;
};
const prevent = (e: DragEvent | MouseEvent | TouchEvent) => e.preventDefault();
window.addEventListener('contextmenu', prevent);
window.addEventListener('dragenter', prevent);
window.addEventListener('dragover', prevent);
window.addEventListener('touchstart', prevent);
GPU()
.then(Main)
.catch((e) => {
document.getElementById('error')!.innerText = e.message;
document.getElementById('support')!.classList.remove('hidden');
})
.finally(() => document.getElementById('loading')!.classList.add('hidden'));
| src/main.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/input.ts",
"retrieved_chunk": " && !repeat\n && !['input', 'textarea', 'select'].includes(\n (target as HTMLElement).tagName.toLowerCase()\n )\n ) {\n handler();\n }\n }\n private onPointerDown({ buttons, pointerId, target }: PointerEvent) {\n (target as HTMLCanvasElement).setPointerCapture(pointerId);",
"score": 0.7662733793258667
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " clock: performance.now() / 1000,\n loop: () => {},\n request: requestAnimationFrame(this.animate),\n };\n this.visibilitychange = this.visibilitychange.bind(this);\n document.addEventListener('visibilitychange', this.visibilitychange);\n }\n add(object: { render: (pass: GPURenderPassEncoder) => void }) {\n this.objects.push(object);\n }",
"score": 0.7352911829948425
},
{
"filename": "src/compute/input.ts",
"retrieved_chunk": " constructor(target: HTMLCanvasElement) {\n this.pointer = {\n id: -1,\n button: 0,\n normalized: vec2.fromValues(-1, -1),\n position: vec2.create(),\n };\n window.addEventListener('keydown', this.onKeyDown.bind(this));\n target.addEventListener('pointerdown', this.onPointerDown.bind(this));\n window.addEventListener('pointermove', this.onPointerMove.bind(this));",
"score": 0.7273581624031067
},
{
"filename": "src/render/points.ts",
"retrieved_chunk": " pass.setVertexBuffer(2, data);\n pass.draw(6, count, 0, 0);\n }\n setTexture(file: Blob) {\n const image = new Image();\n image.addEventListener('load', () => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n throw new Error(\"Couldn't get 2d context\");",
"score": 0.716158390045166
},
{
"filename": "src/render/renderer.ts",
"retrieved_chunk": " objects.forEach((object) => object.render(pass));\n pass.end();\n }\n private visibilitychange() {\n const { animation } = this;\n cancelAnimationFrame(animation.request);\n if (document.visibilityState === 'visible') {\n animation.clock = performance.now() / 1000;\n animation.request = requestAnimationFrame(this.animate);\n }",
"score": 0.7088639736175537
}
] | typescript | .setTexture(file); |
import Camera from './camera';
import { Plane } from './geometry';
import Simulation from '../compute/simulation';
const Vertex = /* wgsl */`
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) iposition: vec2<f32>,
@location(3) isize: f32,
@location(4) iuv: vec2<f32>,
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(0) var<uniform> camera: mat4x4<f32>;
@vertex
fn main(vertex: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.position = camera * vec4<f32>(vertex.position * vertex.isize + vertex.iposition, 0, 1);
out.size = vertex.isize;
out.uv = (vertex.uv - 0.5) * 2;
out.uv2 = vertex.iuv;
return out;
}
`;
const Fragment = /* wgsl */`
struct FragmentInput {
@location(0) size: f32,
@location(1) uv: vec2<f32>,
@location(2) uv2: vec2<f32>,
}
@group(0) @binding(1) var texture: texture_2d<f32>;
@group(0) @binding(2) var textureSampler: sampler;
fn linearTosRGB(linear: vec3<f32>) -> vec3<f32> {
if (all(linear <= vec3<f32>(0.0031308))) {
return linear * 12.92;
}
return (pow(abs(linear), vec3<f32>(1.0/2.4)) * 1.055) - vec3<f32>(0.055);
}
@fragment
fn main(fragment: FragmentInput) -> @location(0) vec4<f32> {
let l = min(length(fragment.uv), 1);
var uv = fragment.uv2 + (fragment.uv / fragment.size / 33);
return vec4<f32>(linearTosRGB(
textureSample(texture, textureSampler, uv).xyz + smoothstep(0.5, 1, l) * 0.1
), smoothstep(1, 0.8, l));
}
`;
class Points {
private readonly bindings: GPUBindGroup;
private readonly device: GPUDevice;
private readonly geometry: GPUBuffer;
private readonly pipeline: GPURenderPipeline;
private readonly simulation: Simulation;
private readonly texture: GPUTexture;
constructor(
camera: Camera,
device: GPUDevice,
format: GPUTextureFormat,
samples: number,
simulation: Simulation,
) {
this.device = device;
this.geometry = Plane(device, 2, 2);
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2',
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
{
arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 2,
offset: 0,
format: 'float32x2',
},
],
},
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
stepMode: 'instance',
attributes: [
{
shaderLocation: 3,
offset: 1 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32',
},
{
shaderLocation: 4,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: 'float32x2',
},
],
},
],
entryPoint: 'main',
module: device.createShaderModule({
code: Vertex,
}),
},
fragment: {
entryPoint: 'main',
module: device.createShaderModule({
code: Fragment,
}),
targets: [{
format,
blend: {
color: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
alpha: {
srcFactor: 'src-alpha',
dstFactor: 'one-minus-src-alpha',
operation: 'add',
},
},
}],
},
primitive: {
topology: 'triangle-list',
},
multisample: {
count: samples,
},
});
this.texture = device.createTexture({
dimension: '2d',
format: 'rgba8unorm-srgb',
size: [512, 512],
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
});
this.bindings = device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
| resource: { buffer: camera.getBuffer() },
},
{ |
binding: 1,
resource: this.texture.createView(),
},
{
binding: 2,
resource: device.createSampler({ minFilter: 'linear', magFilter: 'linear' }),
},
],
});
this.simulation = simulation;
this.generateDefaultTexture();
}
render(pass: GPURenderPassEncoder) {
const { bindings, geometry, pipeline, simulation } = this;
const { count, data, points } = simulation.getBuffers();
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindings);
pass.setVertexBuffer(0, geometry);
pass.setVertexBuffer(1, points);
pass.setVertexBuffer(2, data);
pass.draw(6, count, 0, 0);
}
setTexture(file: Blob) {
const image = new Image();
image.addEventListener('load', () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
let x = 0;
let y = 0;
let w = canvas.width = 512;
let h = canvas.height = 512;
if (image.width / image.height > w / h) {
w = image.width * canvas.height / image.height;
x = (canvas.width - w) * 0.5;
} else {
h = image.height * canvas.width / image.width;
y = (canvas.height - h) * 0.5;
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(image, 0, 0, image.width, image.height, x, y, w, h);
this.updateTexture(canvas);
});
image.src = URL.createObjectURL(file);
}
private generateDefaultTexture() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error("Couldn't get 2d context");
}
canvas.width = canvas.height = 512;
for (let i = 0; i < 256; i++) {
ctx.fillStyle = `hsl(${360 * Math.random()},${20 + 40 * Math.random()}%,${20 + 40 * Math.random()}%)`;
ctx.beginPath();
ctx.arc(canvas.width * Math.random(), canvas.height * Math.random(), 16 + Math.random() * 64, 0, Math.PI * 2);
ctx.fill();
}
this.updateTexture(canvas);
}
private async updateTexture(canvas: HTMLCanvasElement) {
const { device, texture } = this;
const source = await createImageBitmap(canvas)
device.queue.copyExternalImageToTexture({ source, flipY: true }, { texture }, [512, 512]);
}
}
export default Points;
| src/render/points.ts | danielesteban-gpucloth-b0d861b | [
{
"filename": "src/compute/simulation/lines.ts",
"retrieved_chunk": " },\n {\n binding: 2,\n resource: { buffer: uniforms },\n },\n ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [",
"score": 0.8846657872200012
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " binding: 1,\n resource: { buffer: uniforms },\n },\n ],\n }),\n points: points.map((buffer, i) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,",
"score": 0.8834854364395142
},
{
"filename": "src/compute/simulation/step.ts",
"retrieved_chunk": " });\n this.bindings = {\n data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,\n resource: { buffer: data },\n },\n {",
"score": 0.8699625730514526
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " ],\n }),\n points: points.map((buffer) => device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(1),\n entries: [\n {\n binding: 0,\n resource: { buffer },\n },\n ],",
"score": 0.8698488473892212
},
{
"filename": "src/compute/simulation/constrain.ts",
"retrieved_chunk": " code: Compute(4, numPoints, numJoints),\n }),\n },\n });\n this.bindings = {\n data: device.createBindGroup({\n layout: this.pipeline.getBindGroupLayout(0),\n entries: [\n {\n binding: 0,",
"score": 0.8604446649551392
}
] | typescript | resource: { buffer: camera.getBuffer() },
},
{ |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser | : NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 0.8475828170776367
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 0.83165043592453
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.7923897504806519
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 0.7833296060562134
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " PluginsCustomCMS: NotionCMS,\n PluginsCustomFallbackCMS: NotionCMS\n// Helper Function for parsing internal block rich text\n// eslint-disable-next-line jest/unbound-method\nconst parseRichText = NotionBlocksParser.parseRichText\n// temporarily ignore md and plaintext versions of content\nfunction filterContent(content: Content) {\n delete content.plaintext\n delete content.markdown\n return content",
"score": 0.7793026566505432
}
] | typescript | : NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
| htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 0.8417262434959412
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 0.8323959112167358
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.801261305809021
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 0.7961335182189941
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " blocksRenderPlugin({\n blockRenderers: {\n CalloutBlock: (block: Block) => null, // Nulls should invoke default renderer\n QuoteBlock: (block: Block) => null, // Nulls should invoke default renderer\n },\n })],\n })\n console.log('custom render test: purging cache')\n PluginsCustomFallbackCMS.purgeCache()\n await PluginsCustomFallbackCMS.fetch()",
"score": 0.7915480732917786
}
] | typescript | htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import fs from 'node:fs'
import { Buffer } from 'node:buffer'
import { fileTypeFromBuffer } from 'file-type'
import { nanoid } from 'nanoid'
import sharp from 'sharp'
import type { Content, PageContent, PluginExecOptions } from '../types'
interface ImageCacheEntry {
filename?: string
location?: string
url?: string
}
interface ImageCache { [key: string]: Array<ImageCacheEntry> }
const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g
const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json'
const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig
const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig
function multiStringMatch(stringA: unknown, stringB: unknown): Boolean {
if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB)
return false
const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX)
const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX)
return Boolean(matchA && matchB && (matchA[0] === matchB[0]))
}
export default function ({
globalExtension = 'webp',
compression = 80,
imageCacheDirectory = './public',
customMatchers = [],
}: {
globalExtension?: 'webp' | 'png' | 'jpeg'
compression?: number
imageCacheDirectory?: string
customMatchers?: RegExp[]
} = {}) {
let imageCache: ImageCache
try {
// Pull existing imageCache
if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) {
imageCache = JSON.parse(
fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache
}
else {
imageCache = {}
}
}
catch (e) {
console.warn(e, 'ncms-plugin-images: error attempting to read image cache.')
imageCache = {}
}
async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> {
let filename = ''
if (existingImageFile)
return existingImageFile.filename as string
const response = await fetch(imageUrl)
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const fileType = await fileTypeFromBuffer(buffer)
if (fileType?.ext) {
const id = nanoid(6)
filename = `${id}.remote.${globalExtension}`
const outputFilePath = `${imageCacheDirectory}/remote/${filename}`
const imageBuffer = sharp(buffer)
const webPBuffer = await imageBuffer[globalExtension]({
quality: compression,
nearLossless: true,
effort: 6,
}).toBuffer()
const writeStream = fs.createWriteStream(outputFilePath)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`))
writeStream.write(webPBuffer)
}
return filename
}
function detectExisting(path: string, imageUrl: string): ImageCacheEntry {
const entries = imageCache[path]
return entries.filter((entry) => {
return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl)
})[0]
}
async function processImage(
path: string,
imageUrl: string,
updator: { update: Content | string },
debug?: boolean): Promise<void> {
if (imageUrl && path) {
let filename = ''
try {
filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl))
}
catch (e) {
if (debug)
console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!')
return
}
if (filename) {
imageCache[path].push({
filename,
location: `/remote/${filename}`,
url: imageUrl,
})
// if we don't do this, the replaceall cant find the proper url below
if (typeof updator.update !== 'string') {
if (updator.update?.html.includes('amazonaws'))
updator.update.html = updator.update.html.replaceAll('&', '&')
updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`)
}
else {
// This replaces the coverImage
updator.update = updator.update.replace(imageUrl, `/remote/${filename}`)
}
if (debug)
console.log('ncms-plugin-images: rewriting', path, 'at', filename)
}
}
}
return {
name: 'ncms-plugin-images',
hook: 'during-tree',
core: true,
exec | : async (context: PageContent, options: PluginExecOptions) => { |
const copyOfContext = structuredClone(context)
if (!copyOfContext.path)
return
const matchables = [
GENERIC_MATCH,
IMAGE_SOURCE_MATCH,
...customMatchers,
]
if (!imageCache[copyOfContext.path])
imageCache[copyOfContext.path] = [] as ImageCacheEntry[]
const contents = {
update: copyOfContext.content as Content,
}
const coverImage = {
update: copyOfContext.coverImage as string,
}
// Must run all async in series so that we don't end up with duplicates
for (const match of matchables) {
if (!copyOfContext.path)
return
const path = copyOfContext.path
const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || []
const matchedCoverImages = (coverImage.update && [coverImage.update]) || []
for (const imageUrl of matched)
await processImage(path, imageUrl, contents, options.debug)
for (const imageUrl of matchedCoverImages)
await processImage(path, imageUrl, coverImage, options.debug)
}
copyOfContext.content = contents.update
copyOfContext.coverImage = coverImage.update
try {
if (!fs.existsSync(`${imageCacheDirectory}/remote`))
fs.mkdirSync(`${imageCacheDirectory}/remote`)
fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache))
if (options.debug)
fs.writeFileSync('debug/images.json', JSON.stringify(imageCache))
}
catch (e) {
if (options.debug)
console.warn(e, 'ncms-plugin-images: error writing to image cache.')
}
return copyOfContext
},
}
}
| src/plugins/images.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/head.ts",
"retrieved_chunk": "import type { PageContent } from '../types'\nexport default function () {\n return {\n name: 'ncms-plugin-head',\n hook: 'during-tree',\n core: true,\n exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context) as PageContentWithMeta\n copyOfContext.meta = {\n title: '',",
"score": 0.8478097915649414
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.8296145796775818
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " PluginsCustomCMS = new NotionCMS({\n // Kitchen sink DB in community/tests\n databaseId,\n notionAPIKey,\n // Should work with other plugin too\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n }),",
"score": 0.8124059438705444
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " databaseId: '610627a9-28b1-4477-b660-c00c5364435b',\n notionAPIKey,\n draftMode: true,\n // Standin Plugin - use default renderer plugin behind the scenes\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n })],\n })",
"score": 0.8094480037689209
},
{
"filename": "src/tests/notion-cms-caching.spec.ts",
"retrieved_chunk": " hook: '*', // this will run every hook\n exec: (ctx: PluginPassthrough) => {\n counter++\n return ctx\n },\n },\n ],\n })\n console.log('caching test: purging cache')\n testCMS.purgeCache()",
"score": 0.7934408187866211
}
] | typescript | : async (context: PageContent, options: PluginExecOptions) => { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
| plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 0.8417262434959412
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 0.8323959112167358
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.801261305809021
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 0.7961335182189941
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " blocksRenderPlugin({\n blockRenderers: {\n CalloutBlock: (block: Block) => null, // Nulls should invoke default renderer\n QuoteBlock: (block: Block) => null, // Nulls should invoke default renderer\n },\n })],\n })\n console.log('custom render test: purging cache')\n PluginsCustomFallbackCMS.purgeCache()\n await PluginsCustomFallbackCMS.fetch()",
"score": 0.7915480732917786
}
] | typescript | plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: | NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": "import type { Blocks } from '@notion-stuff/v4-types'\nimport _ from 'lodash'\nimport type { BlockRenderers } from '../notion-blocks-parser'\nimport NotionBlocksParser from '../notion-blocks-parser'\nimport type { PluginPassthrough, UnsafePlugin } from '../types'\nexport default function ({\n blockRenderers,\n debug,\n}: { blockRenderers: BlockRenderers; debug?: boolean }) {\n const parser = new NotionBlocksParser({ blockRenderers, debug })",
"score": 0.8485740423202515
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 0.8342451453208923
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.7989934682846069
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 0.7933889627456665
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " blocksRenderPlugin({\n blockRenderers: {\n CalloutBlock: (block: Block) => null, // Nulls should invoke default renderer\n QuoteBlock: (block: Block) => null, // Nulls should invoke default renderer\n },\n })],\n })\n console.log('custom render test: purging cache')\n PluginsCustomFallbackCMS.purgeCache()\n await PluginsCustomFallbackCMS.fetch()",
"score": 0.7878738641738892
}
] | typescript | NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser | = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 0.8234132528305054
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " PluginsCustomCMS: NotionCMS,\n PluginsCustomFallbackCMS: NotionCMS\n// Helper Function for parsing internal block rich text\n// eslint-disable-next-line jest/unbound-method\nconst parseRichText = NotionBlocksParser.parseRichText\n// temporarily ignore md and plaintext versions of content\nfunction filterContent(content: Content) {\n delete content.plaintext\n delete content.markdown\n return content",
"score": 0.8206726312637329
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 0.818486213684082
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.8135205507278442
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " blocksRenderPlugin({\n blockRenderers: {\n CalloutBlock: (block: Block) => null, // Nulls should invoke default renderer\n QuoteBlock: (block: Block) => null, // Nulls should invoke default renderer\n },\n })],\n })\n console.log('custom render test: purging cache')\n PluginsCustomFallbackCMS.purgeCache()\n await PluginsCustomFallbackCMS.fetch()",
"score": 0.792106032371521
}
] | typescript | = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
import dotenv from 'dotenv'
import { suite } from 'uvu'
import * as assert from 'uvu/assert'
import nock from 'nock'
import NotionCMS from '../index'
import type { CMS, PluginPassthrough } from '../types'
dotenv.config()
export const TestNotionCMSCache = suite('TestNotionCMSCache')
const cachingDatabaseId = '1234' // this does not exist in notion
const baseUrl = 'https://api.notion.com/v1'
const cachingTestCMS: NotionCMS = new NotionCMS({
databaseId: cachingDatabaseId,
notionAPIKey: process.env.NOTION as string,
draftMode: true,
})
cachingTestCMS.purgeCache()
const topLevelPageId = '456'
const topLevelPageId2 = '789'
TestNotionCMSCache('Unchanged since last edit time uses cache', async () => {
nock(baseUrl)
.post(`/databases/${cachingDatabaseId}/query`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'page',
id: topLevelPageId,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:03:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 1',
link: null,
},
annotations: {},
plain_text: 'Page 1',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
{
object: 'page',
id: topLevelPageId2,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:03:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 2',
link: null,
},
annotations: {},
plain_text: 'Page 2',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
],
next_cursor: null,
has_more: false,
type: 'page',
page: {},
})
nock(baseUrl)
.get(`/blocks/${topLevelPageId}/children`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'block',
id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad',
parent: {
type: 'page_id',
page_id: topLevelPageId,
},
created_time: '2023-04-22T04:34:00.000Z',
last_edited_time: '2023-04-22T04:34:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
has_children: false,
archived: false,
type: 'heading_1',
heading_1: {
rich_text: [
{
type: 'text',
text: {
content: 'Block 1: Has not changed.',
link: null,
},
annotations: {},
plain_text: 'Block 1: Has not changed.',
href: null,
},
],
is_toggleable: false,
color: 'default',
},
},
],
})
nock(baseUrl)
.get(`/blocks/${topLevelPageId2}/children`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'block',
id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad',
parent: {
type: 'page_id',
page_id: topLevelPageId2,
},
created_time: '2023-04-22T04:34:00.000Z',
last_edited_time: '2023-04-22T04:34:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
has_children: false,
archived: false,
type: 'heading_1',
heading_1: {
rich_text: [
{
type: 'text',
text: {
content: 'Block 2: Has not changed.',
link: null,
},
annotations: {},
plain_text: 'Block 2: Has not changed.',
href: null,
},
],
is_toggleable: false,
color: 'default',
},
},
],
})
// Build the cache
const cms: CMS = await cachingTestCMS.pull()
assert.ok(cms.siteData['/page-1'].content?.plaintext === 'Block 1: Has not changed.')
assert.ok(cms.siteData['/page-2'].content?.plaintext === 'Block 2: Has not changed.')
// Change some data in only page 2
nock(baseUrl)
.post(`/databases/${cachingDatabaseId}/query`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'page',
id: topLevelPageId,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:03:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 1',
link: null,
},
annotations: {},
plain_text: 'Page 1',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
{
object: 'page',
id: topLevelPageId2,
created_time: '2023-04-09T06:03:00.000Z',
last_edited_time: '2023-04-09T06:16:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
properties: {
name: {
id: 'title',
type: 'title',
title: [
{
type: 'text',
text: {
content: 'Page 2',
link: null,
},
annotations: {},
plain_text: 'Page 2',
href: null,
},
],
},
Author: {
id: 'SQeZ',
type: 'people',
people: [
{
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
name: 'Jacob',
avatar_url: null,
type: 'person',
person: {
email: '[email protected]',
},
},
],
},
Tags: {
id: 'NNmP',
type: 'multi_select',
multi_select: [
{
id: '098acfda-2fb1-4ecf-8737-c03b80b5cb18',
name: 'programming',
color: 'default',
},
],
},
},
cover: null,
icon: null,
archived: false,
url: 'https://www.notion.so/Product-B-7fc90a1dca4d49ad91b5136c3d5a304d',
},
],
next_cursor: null,
has_more: false,
type: 'page',
page: {},
})
nock(baseUrl)
.get(`/blocks/${topLevelPageId2}/children`)
.query(true)
.reply(200, {
object: 'list',
results: [
{
object: 'block',
id: '1c92a5ea-dfeb-4c8f-b662-cde078bb02ad',
parent: {
type: 'page_id',
page_id: topLevelPageId2,
},
created_time: '2023-04-22T04:34:00.000Z',
last_edited_time: '2023-04-22T04:34:00.000Z',
created_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
last_edited_by: {
object: 'user',
id: '4e38fa57-609c-4beb-8e28-271b11cc81a3',
},
has_children: false,
archived: false,
type: 'heading_1',
heading_1: {
rich_text: [
{
type: 'text',
text: {
content: 'Block 2: Has changed.',
link: null,
},
annotations: {},
plain_text: 'Block 2: Has changed.',
href: null,
},
],
is_toggleable: false,
color: 'default',
},
},
],
})
const cms2: CMS = await cachingTestCMS.pull()
assert.ok(cms2.siteData['/page-1'].content?.plaintext === 'Block 1: Has not changed.')
assert.ok(cms2.siteData['/page-2'].content?.plaintext === 'Block 2: Has changed.')
})
TestNotionCMSCache('Plugins run even when using cached state.', async () => {
const databaseId = '610627a9-28b1-4477-b660-c00c5364435b'
let counter = 0
const testCMS: NotionCMS = new NotionCMS({
databaseId,
notionAPIKey: process.env.NOTION as string,
draftMode: true,
refreshTimeout: '1 minute',
plugins: [
{
name: 'counter-plugin',
hook: '*', // this will run every hook
| exec: (ctx: PluginPassthrough) => { |
counter++
return ctx
},
},
],
})
console.log('caching test: purging cache')
testCMS.purgeCache()
await testCMS.pull()
assert.equal(counter, 22)
})
| src/tests/notion-cms-caching.spec.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " PluginsCustomCMS = new NotionCMS({\n // Kitchen sink DB in community/tests\n databaseId,\n notionAPIKey,\n // Should work with other plugin too\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n }),",
"score": 0.9252074360847473
},
{
"filename": "src/tests/notion-cms.spec.ts",
"retrieved_chunk": " }\n})\nTestNotionCMS('Options have changed', () => {\n const options = {\n databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: true,\n plugins: [() => 'test plugin'],\n }\n const otherOptions = {",
"score": 0.8937015533447266
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": "})\nexport const PluginsCustomFallback = suite('PluginsCustomFallback')\nPluginsCustomFallback.before(async () => {\n PluginsCustomFallbackCMS = new NotionCMS({\n databaseId,\n notionAPIKey,\n draftMode: true,\n // Should work with other plugin too\n plugins: [\n // use custom renderer plugin behind the scenes",
"score": 0.8853552341461182
},
{
"filename": "src/tests/notion-cms.spec.ts",
"retrieved_chunk": " databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: true,\n plugins: [() => 'test plugin'],\n }\n const newOptions = {\n databaseId,\n notionAPIKey: process.env.NOTION,\n draftMode: false,\n }",
"score": 0.8824493885040283
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " options: Options\n private timer: number\n private coreRenderer: UnsafePlugin\n private logger: NotionLogger\n pull: () => Promise<CMS>\n rootAlias: string\n withinRefreshTimeout: boolean\n quietMode: boolean\n constructor({\n databaseId,",
"score": 0.8667699098587036
}
] | typescript | exec: (ctx: PluginPassthrough) => { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
| this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
return this.mdParser.parse(blocks, depth)
}
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " renderer: MarkedRenderer\n markedOptions\n debug: boolean\n constructor(parser: NotionBlocksMarkdownParser, debug?: boolean) {\n this.markdownParser = parser\n this.debug = debug || false\n this.renderer = new marked.Renderer()\n this.renderer.code = this._highlight.bind(this)\n this.markedOptions = {\n renderer: this.renderer,",
"score": 0.8253382444381714
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " PluginsCustomCMS: NotionCMS,\n PluginsCustomFallbackCMS: NotionCMS\n// Helper Function for parsing internal block rich text\n// eslint-disable-next-line jest/unbound-method\nconst parseRichText = NotionBlocksParser.parseRichText\n// temporarily ignore md and plaintext versions of content\nfunction filterContent(content: Content) {\n delete content.plaintext\n delete content.markdown\n return content",
"score": 0.8175759315490723
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 0.8164618611335754
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.8120452165603638
},
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": " const content = this.annotate(richText.annotations, richText.text.content)\n return richText.text.link\n ? this.annotateLink(richText.text, content)\n : content\n }\n // TODO: support mention when we know what it actually means\n parseMention(mention: RichTextMention): string {\n switch (mention.mention.type) {\n case 'user':\n break",
"score": 0.7871835827827454
}
] | typescript | this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
} |
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CompleteCardContext,
} from "~/types";
import { parse } from "yaml";
import {
getAbstractDateFromMetadata,
getBodyFromContextOrDocument,
getImageUrlFromContextOrDocument,
getTagsFromMetadataOrTagObject,
} from "./cardDataExtraction";
/**
* A un-changeable key used to check if a note is eligeable for render.
*/
const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"];
/**
* Provides additional context for the creation cards in the DOM.
*
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteMetadata(
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
) {
const { cachedMetadata, settings } = context;
const { frontmatter: metaData, tags } = cachedMetadata;
if (!metaData) return undefined;
if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))
return undefined;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
metaData,
tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;
return {
cardData: await extractCardData(context),
context,
} as const;
}
/**
* Provides additional context for the creation cards in the DOM but reads it from the body
*
* @param body - The extracted body for a single event card.
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteBody(
body: string | undefined | null,
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
): Promise<CompleteCardContext[]> {
const { settings } = context;
if (!body) return [];
const inlineEventBlockRegExp = new RegExp(
`%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`,
"gi"
);
const originalFrontmatter = context.cachedMetadata.frontmatter;
const matches = body.match(inlineEventBlockRegExp);
if (!matches) return [];
matches.unshift();
const output: CompleteCardContext[] = [];
for (const block of matches) {
const sanitizedBlock = block.split("\n");
sanitizedBlock.shift();
sanitizedBlock.pop();
const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao
// Replace frontmatter with newly built fake one. Just to re-use all the existing code.
context.cachedMetadata.frontmatter = fakeFrontmatter;
if (! | isDefinedAsObject(fakeFrontmatter)) continue; |
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
fakeFrontmatter,
context.cachedMetadata.tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;
const matchPositionInBody = body.indexOf(block);
output.push({
cardData: await extractCardData(
context,
matchPositionInBody !== -1
? body.slice(matchPositionInBody + block.length)
: undefined
),
context,
});
}
context.cachedMetadata.frontmatter = originalFrontmatter;
return output;
}
/**
* Checks if the extracted tags match at least one of the tags to find.
*
* @param timelineTags - The extracted tags from the note.
* @param tagsToFind - The tags to find.
* @returns `true` if valid.
*/
function extractedTagsAreValid(
timelineTags: string[],
tagsToFind: string[]
): boolean {
return timelineTags.some((tag) => tagsToFind.includes(tag));
}
/**
* Get the content of a card from a note. This function will parse the raw text content of a note and format it.
*
* @param context - Timeline generic context.
* @param rawFileContent - If you already have it, will avoid reading the file again.
* @returns The extracted data to create a card from a note.
*/
export async function extractCardData(
context: MarkdownCodeBlockTimelineProcessingContext,
rawFileContent?: string
) {
const { file, cachedMetadata: c, settings } = context;
const fileTitle =
c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename;
rawFileContent = rawFileContent || (await file.vault.cachedRead(file));
return {
title: fileTitle as string,
body: getBodyFromContextOrDocument(rawFileContent, context),
imageURL: getImageUrlFromContextOrDocument(rawFileContent, context),
startDate: getAbstractDateFromMetadata(
context,
settings.metadataKeyEventStartDate
),
endDate:
getAbstractDateFromMetadata(
context,
settings.metadataKeyEventEndDate
) ??
(isDefined(
getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean")
)
? true
: undefined),
} as const;
}
export type FnExtractCardData = typeof extractCardData;
| src/cardData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 0.7381693720817566
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t\tsettings: { metadataKeyEventBodyOverride },\n\t} = context;\n\tconst overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;\n\tif (!rawFileText.length || overrideBody) return overrideBody;\n\tconst rawTextArray = rawFileText.split(\"\\n\");\n\trawTextArray.shift();\n\tconst processedArray = rawTextArray.slice(rawTextArray.indexOf(\"---\") + 1);\n\tconst finalString = processedArray.join(\"\\n\").trim();\n\treturn finalString;\n}",
"score": 0.7179101705551147
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (",
"score": 0.7065715789794922
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 0.6806941032409668
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.",
"score": 0.6636700630187988
}
] | typescript | isDefinedAsObject(fakeFrontmatter)) continue; |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
| await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 0.7876020669937134
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 0.7685926556587219
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,",
"score": 0.7654014825820923
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 0.7475998997688293
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t\tsettings: { metadataKeyEventBodyOverride },\n\t} = context;\n\tconst overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;\n\tif (!rawFileText.length || overrideBody) return overrideBody;\n\tconst rawTextArray = rawFileText.split(\"\\n\");\n\trawTextArray.shift();\n\tconst processedArray = rawTextArray.slice(rawTextArray.indexOf(\"---\") + 1);\n\tconst finalString = processedArray.join(\"\\n\").trim();\n\treturn finalString;\n}",
"score": 0.731745719909668
}
] | typescript | await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
import fs from 'node:fs'
import { Buffer } from 'node:buffer'
import { fileTypeFromBuffer } from 'file-type'
import { nanoid } from 'nanoid'
import sharp from 'sharp'
import type { Content, PageContent, PluginExecOptions } from '../types'
interface ImageCacheEntry {
filename?: string
location?: string
url?: string
}
interface ImageCache { [key: string]: Array<ImageCacheEntry> }
const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g
const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json'
const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig
const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig
function multiStringMatch(stringA: unknown, stringB: unknown): Boolean {
if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB)
return false
const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX)
const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX)
return Boolean(matchA && matchB && (matchA[0] === matchB[0]))
}
export default function ({
globalExtension = 'webp',
compression = 80,
imageCacheDirectory = './public',
customMatchers = [],
}: {
globalExtension?: 'webp' | 'png' | 'jpeg'
compression?: number
imageCacheDirectory?: string
customMatchers?: RegExp[]
} = {}) {
let imageCache: ImageCache
try {
// Pull existing imageCache
if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) {
imageCache = JSON.parse(
fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache
}
else {
imageCache = {}
}
}
catch (e) {
console.warn(e, 'ncms-plugin-images: error attempting to read image cache.')
imageCache = {}
}
async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> {
let filename = ''
if (existingImageFile)
return existingImageFile.filename as string
const response = await fetch(imageUrl)
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const fileType = await fileTypeFromBuffer(buffer)
if (fileType?.ext) {
const id = nanoid(6)
filename = `${id}.remote.${globalExtension}`
const outputFilePath = `${imageCacheDirectory}/remote/${filename}`
const imageBuffer = sharp(buffer)
const webPBuffer = await imageBuffer[globalExtension]({
quality: compression,
nearLossless: true,
effort: 6,
}).toBuffer()
const writeStream = fs.createWriteStream(outputFilePath)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`))
writeStream.write(webPBuffer)
}
return filename
}
function detectExisting(path: string, imageUrl: string): ImageCacheEntry {
const entries = imageCache[path]
return entries.filter((entry) => {
return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl)
})[0]
}
async function processImage(
path: string,
imageUrl: string,
| updator: { update: Content | string },
debug?: boolean): Promise<void> { |
if (imageUrl && path) {
let filename = ''
try {
filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl))
}
catch (e) {
if (debug)
console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!')
return
}
if (filename) {
imageCache[path].push({
filename,
location: `/remote/${filename}`,
url: imageUrl,
})
// if we don't do this, the replaceall cant find the proper url below
if (typeof updator.update !== 'string') {
if (updator.update?.html.includes('amazonaws'))
updator.update.html = updator.update.html.replaceAll('&', '&')
updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`)
}
else {
// This replaces the coverImage
updator.update = updator.update.replace(imageUrl, `/remote/${filename}`)
}
if (debug)
console.log('ncms-plugin-images: rewriting', path, 'at', filename)
}
}
}
return {
name: 'ncms-plugin-images',
hook: 'during-tree',
core: true,
exec: async (context: PageContent, options: PluginExecOptions) => {
const copyOfContext = structuredClone(context)
if (!copyOfContext.path)
return
const matchables = [
GENERIC_MATCH,
IMAGE_SOURCE_MATCH,
...customMatchers,
]
if (!imageCache[copyOfContext.path])
imageCache[copyOfContext.path] = [] as ImageCacheEntry[]
const contents = {
update: copyOfContext.content as Content,
}
const coverImage = {
update: copyOfContext.coverImage as string,
}
// Must run all async in series so that we don't end up with duplicates
for (const match of matchables) {
if (!copyOfContext.path)
return
const path = copyOfContext.path
const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || []
const matchedCoverImages = (coverImage.update && [coverImage.update]) || []
for (const imageUrl of matched)
await processImage(path, imageUrl, contents, options.debug)
for (const imageUrl of matchedCoverImages)
await processImage(path, imageUrl, coverImage, options.debug)
}
copyOfContext.content = contents.update
copyOfContext.coverImage = coverImage.update
try {
if (!fs.existsSync(`${imageCacheDirectory}/remote`))
fs.mkdirSync(`${imageCacheDirectory}/remote`)
fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache))
if (options.debug)
fs.writeFileSync('debug/images.json', JSON.stringify(imageCache))
}
catch (e) {
if (options.debug)
console.warn(e, 'ncms-plugin-images: error writing to image cache.')
}
return copyOfContext
},
}
}
| src/plugins/images.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": " const id = uuidToId(link.page_id)\n // These will get replaced if ncms-plugin-linker is used.\n return `<a href=\"/${id}\">/${id}</a>`\n }\n parseFile(file: ExternalFileWithCaption | FileWithCaption): {\n caption: string\n url: string\n } {\n const fileContent = {\n caption: '',",
"score": 0.8292385339736938
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " }\n return access\n }\n queryByPath(path: string): Page {\n return this._queryByPath(path, this.cms.siteData)\n }\n export({ pretty = false, path = this.localCacheUrl }:\n { pretty?: boolean; path?: string } = {}) {\n this.cms.lastUpdateTimestamp = Date.now()\n if (pretty) {",
"score": 0.8260346055030823
},
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": " fileContent.caption = file.caption\n ? this.parseRichTexts(file.caption)\n : fileContent.url\n return fileContent\n }\n private annotate(annotations: Annotations, originalContent: string): string {\n // @ts-expect-error reduce\n return Object.entries(annotations).reduce(\n // @ts-expect-error reduce\n (",
"score": 0.8244066834449768
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " filters: [(node: WalkNode) => NotionCMS._isPageContentObject(node)],\n callback: (node: WalkNode) => cb(node.val) as unknown,\n })\n .withRootObjectCallbacks(false)\n .walk(startPoint)\n }\n getTaggedCollection(tags: string | Array<string>): Array<Page | undefined> {\n if (!_.isArray(tags))\n tags = [tags]\n const taggedPages = [] as Array<string>",
"score": 0.8144522905349731
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " }\n }\n async _getPageContent(state: CMS, cachedState?: CMS): Promise<CMS> {\n let stateWithContent = _.cloneDeep(state)\n await new AsyncWalkBuilder()\n .withCallback({\n filters: [(node: WalkNode) => NotionCMS._isPageContentObject(node)],\n nodeTypeFilters: ['object'],\n positionFilter: 'postWalk',\n callback: async (node: WalkNode) => {",
"score": 0.8104978203773499
}
] | typescript | updator: { update: Content | string },
debug?: boolean): Promise<void> { |
import fs from 'node:fs'
import { Buffer } from 'node:buffer'
import { fileTypeFromBuffer } from 'file-type'
import { nanoid } from 'nanoid'
import sharp from 'sharp'
import type { Content, PageContent, PluginExecOptions } from '../types'
interface ImageCacheEntry {
filename?: string
location?: string
url?: string
}
interface ImageCache { [key: string]: Array<ImageCacheEntry> }
const IMAGE_FILE_MATCH_REGEX = /(.*)X-Amz-Algorithm/g
const IMAGE_CACHE_FILENAME = 'ncms-image-cache.json'
const GENERIC_MATCH = /\b(https?:\/\/[\w_#&?.\/-]*?\.(?:png|jpe?g|svg|ico))(?=[`'")\]])/ig
const IMAGE_SOURCE_MATCH = /<img[^>]*src=['|"](https?:\/\/[^'|"]+)(?:['|"])/ig
function multiStringMatch(stringA: unknown, stringB: unknown): Boolean {
if (typeof stringA !== 'string' || typeof stringB !== 'string' || !stringA || !stringB)
return false
const matchA = stringA.match(IMAGE_FILE_MATCH_REGEX)
const matchB = stringB.match(IMAGE_FILE_MATCH_REGEX)
return Boolean(matchA && matchB && (matchA[0] === matchB[0]))
}
export default function ({
globalExtension = 'webp',
compression = 80,
imageCacheDirectory = './public',
customMatchers = [],
}: {
globalExtension?: 'webp' | 'png' | 'jpeg'
compression?: number
imageCacheDirectory?: string
customMatchers?: RegExp[]
} = {}) {
let imageCache: ImageCache
try {
// Pull existing imageCache
if (fs.existsSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`)) {
imageCache = JSON.parse(
fs.readFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, 'utf-8')) as ImageCache
}
else {
imageCache = {}
}
}
catch (e) {
console.warn(e, 'ncms-plugin-images: error attempting to read image cache.')
imageCache = {}
}
async function writeOutImage(imageUrl: string, existingImageFile: ImageCacheEntry): Promise<string> {
let filename = ''
if (existingImageFile)
return existingImageFile.filename as string
const response = await fetch(imageUrl)
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const fileType = await fileTypeFromBuffer(buffer)
if (fileType?.ext) {
const id = nanoid(6)
filename = `${id}.remote.${globalExtension}`
const outputFilePath = `${imageCacheDirectory}/remote/${filename}`
const imageBuffer = sharp(buffer)
const webPBuffer = await imageBuffer[globalExtension]({
quality: compression,
nearLossless: true,
effort: 6,
}).toBuffer()
const writeStream = fs.createWriteStream(outputFilePath)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
writeStream.on('error', err => console.warn(`ncms-plugin-images: failed to write image file: ${err}`))
writeStream.write(webPBuffer)
}
return filename
}
function detectExisting(path: string, imageUrl: string): ImageCacheEntry {
const entries = imageCache[path]
return entries.filter((entry) => {
return multiStringMatch(entry.url, imageUrl) || multiStringMatch(entry.location, imageUrl)
})[0]
}
async function processImage(
path: string,
imageUrl: string,
updator: { update: Content | string },
debug?: boolean): Promise<void> {
if (imageUrl && path) {
let filename = ''
try {
filename = await writeOutImage(imageUrl, detectExisting(path, imageUrl))
}
catch (e) {
if (debug)
console.warn('ncms-plugin-images: File type could not be reliably determined! The binary data may be malformed! No file saved!')
return
}
if (filename) {
imageCache[path].push({
filename,
location: `/remote/${filename}`,
url: imageUrl,
})
// if we don't do this, the replaceall cant find the proper url below
if (typeof updator.update !== 'string') {
if (updator.update?.html.includes('amazonaws'))
updator.update.html = updator.update.html.replaceAll('&', '&')
updator.update.html = updator.update.html.replace(imageUrl, `/remote/${filename}`)
}
else {
// This replaces the coverImage
updator.update = updator.update.replace(imageUrl, `/remote/${filename}`)
}
if (debug)
console.log('ncms-plugin-images: rewriting', path, 'at', filename)
}
}
}
return {
name: 'ncms-plugin-images',
hook: 'during-tree',
core: true,
exec: async ( | context: PageContent, options: PluginExecOptions) => { |
const copyOfContext = structuredClone(context)
if (!copyOfContext.path)
return
const matchables = [
GENERIC_MATCH,
IMAGE_SOURCE_MATCH,
...customMatchers,
]
if (!imageCache[copyOfContext.path])
imageCache[copyOfContext.path] = [] as ImageCacheEntry[]
const contents = {
update: copyOfContext.content as Content,
}
const coverImage = {
update: copyOfContext.coverImage as string,
}
// Must run all async in series so that we don't end up with duplicates
for (const match of matchables) {
if (!copyOfContext.path)
return
const path = copyOfContext.path
const matched = (contents.update && Array.from(contents.update.html.matchAll(match), m => m[1])) || []
const matchedCoverImages = (coverImage.update && [coverImage.update]) || []
for (const imageUrl of matched)
await processImage(path, imageUrl, contents, options.debug)
for (const imageUrl of matchedCoverImages)
await processImage(path, imageUrl, coverImage, options.debug)
}
copyOfContext.content = contents.update
copyOfContext.coverImage = coverImage.update
try {
if (!fs.existsSync(`${imageCacheDirectory}/remote`))
fs.mkdirSync(`${imageCacheDirectory}/remote`)
fs.writeFileSync(`${imageCacheDirectory}/remote/${IMAGE_CACHE_FILENAME}`, JSON.stringify(imageCache))
if (options.debug)
fs.writeFileSync('debug/images.json', JSON.stringify(imageCache))
}
catch (e) {
if (options.debug)
console.warn(e, 'ncms-plugin-images: error writing to image cache.')
}
return copyOfContext
},
}
}
| src/plugins/images.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/plugins/head.ts",
"retrieved_chunk": "import type { PageContent } from '../types'\nexport default function () {\n return {\n name: 'ncms-plugin-head',\n hook: 'during-tree',\n core: true,\n exec: (context: PageContent) => {\n const copyOfContext = structuredClone(context) as PageContentWithMeta\n copyOfContext.meta = {\n title: '',",
"score": 0.8682426810264587
},
{
"filename": "src/plugins/render.ts",
"retrieved_chunk": " return {\n parser,\n name: 'ncms-plugin-blocks-render',\n core: true,\n hook: 'parse',\n exec: (context: PluginPassthrough): string => {\n const copyOfContext = _.cloneDeep(context) as Blocks\n return parser.blocksToHtml(copyOfContext)\n },\n } satisfies UnsafePlugin",
"score": 0.8387293219566345
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " PluginsCustomCMS = new NotionCMS({\n // Kitchen sink DB in community/tests\n databaseId,\n notionAPIKey,\n // Should work with other plugin too\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n }),",
"score": 0.8335131406784058
},
{
"filename": "src/tests/custom-render.spec.ts",
"retrieved_chunk": " databaseId: '610627a9-28b1-4477-b660-c00c5364435b',\n notionAPIKey,\n draftMode: true,\n // Standin Plugin - use default renderer plugin behind the scenes\n plugins: [() => ({\n name: 'ncms-placeholder-plugin',\n hook: 'post-parse',\n exec: (block: Block) => block,\n })],\n })",
"score": 0.8248361945152283
},
{
"filename": "src/tests/notion-cms-caching.spec.ts",
"retrieved_chunk": " hook: '*', // this will run every hook\n exec: (ctx: PluginPassthrough) => {\n counter++\n return ctx\n },\n },\n ],\n })\n console.log('caching test: purging cache')\n testCMS.purgeCache()",
"score": 0.8123331069946289
}
] | typescript | context: PageContent, options: PluginExecOptions) => { |
import type {
AudioBlock,
Block,
Blocks,
BulletedListItemBlock,
CalloutBlock,
CodeBlock,
EmbedBlock,
FileBlock,
HeadingBlock,
ImageBlock,
LinkPreviewBlock,
LinkToPageBlock,
NumberedListItemBlock,
PDFBlock,
ParagraphBlock,
QuoteBlock,
RichText,
ToDoBlock,
VideoBlock,
} from '@notion-stuff/v4-types'
import { z } from 'zod'
import NotionBlocksMarkdownParser from './notion-blocks-md-parser'
import NotionBlocksHtmlParser from './notion-blocks-html-parser'
import NotionBlocksPlaintextParser from './notion-blocks-plaintext-parser'
const blockRenderers = z.object({
AudioBlock: z.function().returns(z.string()),
BulletedListItemBlock: z.function().returns(z.string()),
CalloutBlock: z.function().returns(z.string()),
CodeBlock: z.function().returns(z.string()),
EmbedBlock: z.function().returns(z.string()),
FileBlock: z.function().returns(z.string()),
HeadingBlock: z.function().returns(z.string()),
ImageBlock: z.function().returns(z.string()),
LinkToPageBlock: z.function().returns(z.string()),
NumberedListItemBlock: z.function().returns(z.string()),
ParagraphBlock: z.function().returns(z.string()),
PDFBlock: z.function().returns(z.string()),
QuoteBlock: z.function().returns(z.string()),
RichText: z.function().returns(z.string()),
RichTextEquation: z.function().returns(z.string()),
RichTextMention: z.function().returns(z.string()),
RichTextText: z.function().returns(z.string()),
ToDoBlock: z.function().returns(z.string()),
ToggleBlock: z.function().returns(z.string()),
VideoBlock: z.function().returns(z.string()),
LinkPreviewBlock: z.function().returns(z.string()),
}).partial()
export type BlockRenderers = z.infer<typeof blockRenderers>
type Renderer = (block: Block | RichText[], ...args: unknown[]) => string
type CustomRenderer = (block: Block | RichText[], ...args: unknown[]) => string | null
function modularize(
custom: CustomRenderer | undefined,
def: Renderer): Renderer {
return function render(block: Block | RichText[], ...args: unknown[]) {
if (custom) {
const customRender = custom(block, ...args)
if (customRender !== null)
return customRender
}
return def(block, ...args)
}
}
export default class NotionBlocksParser {
mdParser: NotionBlocksMarkdownParser
htmlParser: NotionBlocksHtmlParser
plainTextParser: NotionBlocksPlaintextParser
debug: boolean
constructor({ blockRenderers, debug }: { blockRenderers?: BlockRenderers; debug?: boolean }) {
this.mdParser = new NotionBlocksMarkdownParser()
this.plainTextParser = new NotionBlocksPlaintextParser()
this.debug = debug || false
this.mdParser.parseParagraph = modularize(
blockRenderers?.ParagraphBlock,
this.mdParser.parseParagraph.bind(this.mdParser) as Renderer,
) as (block: ParagraphBlock) => string
this.mdParser.parseCodeBlock = modularize(
blockRenderers?.CodeBlock,
this.mdParser.parseCodeBlock.bind(this.mdParser) as Renderer,
) as (block: CodeBlock) => string
this.mdParser.parseQuoteBlock = modularize(
blockRenderers?.QuoteBlock,
this.mdParser.parseQuoteBlock.bind(this.mdParser) as Renderer,
) as (block: QuoteBlock) => string
this.mdParser.parseCalloutBlock = modularize(
blockRenderers?.CalloutBlock,
this.mdParser.parseCalloutBlock.bind(this.mdParser) as Renderer,
) as (block: CalloutBlock) => string
this.mdParser.parseHeading = modularize(
blockRenderers?.HeadingBlock,
this.mdParser.parseHeading.bind(this.mdParser) as Renderer,
) as (block: HeadingBlock) => string
this.mdParser.parseBulletedListItems = modularize(
blockRenderers?.BulletedListItemBlock,
this.mdParser.parseBulletedListItems.bind(this.mdParser) as Renderer,
) as (block: BulletedListItemBlock) => string
this.mdParser.parseLinkToPageBlock = modularize(
blockRenderers?.LinkToPageBlock,
this.mdParser.parseLinkToPageBlock.bind(this.mdParser) as Renderer,
) as (block: LinkToPageBlock) => string
this.mdParser.parseNumberedListItems = modularize(
blockRenderers?.NumberedListItemBlock,
this.mdParser.parseNumberedListItems.bind(this.mdParser) as Renderer,
) as (block: NumberedListItemBlock) => string
this.mdParser.parseTodoBlock = modularize(
blockRenderers?.ToDoBlock,
this.mdParser.parseTodoBlock.bind(this.mdParser) as Renderer,
) as (block: ToDoBlock) => string
this.mdParser.parseImageBlock = modularize(
blockRenderers?.ImageBlock,
this.mdParser.parseImageBlock.bind(this.mdParser) as Renderer,
) as (block: ImageBlock) => string
this.mdParser.parseEmbedBlock = modularize(
blockRenderers?.EmbedBlock,
this.mdParser.parseEmbedBlock.bind(this.mdParser) as Renderer,
) as (block: EmbedBlock) => string
this.mdParser.parseAudioBlock = modularize(
blockRenderers?.AudioBlock,
this.mdParser.parseAudioBlock.bind(this.mdParser) as Renderer,
) as (block: AudioBlock) => string
this.mdParser.parseVideoBlock = modularize(
blockRenderers?.VideoBlock,
this.mdParser.parseVideoBlock.bind(this.mdParser) as Renderer,
) as (block: VideoBlock) => string
this.mdParser.parseFileBlock = modularize(
blockRenderers?.FileBlock,
this.mdParser.parseFileBlock.bind(this.mdParser) as Renderer,
) as (block: FileBlock) => string
this.mdParser.parsePdfBlock = modularize(
blockRenderers?.PDFBlock,
this.mdParser.parsePdfBlock.bind(this.mdParser) as Renderer,
) as (block: PDFBlock) => string
this.mdParser.parseLinkPreview = modularize(
blockRenderers?.LinkPreviewBlock,
this.mdParser.parseLinkPreview.bind(this.mdParser) as Renderer,
) as (block: LinkPreviewBlock) => string
// Warning: this parser is used in many of the other parsers internally.
// Modding it could affect the others unexpectedly.
this.mdParser.parseRichTexts = modularize(
blockRenderers?.RichText,
this.mdParser.parseRichTexts.bind(this.mdParser) as Renderer,
) as (block: RichText[]) => string
this.htmlParser = new NotionBlocksHtmlParser(this.mdParser, this.debug)
}
markdownToPlainText(markdown: string): string {
return this.plainTextParser.parse(markdown)
}
blocksToPlainText(blocks: Blocks, depth?: number): string {
return this.plainTextParser.parse(
this.blocksToMarkdown(blocks, depth))
}
blocksToMarkdown(blocks: Blocks, depth?: number): string {
| return this.mdParser.parse(blocks, depth)
} |
blocksToHtml(blocks: Blocks): string {
return this.htmlParser.parse(blocks)
}
static parseRichText(richTexts: RichText[]) {
const tempParser = new NotionBlocksMarkdownParser()
return tempParser.parseRichTexts(richTexts)
}
}
| src/notion-blocks-parser.ts | agency-kit-notion-cms-dfe1751 | [
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " }\n marked.use({ silent: true })\n // This is a workaround so that hljs doesn't complain about mermaid not being a registered lang.\n hljs.registerAliases('mermaid', { languageName: 'plaintext' })\n }\n marked(md: string): string {\n return marked(md, this.markedOptions)\n }\n parse(blocks: Blocks) {\n let markdown = this.markdownParser.parse(blocks)",
"score": 0.844572901725769
},
{
"filename": "src/notion-cms.ts",
"retrieved_chunk": " async _parsePageContent(pageContent: BlockObjectResponse[]): Promise<Content> {\n const results = await this._runPlugins(pageContent as Blocks, 'pre-parse')\n const markdown: string = this.coreRenderer.parser.blocksToMarkdown(pageContent as Blocks)\n const plaintext: string = this.coreRenderer.parser.markdownToPlainText(markdown)\n const parsedBlocks = await this._runPlugins(results as Blocks, 'parse')\n const html = await this._runPlugins(parsedBlocks, 'post-parse') as string\n return {\n plaintext,\n markdown,\n html,",
"score": 0.8344501256942749
},
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": " }\n return embedded.concat(EOL_MD)\n }\n parseRichTexts(richTexts: RichText[]): string {\n return richTexts.reduce((parsedContent, richText) => {\n switch (richText.type) {\n case 'text':\n parsedContent += this.parseText(richText)\n break\n case 'mention':",
"score": 0.827959418296814
},
{
"filename": "src/notion-blocks-html-parser.ts",
"retrieved_chunk": " // if (this.debug)\n // fs.writeFileSync('./debug/parsed.md', markdown)\n // Take another pass to wrap any deeply nested mixed HTML content's inner text in p tags\n markdown = this._mixedHTML(markdown)\n // if (this.debug)\n // fs.appendFileSync('./debug/parsed.md', `--------ALTERED----------**\\n\\n\\n${markdown}`)\n return marked(markdown, this.markedOptions)\n }\n _highlight(code: string, lang: string | undefined): string {\n let language",
"score": 0.8170344829559326
},
{
"filename": "src/notion-blocks-md-parser.ts",
"retrieved_chunk": " parsedContent += this.parseMention(richText)\n break\n case 'equation':\n parsedContent += this.parseEquation(richText)\n break\n }\n return parsedContent\n }, '')\n }\n parseText(richText: RichTextText): string {",
"score": 0.8042328357696533
}
] | typescript | return this.mdParser.parse(blocks, depth)
} |
import { MarkdownRenderChild, MarkdownRenderer } from "obsidian";
import { isDefined, createElementShort } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CardContent,
AutoTimelineSettings,
} from "~/types";
import { formatAbstractDate } from "./abstractDateFormatting";
/**
* Generates a card in the DOM based on given ccontext.
*
* @param param0 - The context built for this timeline.
* @param param0.elements - The HTMLElements exposed for this context.
* @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.
* @param param0.file - The target note file.
* @param param0.settings - The plugin's settings.
* @param cardContent - The content of a single timeline card.
*/
export function createCardFromBuiltContext(
{
elements: { cardListRootElement },
file,
settings,
}: MarkdownCodeBlockTimelineProcessingContext,
cardContent: CardContent
): void {
const { body, title, imageURL } = cardContent;
const cardBaseDiv = createElementShort(cardListRootElement, "a", [
"internal-link",
"aat-card",
]);
cardBaseDiv.setAttribute("href", file.path);
if (imageURL) {
createElementShort(cardBaseDiv, "img", "aat-card-image").setAttribute(
"src",
imageURL
);
cardBaseDiv.addClass("aat-card-has-image");
}
const cardTextWraper = createElementShort(
cardBaseDiv,
"div",
"aat-card-text-wraper"
);
const titleWrap = createElementShort(
cardTextWraper,
"header",
"aat-card-head-wrap"
);
createElementShort(titleWrap, "h2", "aat-card-title", title);
createElementShort(
titleWrap,
"h4",
"aat-card-start-date",
getDateText(cardContent, settings).trim()
);
const markdownTextWrapper = createElementShort(
cardTextWraper,
"div",
"aat-card-body"
);
const rendered = new MarkdownRenderChild(markdownTextWrapper);
rendered.containerEl = markdownTextWrapper;
MarkdownRenderer.renderMarkdown(
formatBodyForCard(body),
markdownTextWrapper,
file.path,
rendered
);
}
/**
* Format the body string of the note data for a single card.
*
* @param body - The body string parsed earlier.
* @returns The formated string ready to be displayed.
*/
export function formatBodyForCard(body?: string | null): string {
if (!body) return "No body for this note :(";
// Remove external image links
return (
body
.replace(/!\[.*\]\(.*\)/gi, "")
// Remove tags
.replace(/#[a-zA-Z\d-_]*/gi, "")
// Remove internal images ![[Pasted image 20230418232101.png]]
.replace(/!\[\[.*\]\]/gi, "")
// Remove other timelines to avoid circular dependencies!
.replace(/```aat-vertical\n.*\n```/gi, "")
// Trim the text
.trim()
);
}
/**
* Get the text displayed in the card where the date should be.
*
* @param param0 - The context for a single card.
* @param param0.startDate - the start date of an event.
* @param param0.endDate - the end date of an event.
* @param settings - The settings of the plugin.
* @returns a formated string representation of the dates included in the card content based off the settings.
*/
export function getDateText(
{ startDate, endDate }: Pick<CardContent, "startDate" | "endDate">,
settings: AutoTimelineSettings
): string {
if (!isDefined(startDate)) return "Start date missing";
| const formatedStart = formatAbstractDate(startDate, settings); |
if (!isDefined(endDate)) return formatedStart;
return `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;
}
| src/cardMarkup.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.\n * @returns The start and end boundaries of the target end date.\n */\nexport function findBoundaries(\n\tdate: AbstractDate,\n\tcollection: CompleteCardContext[],\n\trootElement: HTMLElement,\n\tindexOffset: number\n): { start: Boundary; end: Boundary } {\n\tconst firstOverIndex = collection.findIndex(({ cardData: { startDate } }) =>",
"score": 0.873080849647522
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 0.8592587113380432
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.8584709167480469
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "] as const;\n/**\n * Renders the little stripes in the gutter of the timeline.\n *\n * @param ranges - A collection of ranges.\n * @param rootElement - The root of all elements for this complete timeline.\n */\nexport function renderRanges(ranges: Range[], rootElement: HTMLElement) {\n\tconst endDates: (number[] | true | undefined)[] = AVAILABLE_COLORS.map(\n\t\t() => undefined",
"score": 0.8571807146072388
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "}\n/**\n * Shorthand to format a part of an abstract date.\n *\n * @param datePart - fragment of an abstract date.\n * @param configuration - the configuration bound to that date token.\n * @returns the formated token.\n */\nexport function formatDateToken(\n\tdatePart: number,",
"score": 0.8483216762542725
}
] | typescript | const formatedStart = formatAbstractDate(startDate, settings); |
import { MarkdownRenderChild, MarkdownRenderer } from "obsidian";
import { isDefined, createElementShort } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CardContent,
AutoTimelineSettings,
} from "~/types";
import { formatAbstractDate } from "./abstractDateFormatting";
/**
* Generates a card in the DOM based on given ccontext.
*
* @param param0 - The context built for this timeline.
* @param param0.elements - The HTMLElements exposed for this context.
* @param param0.elements.cardListRootElement - The right side of the timeline, this is where the carads are spawned.
* @param param0.file - The target note file.
* @param param0.settings - The plugin's settings.
* @param cardContent - The content of a single timeline card.
*/
export function createCardFromBuiltContext(
{
elements: { cardListRootElement },
file,
settings,
}: MarkdownCodeBlockTimelineProcessingContext,
cardContent: CardContent
): void {
const { body, title, imageURL } = cardContent;
const cardBaseDiv = createElementShort(cardListRootElement, "a", [
"internal-link",
"aat-card",
]);
cardBaseDiv.setAttribute("href", file.path);
if (imageURL) {
createElementShort(cardBaseDiv, "img", "aat-card-image").setAttribute(
"src",
imageURL
);
cardBaseDiv.addClass("aat-card-has-image");
}
const cardTextWraper = createElementShort(
cardBaseDiv,
"div",
"aat-card-text-wraper"
);
const titleWrap = createElementShort(
cardTextWraper,
"header",
"aat-card-head-wrap"
);
createElementShort(titleWrap, "h2", "aat-card-title", title);
createElementShort(
titleWrap,
"h4",
"aat-card-start-date",
getDateText(cardContent, settings).trim()
);
const markdownTextWrapper = createElementShort(
cardTextWraper,
"div",
"aat-card-body"
);
const rendered = new MarkdownRenderChild(markdownTextWrapper);
rendered.containerEl = markdownTextWrapper;
MarkdownRenderer.renderMarkdown(
formatBodyForCard(body),
markdownTextWrapper,
file.path,
rendered
);
}
/**
* Format the body string of the note data for a single card.
*
* @param body - The body string parsed earlier.
* @returns The formated string ready to be displayed.
*/
export function formatBodyForCard(body?: string | null): string {
if (!body) return "No body for this note :(";
// Remove external image links
return (
body
.replace(/!\[.*\]\(.*\)/gi, "")
// Remove tags
.replace(/#[a-zA-Z\d-_]*/gi, "")
// Remove internal images ![[Pasted image 20230418232101.png]]
.replace(/!\[\[.*\]\]/gi, "")
// Remove other timelines to avoid circular dependencies!
.replace(/```aat-vertical\n.*\n```/gi, "")
// Trim the text
.trim()
);
}
/**
* Get the text displayed in the card where the date should be.
*
* @param param0 - The context for a single card.
* @param param0.startDate - the start date of an event.
* @param param0.endDate - the end date of an event.
* @param settings - The settings of the plugin.
* @returns a formated string representation of the dates included in the card content based off the settings.
*/
export function getDateText(
{ startDate, endDate }: Pick<CardContent, "startDate" | "endDate">,
settings: AutoTimelineSettings
): string {
| if (!isDefined(startDate)) return "Start date missing"; |
const formatedStart = formatAbstractDate(startDate, settings);
if (!isDefined(endDate)) return formatedStart;
return `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;
}
| src/cardMarkup.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t}\n\treturn [0, 1, 1];\n}\ntype Boundary = { date: AbstractDate; top: number };\n/**\n * Find the position of the last card having a lower start date and the first card with a higher start date relative to the endDate of the evaluated range.\n *\n * @param date - The target endDate to position on the timeline.\n * @param collection - The collection of cards part of the same timeline.\n * @param rootElement - The root HTMLElement of the cardList.",
"score": 0.8724555373191833
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " *\n * @param date - The target endDate to position on the timeline.\n * @param collection - The collection of cards part of the same timeline.\n * @param timelineLength - The length in pixel of the timeline.\n * @param rootElement - The root HTMLElement of the cardList.\n * @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.\n * @returns The expected position relative to the top of the timeline container for this date range.\n */\nexport function findEndPositionForDate(\n\tdate: AbstractDate,",
"score": 0.8686689138412476
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.\n * @returns The start and end boundaries of the target end date.\n */\nexport function findBoundaries(\n\tdate: AbstractDate,\n\tcollection: CompleteCardContext[],\n\trootElement: HTMLElement,\n\tindexOffset: number\n): { start: Boundary; end: Boundary } {\n\tconst firstOverIndex = collection.findIndex(({ cardData: { startDate } }) =>",
"score": 0.8686665892601013
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 0.8682236671447754
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "] as const;\n/**\n * Renders the little stripes in the gutter of the timeline.\n *\n * @param ranges - A collection of ranges.\n * @param rootElement - The root of all elements for this complete timeline.\n */\nexport function renderRanges(ranges: Range[], rootElement: HTMLElement) {\n\tconst endDates: (number[] | true | undefined)[] = AVAILABLE_COLORS.map(\n\t\t() => undefined",
"score": 0.8628178834915161
}
] | typescript | if (!isDefined(startDate)) return "Start date missing"; |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab( | new TimelineSettingTab(this.app, this)); |
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "\t\t\t`{${token}}`,\n\t\t\tapplyConditionBasedFormatting(\n\t\t\t\tformatDateToken(date[index], configuration),\n\t\t\t\tdate[index],\n\t\t\t\tconfiguration,\n\t\t\t\tapplyAdditonalConditionFormatting\n\t\t\t)\n\t\t);\n\t});\n\treturn output;",
"score": 0.7248854637145996
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "\tlet output = dateDisplayFormat.toString();\n\tprioArray.forEach((token, index) => {\n\t\tconst configuration = dateTokenConfiguration.find(\n\t\t\t({ name }) => name === token\n\t\t);\n\t\tif (!configuration)\n\t\t\tthrow new Error(\n\t\t\t\t`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`\n\t\t\t);\n\t\toutput = output.replace(",
"score": 0.6866298913955688
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.6764441728591919
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tconstructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {\n\t\tsuper(app, plugin);\n\t\tthis.plugin = plugin;\n\t\tthis.vueApp = null;\n\t}\n\tdisplay(): void {\n\t\tthis.containerEl.empty();\n\t\t// TODO Read locale off obsidian.\n\t\tconst i18n = createVueI18nConfig();\n\t\tthis.vueApp = createApp({",
"score": 0.6760809421539307
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tend: {\n\t\t\ttop: getChildAtIndexInHTMLElement(\n\t\t\t\trootElement,\n\t\t\t\tfirstOverIndex + indexOffset\n\t\t\t).offsetTop,\n\t\t\tdate: collection[firstOverIndex].cardData.startDate as AbstractDate,\n\t\t},\n\t};\n}",
"score": 0.6691486835479736
}
] | typescript | new TimelineSettingTab(this.app, this)); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = | compareAbstractDates(a, b); |
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 0.8174475431442261
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)",
"score": 0.8041595220565796
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 0.779681921005249
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 0.7725695371627808
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.\n * @returns The start and end boundaries of the target end date.\n */\nexport function findBoundaries(\n\tdate: AbstractDate,\n\tcollection: CompleteCardContext[],\n\trootElement: HTMLElement,\n\tindexOffset: number\n): { start: Boundary; end: Boundary } {\n\tconst firstOverIndex = collection.findIndex(({ cardData: { startDate } }) =>",
"score": 0.759835958480835
}
] | typescript | compareAbstractDates(a, b); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const | baseData = await getDataFromNoteMetadata(context, tagsToFind); |
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 0.7823827266693115
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 0.7403082251548767
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "\t\telements: { cardListRootElement },\n\t\tfile,\n\t\tsettings,\n\t}: MarkdownCodeBlockTimelineProcessingContext,\n\tcardContent: CardContent\n): void {\n\tconst { body, title, imageURL } = cardContent;\n\tconst cardBaseDiv = createElementShort(cardListRootElement, \"a\", [\n\t\t\"internal-link\",\n\t\t\"aat-card\",",
"score": 0.732813835144043
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t)\n\t\t\t\treturn accumulator;\n\t\t\tconst timelineLength = timelineRootElement.offsetHeight;\n\t\t\tconst targetCard = cardListRootElement.children.item(\n\t\t\t\tindex\n\t\t\t) as HTMLElement | null;\n\t\t\t// Error handling but should not happen\n\t\t\tif (!targetCard) return accumulator;\n\t\t\tconst cardRelativeTopPosition = targetCard.offsetTop;\n\t\t\tlet targetPosition: number;",
"score": 0.7306746244430542
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 0.7243709564208984
}
] | typescript | baseData = await getDataFromNoteMetadata(context, tagsToFind); |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
| prioArray.forEach((token, index) => { |
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.7333487272262573
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}",
"score": 0.7045586109161377
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 0.694819450378418
},
{
"filename": "src/types.ts",
"retrieved_chunk": "type NumberSpecific = Merge<\n\tCommonValues<DateTokenType.number>,\n\t{\n\t\t/**\n\t\t * The minimum ammount of digits when displaying the date\n\t\t */\n\t\tminLeght: number;\n\t\tdisplayWhenZero: boolean;\n\t\thideSign: boolean;\n\t}",
"score": 0.690066933631897
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 0.6862050294876099
}
] | typescript | prioArray.forEach((token, index) => { |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
| if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 0.8152860999107361
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 0.8145204782485962
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": " * @param timelineFile - The file path of the timeline.\n * @param settings - The plugin's settings.\n * @returns the nessessary context to build a timeline.\n */\nexport function setupTimelineCreation(\n\tapp: App,\n\telement: HTMLElement,\n\ttimelineFile: string,\n\tsettings: AutoTimelineSettings\n) {",
"score": 0.802923321723938
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn isDefined(value) && value instanceof Object;\n}\n/**\n * Shorthand to quickly get a well typed number date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.number> - A well typed date token configuration object.\n */\nexport function createNumberDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.number>> = {}",
"score": 0.7976939678192139
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 0.7936758995056152
}
] | typescript | if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
import { PluginSettingTab } from "obsidian";
import { createApp, ref } from "vue";
import createVueI18nConfig from "~/i18n.config";
import VApp from "~/views/App.vue";
import type { App as ObsidianApp } from "obsidian";
import type AprilsAutomaticTimelinesPlugin from "~/main";
import type { AutoTimelineSettings, DateTokenConfiguration } from "./types";
import type { App as VueApp } from "vue";
import { createNumberDateTokenConfiguration } from "./utils";
/**
* Default key value relation for obsidian settings object
*/
export const SETTINGS_DEFAULT = {
metadataKeyEventStartDate: "aat-event-start-date",
metadataKeyEventEndDate: "aat-event-end-date",
metadataKeyEventTitleOverride: "aat-event-title",
metadataKeyEventBodyOverride: "aat-event-body",
metadataKeyEventPictureOverride: "aat-event-picture",
metadataKeyEventTimelineTag: "timelines",
noteInlineEventKey: "aat-inline-event",
markdownBlockTagsToFindSeparator: ",",
dateParserRegex: "(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)",
dateParserGroupPriority: "year,month,day",
dateDisplayFormat: "{day}/{month}/{year}",
lookForTagsForTimeline: false,
lookForInlineEventsInNotes: true,
applyAdditonalConditionFormatting: true,
dateTokenConfiguration: [
createNumberDateTokenConfiguration({ name: "year", minLeght: 4 }),
createNumberDateTokenConfiguration({ name: "month" }),
createNumberDateTokenConfiguration({ name: "day" }),
] as DateTokenConfiguration[],
};
export const __VUE_PROD_DEVTOOLS__ = true;
/**
* Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note.
*/
export class TimelineSettingTab extends PluginSettingTab {
plugin: AprilsAutomaticTimelinesPlugin;
vueApp: VueApp<Element> | null;
constructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {
super(app, plugin);
this.plugin = plugin;
this.vueApp = null;
}
display(): void {
this.containerEl.empty();
// TODO Read locale off obsidian.
const i18n = createVueI18nConfig();
this.vueApp = createApp({
components: { VApp },
template: "<VApp :value='value' @update:value='save' />",
setup: () => {
const value = ref(this.plugin.settings);
return {
value,
| save: async (payload: Partial<AutoTimelineSettings>) => { |
this.plugin.settings = {
...this.plugin.settings,
...payload,
};
value.value = this.plugin.settings;
await this.plugin.saveSettings();
},
};
},
methods: {},
});
this.vueApp.use(i18n).mount(this.containerEl);
}
hide() {
if (!this.vueApp) return;
this.vueApp.unmount();
this.vueApp = null;
}
}
| src/settings.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst { app } = this;\n\t\tconst { tagsToFind, settingsOverride } =\n\t\t\tparseMarkdownBlockSource(source);\n\t\tconst finalSettings = { ...this.settings, ...settingsOverride };\n\t\tconst creationContext = setupTimelineCreation(\n\t\t\tapp,\n\t\t\telement,\n\t\t\tsourcePath,\n\t\t\tfinalSettings\n\t\t);",
"score": 0.729720950126648
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },\n\t\tfile: currentFile,\n\t\tapp,\n\t\tsettings: { metadataKeyEventPictureOverride },\n\t} = context;\n\tconst {\n\t\tvault,\n\t\tmetadataCache: { getFirstLinkpathDest },",
"score": 0.7282462120056152
},
{
"filename": "src/i18n.config.ts",
"retrieved_chunk": "import { createI18n } from \"vue-i18n\";\nimport en from \"~/locales/en.json\";\nexport default () =>\n\tcreateI18n({\n\t\tlocale: \"en\",\n\t\tfallbackLocale: \"en\",\n\t\tmessages: {\n\t\t\ten,\n\t\t},\n\t\tallowComposition: true,",
"score": 0.7266974449157715
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treturn {\n\t\ttagsToFind,\n\t\tsettingsOverride: sourceEntries.reduce((accumulator, element) => {\n\t\t\treturn {\n\t\t\t\t...accumulator,\n\t\t\t\t...parseSingleLine(element),\n\t\t\t};\n\t\t}, {} as Partial<AutoTimelineSettings>),\n\t} as const;\n}",
"score": 0.7165855765342712
},
{
"filename": "src/main.ts",
"retrieved_chunk": "export default class AprilsAutomaticTimelinesPlugin extends Plugin {\n\tsettings: AutoTimelineSettings;\n\t/**\n\t * The default onload method of a obsidian plugin\n\t * See the official documentation for more details\n\t */\n\tasync onload() {\n\t\tawait this.loadSettings();\n\t\tthis.registerMarkdownCodeBlockProcessor(\n\t\t\t\"aat-vertical\",",
"score": 0.7103560566902161
}
] | typescript | save: async (payload: Partial<AutoTimelineSettings>) => { |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray. | forEach((token, index) => { |
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.7441632747650146
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}",
"score": 0.7129130959510803
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 0.6894771456718445
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 0.6857807636260986
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);",
"score": 0.6834651231765747
}
] | typescript | forEach((token, index) => { |
import { SETTINGS_DEFAULT } from "~/settings";
import { FnGetRangeData } from "./rangeData";
import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData";
import type { App, CachedMetadata, TFile } from "obsidian";
import type { Merge } from "ts-essentials";
/**
* @author https://stackoverflow.com/a/69756175
*/
export type PickByType<T, Value> = {
[P in keyof T as T[P] extends Value | undefined ? P : never]: T[P];
};
export type AutoTimelineSettings = typeof SETTINGS_DEFAULT;
/**
* The main bundle of data needed to build a timeline.
*/
export interface MarkdownCodeBlockTimelineProcessingContext {
/**
* Obsidian application context.
*/
app: App;
/**
* The plugins settings
*/
settings: AutoTimelineSettings;
/**
* The formatted metadata of a single note.
*/
cachedMetadata: CachedMetadata;
/**
* The file data of a single note.
*/
file: TFile;
/**
* The filepath of a single timeline.
*/
timelineFile: string;
/**
* Shorthand access to HTMLElements for the range timelines and the card list.
*/
elements: {
timelineRootElement: HTMLElement;
cardListRootElement: HTMLElement;
};
}
/**
* The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.
*/
export type CompleteCardContext = Exclude<
Awaited<ReturnType<typeof getDataFromNoteMetadata>>,
undefined
>;
/**
* The context extracted from a single note to create a single card in the timeline.
*/
| export type CardContent = Awaited<ReturnType<FnExtractCardData>>; |
/**
* The needed data to compute a range in a single timeline.
*/
export type Range = ReturnType<FnGetRangeData>[number];
/**
* An abstract representation of a fantasy date.
* Given the fickle nature of story telling and how people will literally almost never stick to standard date formats
* We'll organise the dates in segments, let's take for example our human callendar
* The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to
* `[year, month, day]`
* Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates.
* The only major limitation to this system is that all the dates must respect the same system.
*/
export type AbstractDate = number[];
/**
* Before formatting an abstract date, the end user can configure it's output display
* This DateToken type helps to determine what's the nature of a given token
* E.g. should it be displayed as a number or as a string ?
*/
export enum DateTokenType {
number = "NUMBER",
string = "STRING",
}
export const availableDateTokenTypeArray = Object.values(DateTokenType);
export enum Condition {
Greater = "GREATER",
Less = "LESS",
Equal = "EQUAL",
NotEqual = "NOTEQUAL",
GreaterOrEqual = "GREATEROREQUAL",
LessOrEqual = "LESSOREQUAL",
}
export const availableConditionArray = Object.values(Condition);
export type Evaluation<T extends number = number> = {
condition: Condition;
value: T;
};
export type AdditionalDateFormatting<T extends number = number> = {
evaluations: Evaluation<T>[];
/**
* Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.
*/
conditionsAreExclusive: boolean;
/**
* Use `{value}` to include the pre-formated output of the numerical value held.
*/
format: string;
};
/**
* The data used to compute the output of an abstract date based on it's type
*/
type CommonValues<T extends DateTokenType> = {
name: string;
type: T;
formatting: AdditionalDateFormatting[];
};
export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =
T extends DateTokenType.number
? NumberSpecific
: T extends DateTokenType.string
? StringSpecific
: StringSpecific | NumberSpecific;
/**
* Number typed date token.
*/
type NumberSpecific = Merge<
CommonValues<DateTokenType.number>,
{
/**
* The minimum ammount of digits when displaying the date
*/
minLeght: number;
displayWhenZero: boolean;
hideSign: boolean;
}
>;
/**
* String typed date token.
*/
type StringSpecific = Merge<
CommonValues<DateTokenType.string>,
{
/**
* The dictionary reference for the token
*/
dictionary: string[];
}
>;
| src/types.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.8355634212493896
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the body of a given card or null if none was found.\n */\nexport function getBodyFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext\n): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },",
"score": 0.8321195244789124
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * Will compute all the data needed to build ranges in the timeline.\n *\n * @param collection - The complete collection of relevant data gathered from notes.\n * @returns the needed data to build ranges in the timeline.\n */\nexport function getAllRangeData(collection: CompleteCardContext[]) {\n\tif (!collection.length) return [];\n\treturn collection.reduce(\n\t\t(accumulator, relatedCardData, index) => {\n\t\t\tconst {",
"score": 0.8284912109375
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "/**\n * Format the body string of the note data for a single card.\n *\n * @param body - The body string parsed earlier.\n * @returns The formated string ready to be displayed.\n */\nexport function formatBodyForCard(body?: string | null): string {\n\tif (!body) return \"No body for this note :(\";\n\t// Remove external image links\n\treturn (",
"score": 0.8232753276824951
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "/**\n * Extract the first image from the raw markdown in a note.\n *\n * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the URL of the image to be displayed in a card or null if none where found.\n */\nexport function getImageUrlFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext",
"score": 0.8228685855865479
}
] | typescript | export type CardContent = Awaited<ReturnType<FnExtractCardData>>; |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if ( | isDefined(baseData)) events.push(baseData); |
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 0.7858667969703674
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 0.7206518650054932
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();",
"score": 0.7118521332740784
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 0.707359254360199
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " */\nexport function getTagsFromMetadataOrTagObject(\n\tsettings: AutoTimelineSettings,\n\tmetaData: Omit<FrontMatterCache, \"position\">,\n\ttags?: TagCache[]\n): string[] {\n\tlet output = [] as string[];\n\tconst timelineArray = metaData[settings.metadataKeyEventTimelineTag];\n\tif (isDefinedAsArray(timelineArray))\n\t\toutput = timelineArray.filter(isDefinedAsString);",
"score": 0.6974855065345764
}
] | typescript | isDefined(baseData)) events.push(baseData); |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
( | { name }) => name === token
); |
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);",
"score": 0.7891553640365601
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.7604337334632874
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)",
"score": 0.7465493679046631
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 0.745525598526001
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 0.7292283177375793
}
] | typescript | { name }) => name === token
); |
import { PluginSettingTab } from "obsidian";
import { createApp, ref } from "vue";
import createVueI18nConfig from "~/i18n.config";
import VApp from "~/views/App.vue";
import type { App as ObsidianApp } from "obsidian";
import type AprilsAutomaticTimelinesPlugin from "~/main";
import type { AutoTimelineSettings, DateTokenConfiguration } from "./types";
import type { App as VueApp } from "vue";
import { createNumberDateTokenConfiguration } from "./utils";
/**
* Default key value relation for obsidian settings object
*/
export const SETTINGS_DEFAULT = {
metadataKeyEventStartDate: "aat-event-start-date",
metadataKeyEventEndDate: "aat-event-end-date",
metadataKeyEventTitleOverride: "aat-event-title",
metadataKeyEventBodyOverride: "aat-event-body",
metadataKeyEventPictureOverride: "aat-event-picture",
metadataKeyEventTimelineTag: "timelines",
noteInlineEventKey: "aat-inline-event",
markdownBlockTagsToFindSeparator: ",",
dateParserRegex: "(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)",
dateParserGroupPriority: "year,month,day",
dateDisplayFormat: "{day}/{month}/{year}",
lookForTagsForTimeline: false,
lookForInlineEventsInNotes: true,
applyAdditonalConditionFormatting: true,
dateTokenConfiguration: [
createNumberDateTokenConfiguration({ name: "year", minLeght: 4 }),
createNumberDateTokenConfiguration({ name: "month" }),
createNumberDateTokenConfiguration({ name: "day" }),
] as DateTokenConfiguration[],
};
export const __VUE_PROD_DEVTOOLS__ = true;
/**
* Class designed to display the inputs that allow the end user to change the default keys that are looked for when processing metadata in a single note.
*/
export class TimelineSettingTab extends PluginSettingTab {
plugin: AprilsAutomaticTimelinesPlugin;
vueApp: VueApp<Element> | null;
constructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {
super(app, plugin);
this.plugin = plugin;
this.vueApp = null;
}
display(): void {
this.containerEl.empty();
// TODO Read locale off obsidian.
| const i18n = createVueI18nConfig(); |
this.vueApp = createApp({
components: { VApp },
template: "<VApp :value='value' @update:value='save' />",
setup: () => {
const value = ref(this.plugin.settings);
return {
value,
save: async (payload: Partial<AutoTimelineSettings>) => {
this.plugin.settings = {
...this.plugin.settings,
...payload,
};
value.value = this.plugin.settings;
await this.plugin.saveSettings();
},
};
},
methods: {},
});
this.vueApp.use(i18n).mount(this.containerEl);
}
hide() {
if (!this.vueApp) return;
this.vueApp.unmount();
this.vueApp = null;
}
}
| src/settings.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/main.ts",
"retrieved_chunk": "export default class AprilsAutomaticTimelinesPlugin extends Plugin {\n\tsettings: AutoTimelineSettings;\n\t/**\n\t * The default onload method of a obsidian plugin\n\t * See the official documentation for more details\n\t */\n\tasync onload() {\n\t\tawait this.loadSettings();\n\t\tthis.registerMarkdownCodeBlockProcessor(\n\t\t\t\"aat-vertical\",",
"score": 0.7388985753059387
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst { app } = this;\n\t\tconst { tagsToFind, settingsOverride } =\n\t\t\tparseMarkdownBlockSource(source);\n\t\tconst finalSettings = { ...this.settings, ...settingsOverride };\n\t\tconst creationContext = setupTimelineCreation(\n\t\t\tapp,\n\t\t\telement,\n\t\t\tsourcePath,\n\t\t\tfinalSettings\n\t\t);",
"score": 0.7208501696586609
},
{
"filename": "src/i18n.config.ts",
"retrieved_chunk": "import { createI18n } from \"vue-i18n\";\nimport en from \"~/locales/en.json\";\nexport default () =>\n\tcreateI18n({\n\t\tlocale: \"en\",\n\t\tfallbackLocale: \"en\",\n\t\tmessages: {\n\t\t\ten,\n\t\t},\n\t\tallowComposition: true,",
"score": 0.6976207494735718
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },\n\t\tfile: currentFile,\n\t\tapp,\n\t\tsettings: { metadataKeyEventPictureOverride },\n\t} = context;\n\tconst {\n\t\tvault,\n\t\tmetadataCache: { getFirstLinkpathDest },",
"score": 0.6812759637832642
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "\t);\n\tconst rendered = new MarkdownRenderChild(markdownTextWrapper);\n\trendered.containerEl = markdownTextWrapper;\n\tMarkdownRenderer.renderMarkdown(\n\t\tformatBodyForCard(body),\n\t\tmarkdownTextWrapper,\n\t\tfile.path,\n\t\trendered\n\t);\n}",
"score": 0.6804263591766357
}
] | typescript | const i18n = createVueI18nConfig(); |
import PROP_PREFIX from './prefix';
// part and slotted not currently supported by quarks
const PSEUDO_ELEMENTS = [
// '::part()',
// '::slotted()',
'::after',
'::backdrop',
'::before',
'::cue',
'::cue-region',
'::first-letter',
'::first-line',
'::file-selector-button',
'::grammar-error',
'::marker',
'::placeholder',
'::selection',
'::spelling-error',
'::target-text',
'::-moz-placeholder',
'::-moz-progress-bar',
'::-moz-range-progress',
'::-moz-range-thumb',
'::-moz-range-track',
'::-moz-selection',
'::-ms-backdrop',
'::-ms-browse',
'::-ms-check',
'::-ms-clear',
'::-ms-expand',
'::-ms-fill',
'::-ms-fill-lower',
'::-ms-fill-upper',
'::-ms-input-placeholder',
'::-ms-reveal',
'::-ms-thumb',
'::-ms-ticks-after',
'::-ms-ticks-before',
'::-ms-tooltip',
'::-ms-track',
'::-ms-value',
'::-webkit-backdrop',
'::-webkit-input-placeholder',
'::-webkit-progress-bar',
'::-webkit-progress-inner-value',
'::-webkit-progress-value',
'::-webkit-slider-runnable-track',
'::-webkit-slider-thumb',
];
| export const prefixedPseudoElements = PSEUDO_ELEMENTS.map(pseudoEle => pseudoEle.replace('::', PROP_PREFIX)); |
export default PSEUDO_ELEMENTS;
| src/constants/pseudoElements.ts | quarks-css-quarks-2822055 | [
{
"filename": "src/createStylesFromProps.ts",
"retrieved_chunk": "import PROP_PREFIX from './constants/prefix';\nimport { validateProp } from './setup';\nimport media from './theme/breakpoints';\nimport { customOverwrites } from './theme/customOverwrites';\nimport { camelToKebabCase } from './utils/functions';\nimport { isCustomOverwrite, isMediaQuery, isPseudo, isPseudoElement } from './utils/propChecks';\nimport { objectEntries } from './utils/typeUtils';\nimport type { CSSAttribute } from 'goober';\nconst createStylesFromProps = (props: Record<string, unknown>): CSSAttribute =>\n objectEntries(props).reduce((prevValue, prop) => {",
"score": 0.5436543822288513
},
{
"filename": "src/theme/breakpoints.ts",
"retrieved_chunk": "import { objectEntries } from '../utils/typeUtils';\nconst DEFAULT_BREAKPOINTS = {\n xs: '375px',\n sm: '576px',\n md: '768px',\n lg: '992px',\n xl: '1280px',\n} as const;\ntype CreateMedia<T extends typeof DEFAULT_BREAKPOINTS> = {\n [P in keyof T & string as `$${P}`]: T[P] extends string ? `@media screen and (min-width: ${T[P]})` : never;",
"score": 0.5341248512268066
},
{
"filename": "src/types/pseudos.ts",
"retrieved_chunk": "import type { PropPrefix } from '../constants/prefix';\nimport type { Replace } from '../utils/typeUtils';\nimport type { Pseudos } from 'csstype';\ntype FilterPseudoTypes<T extends string, U extends string> = T extends `${U}${string}` ? T : never;\ntype PseudoElements = FilterPseudoTypes<Pseudos, '::'>;\ntype PseudoClasses = Exclude<Pseudos, PseudoElements>;\nexport type PseudoClassProps = Replace<PseudoClasses, ':', PropPrefix>;\nexport type PseudoElementProps = Exclude<Replace<PseudoElements, '::', PropPrefix>, '$slotted' | '$part'>;",
"score": 0.525585949420929
},
{
"filename": "src/utils/propChecks.ts",
"retrieved_chunk": "import { prefixedPseudoElements } from '../constants/pseudoElements';\nimport media from '../theme/breakpoints';\nimport { customOverwrites } from '../theme/customOverwrites';\nimport type { valueof } from './typeUtils';\ntype customOverWriteValues = Parameters<valueof<typeof customOverwrites>>[number];\nexport const isCustomOverwrite = (\n prop: [string, unknown],\n): prop is [keyof typeof customOverwrites, customOverWriteValues] => prop[0] in customOverwrites;\nexport const isMediaQuery = (prop: [string, unknown]): prop is [keyof typeof media, Record<string, unknown>] =>\n prop[0] in media;",
"score": 0.5132400393486023
},
{
"filename": "src/theme/breakpoints.ts",
"retrieved_chunk": "};\ntype Media = CreateMedia<typeof DEFAULT_BREAKPOINTS>;\nconst media = objectEntries(DEFAULT_BREAKPOINTS).reduce(\n (prevValue, [breakpointKey, breakpointValue]) => ({\n ...prevValue,\n [`$${breakpointKey}`]: `@media screen and (min-width: ${breakpointValue})`,\n }),\n {} as Media,\n);\nexport default media;",
"score": 0.5060580372810364
}
] | typescript | export const prefixedPseudoElements = PSEUDO_ELEMENTS.map(pseudoEle => pseudoEle.replace('::', PROP_PREFIX)); |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output | = dateDisplayFormat.toString(); |
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}",
"score": 0.7106316685676575
},
{
"filename": "src/types.ts",
"retrieved_chunk": "type NumberSpecific = Merge<\n\tCommonValues<DateTokenType.number>,\n\t{\n\t\t/**\n\t\t * The minimum ammount of digits when displaying the date\n\t\t */\n\t\tminLeght: number;\n\t\tdisplayWhenZero: boolean;\n\t\thideSign: boolean;\n\t}",
"score": 0.7071197032928467
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.7028874754905701
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 0.6941474676132202
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn {\n\t\tname: \"\",\n\t\ttype: DateTokenType.string,\n\t\tdictionary: [\"\"],\n\t\tformatting: [],\n\t\t...defaultValue,\n\t};\n}\n/**\n * Narrow type down to specific subtype for DateTokenConfigurations.",
"score": 0.6924096345901489
}
] | typescript | = dateDisplayFormat.toString(); |
import { SETTINGS_DEFAULT } from "~/settings";
import { FnGetRangeData } from "./rangeData";
import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData";
import type { App, CachedMetadata, TFile } from "obsidian";
import type { Merge } from "ts-essentials";
/**
* @author https://stackoverflow.com/a/69756175
*/
export type PickByType<T, Value> = {
[P in keyof T as T[P] extends Value | undefined ? P : never]: T[P];
};
export type AutoTimelineSettings = typeof SETTINGS_DEFAULT;
/**
* The main bundle of data needed to build a timeline.
*/
export interface MarkdownCodeBlockTimelineProcessingContext {
/**
* Obsidian application context.
*/
app: App;
/**
* The plugins settings
*/
settings: AutoTimelineSettings;
/**
* The formatted metadata of a single note.
*/
cachedMetadata: CachedMetadata;
/**
* The file data of a single note.
*/
file: TFile;
/**
* The filepath of a single timeline.
*/
timelineFile: string;
/**
* Shorthand access to HTMLElements for the range timelines and the card list.
*/
elements: {
timelineRootElement: HTMLElement;
cardListRootElement: HTMLElement;
};
}
/**
* The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.
*/
export type CompleteCardContext = Exclude<
Awaited<ReturnType<typeof getDataFromNoteMetadata>>,
undefined
>;
/**
* The context extracted from a single note to create a single card in the timeline.
*/
export type CardContent = Awaited<ReturnType<FnExtractCardData>>;
/**
* The needed data to compute a range in a single timeline.
*/
export type | Range = ReturnType<FnGetRangeData>[number]; |
/**
* An abstract representation of a fantasy date.
* Given the fickle nature of story telling and how people will literally almost never stick to standard date formats
* We'll organise the dates in segments, let's take for example our human callendar
* The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to
* `[year, month, day]`
* Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates.
* The only major limitation to this system is that all the dates must respect the same system.
*/
export type AbstractDate = number[];
/**
* Before formatting an abstract date, the end user can configure it's output display
* This DateToken type helps to determine what's the nature of a given token
* E.g. should it be displayed as a number or as a string ?
*/
export enum DateTokenType {
number = "NUMBER",
string = "STRING",
}
export const availableDateTokenTypeArray = Object.values(DateTokenType);
export enum Condition {
Greater = "GREATER",
Less = "LESS",
Equal = "EQUAL",
NotEqual = "NOTEQUAL",
GreaterOrEqual = "GREATEROREQUAL",
LessOrEqual = "LESSOREQUAL",
}
export const availableConditionArray = Object.values(Condition);
export type Evaluation<T extends number = number> = {
condition: Condition;
value: T;
};
export type AdditionalDateFormatting<T extends number = number> = {
evaluations: Evaluation<T>[];
/**
* Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.
*/
conditionsAreExclusive: boolean;
/**
* Use `{value}` to include the pre-formated output of the numerical value held.
*/
format: string;
};
/**
* The data used to compute the output of an abstract date based on it's type
*/
type CommonValues<T extends DateTokenType> = {
name: string;
type: T;
formatting: AdditionalDateFormatting[];
};
export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =
T extends DateTokenType.number
? NumberSpecific
: T extends DateTokenType.string
? StringSpecific
: StringSpecific | NumberSpecific;
/**
* Number typed date token.
*/
type NumberSpecific = Merge<
CommonValues<DateTokenType.number>,
{
/**
* The minimum ammount of digits when displaying the date
*/
minLeght: number;
displayWhenZero: boolean;
hideSign: boolean;
}
>;
/**
* String typed date token.
*/
type StringSpecific = Merge<
CommonValues<DateTokenType.string>,
{
/**
* The dictionary reference for the token
*/
dictionary: string[];
}
>;
| src/types.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * Will compute all the data needed to build ranges in the timeline.\n *\n * @param collection - The complete collection of relevant data gathered from notes.\n * @returns the needed data to build ranges in the timeline.\n */\nexport function getAllRangeData(collection: CompleteCardContext[]) {\n\tif (!collection.length) return [];\n\treturn collection.reduce(\n\t\t(accumulator, relatedCardData, index) => {\n\t\t\tconst {",
"score": 0.8216111660003662
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.8201135993003845
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tcontext,\n\t} as const;\n}\n/**\n * Provides additional context for the creation cards in the DOM but reads it from the body\n *\n * @param body - The extracted body for a single event card.\n * @param context - Timeline generic context.\n * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.",
"score": 0.8170841932296753
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "/**\n * Extract the first image from the raw markdown in a note.\n *\n * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the URL of the image to be displayed in a card or null if none where found.\n */\nexport function getImageUrlFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext",
"score": 0.8160549402236938
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "/**\n * Format the body string of the note data for a single card.\n *\n * @param body - The body string parsed earlier.\n * @returns The formated string ready to be displayed.\n */\nexport function formatBodyForCard(body?: string | null): string {\n\tif (!body) return \"No body for this note :(\";\n\t// Remove external image links\n\treturn (",
"score": 0.8150189518928528
}
] | typescript | Range = ReturnType<FnGetRangeData>[number]; |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if | (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { |
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " */\nexport function getTagsFromMetadataOrTagObject(\n\tsettings: AutoTimelineSettings,\n\tmetaData: Omit<FrontMatterCache, \"position\">,\n\ttags?: TagCache[]\n): string[] {\n\tlet output = [] as string[];\n\tconst timelineArray = metaData[settings.metadataKeyEventTimelineTag];\n\tif (isDefinedAsArray(timelineArray))\n\t\toutput = timelineArray.filter(isDefinedAsString);",
"score": 0.740204930305481
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "export function applyConditionBasedFormatting(\n\tformatedDate: string,\n\tdate: number,\n\t{ formatting }: DateTokenConfiguration,\n\tapplyAdditonalConditionFormatting: AutoTimelineSettings[\"applyAdditonalConditionFormatting\"]\n): string {\n\tif (!applyAdditonalConditionFormatting) return formatedDate;\n\treturn formatting.reduce(\n\t\t(output, { format, conditionsAreExclusive, evaluations }) => {\n\t\t\tconst evaluationRestult = (",
"score": 0.7391883134841919
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": " * @returns the formated token.\n */\nfunction formatStringDateToken(\n\tdatePart: number,\n\t{ dictionary }: DateTokenConfiguration<DateTokenType.string>\n): string {\n\treturn dictionary[datePart];\n}",
"score": 0.7291190028190613
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " *\n * @param value - Date token configuration.\n * @returns typeguard.\n */\nexport function dateTokenConfigurationIsTypeString(\n\tvalue: DateTokenConfiguration\n): value is DateTokenConfiguration<DateTokenType.string> {\n\treturn value.type === DateTokenType.string;\n}\n/**",
"score": 0.727957010269165
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 0.7259553670883179
}
] | typescript | (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) { |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
| const configuration = dateTokenConfiguration.find(
({ name }) => name === token
); |
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);",
"score": 0.786554753780365
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.7705590128898621
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)",
"score": 0.7575781941413879
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 0.7534434199333191
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 0.7335941791534424
}
] | typescript | const configuration = dateTokenConfiguration.find(
({ name }) => name === token
); |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
| !isDefined(matches.groups.value)
)
return {}; |
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t} = app;\n\tconst override = metadata?.[metadataKeyEventPictureOverride];\n\tif (override) return override;\n\tconst internalLinkMatch = rawFileText.match(/!\\[\\[(?<src>.*)\\]\\]/);\n\tconst matchs =\n\t\tinternalLinkMatch || rawFileText.match(/!\\[.*\\]\\((?<src>.*)\\)/);\n\tif (!matchs || !matchs.groups || !matchs.groups.src) return null;\n\tif (internalLinkMatch) {\n\t\t// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295\n\t\tconst file = getFirstLinkpathDest.bind(app.metadataCache)(",
"score": 0.7545533776283264
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);",
"score": 0.6951264142990112
},
{
"filename": "src/composable/hasSlot.ts",
"retrieved_chunk": "\treturn slot(slotProps).some((vnode: VNode) => {\n\t\tif (vnode.type === Comment) return false;\n\t\tif (Array.isArray(vnode.children) && !vnode.children.length)\n\t\t\treturn false;\n\t\treturn (\n\t\t\tvnode.type !== Text ||\n\t\t\t(typeof vnode.children === \"string\" && vnode.children.trim() !== \"\")\n\t\t);\n\t});\n}",
"score": 0.6903840899467468
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 0.6687930822372437
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 0.6677675247192383
}
] | typescript | !isDefined(matches.groups.value)
)
return {}; |
import {
isDefined,
findLastIndex,
lerp,
inLerp,
getChildAtIndexInHTMLElement,
compareAbstractDates,
} from "~/utils";
import type { CompleteCardContext, AbstractDate } from "~/types";
/**
* Will compute all the data needed to build ranges in the timeline.
*
* @param collection - The complete collection of relevant data gathered from notes.
* @returns the needed data to build ranges in the timeline.
*/
export function getAllRangeData(collection: CompleteCardContext[]) {
if (!collection.length) return [];
return collection.reduce(
(accumulator, relatedCardData, index) => {
const {
context: {
elements: { timelineRootElement, cardListRootElement },
},
cardData: { startDate, endDate },
} = relatedCardData;
if (!isDefined(startDate) || !isDefined(endDate))
return accumulator;
if (
endDate !== true &&
compareAbstractDates(endDate, startDate) < 0
)
return accumulator;
const timelineLength = timelineRootElement.offsetHeight;
const targetCard = cardListRootElement.children.item(
index
) as HTMLElement | null;
// Error handling but should not happen
if (!targetCard) return accumulator;
const cardRelativeTopPosition = targetCard.offsetTop;
let targetPosition: number;
if (endDate === true) targetPosition = timelineLength;
else
targetPosition = findEndPositionForDate(
endDate,
collection.slice(index),
timelineLength,
cardListRootElement,
index
);
accumulator.push({
relatedCardData: {
...relatedCardData,
cardData: {
...relatedCardData.cardData,
endDate,
startDate,
},
},
targetPosition,
cardRelativeTopPosition,
index,
} as const);
return accumulator;
},
[] as {
readonly relatedCardData: CompleteCardContext & {
cardData: CompleteCardContext["cardData"] & {
| startDate: AbstractDate; |
endDate: AbstractDate | true;
};
};
readonly index: number;
readonly targetPosition: number;
readonly cardRelativeTopPosition: number;
}[]
);
}
export type FnGetRangeData = typeof getAllRangeData;
/**
* Finds the end position in pixel relative to the top of the timeline root element for the give endDate of a range.
*
* @param date - The target endDate to position on the timeline.
* @param collection - The collection of cards part of the same timeline.
* @param timelineLength - The length in pixel of the timeline.
* @param rootElement - The root HTMLElement of the cardList.
* @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.
* @returns The expected position relative to the top of the timeline container for this date range.
*/
export function findEndPositionForDate(
date: AbstractDate,
collection: CompleteCardContext[],
timelineLength: number,
rootElement: HTMLElement,
indexOffset: number
): number {
if (collection.length <= 1) return timelineLength;
try {
const { start, end } = findBoundaries(
date,
collection,
rootElement,
indexOffset
);
const [inLerpStart, inLerpEnd, targetInLerpDate] = getInLerpValues(
start.date,
end.date,
date
);
const t = inLerp(inLerpStart, inLerpEnd, targetInLerpDate);
return lerp(start.top, end.top, t);
} catch (_) {
return timelineLength;
}
}
/**
* Gets the values to compute the inlerp needed for range gutter renders.
*
* @param a - The start date
* @param b - The end date
* @param c - The date in between
* @returns the first non equal member of a - b when compared from left to right, also returns the same member from c.
*/
export function getInLerpValues(
a: AbstractDate,
b: AbstractDate,
c: AbstractDate
): [number, number, number] {
for (let index = 0; index < a.length; index++) {
if (a[index] === b[index]) continue;
return [a[index], b[index], c[index]];
}
return [0, 1, 1];
}
type Boundary = { date: AbstractDate; top: number };
/**
* Find the position of the last card having a lower start date and the first card with a higher start date relative to the endDate of the evaluated range.
*
* @param date - The target endDate to position on the timeline.
* @param collection - The collection of cards part of the same timeline.
* @param rootElement - The root HTMLElement of the cardList.
* @param indexOffset - Since the date is already sorted by date we can save a little time by skipping all the elements before.
* @returns The start and end boundaries of the target end date.
*/
export function findBoundaries(
date: AbstractDate,
collection: CompleteCardContext[],
rootElement: HTMLElement,
indexOffset: number
): { start: Boundary; end: Boundary } {
const firstOverIndex = collection.findIndex(({ cardData: { startDate } }) =>
isDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false
);
if (firstOverIndex === -1)
throw new Error(
"No first over found - Can't draw range since there are no other two start date to referrence it's position"
);
const firstLastUnderIndex = findLastIndex(
collection,
({ cardData: { startDate } }) =>
isDefined(startDate)
? compareAbstractDates(startDate, date) <= 0
: false
);
if (firstLastUnderIndex === -1)
throw new Error(
"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members"
);
const lastUnderIndex = collection.findIndex(
({ cardData: { startDate } }, index) => {
return (
compareAbstractDates(
startDate,
collection[firstLastUnderIndex].cardData.startDate
) === 0
);
}
);
if (lastUnderIndex === -1)
throw new Error(
"No last under found - Can't draw range since there are no other two start date to referrence it's position"
);
const startElement = getChildAtIndexInHTMLElement(
rootElement,
lastUnderIndex + indexOffset
);
const startDate = collection[lastUnderIndex].cardData
.startDate as AbstractDate;
const startIsMoreThanOneCardAway = lastUnderIndex > 1;
const shouldOffsetStartToBottomOfCard =
startIsMoreThanOneCardAway &&
compareAbstractDates(startDate, date) !== 0;
return {
start: {
top:
startElement.offsetTop +
(shouldOffsetStartToBottomOfCard
? startElement.innerHeight
: 0),
date: startDate,
},
end: {
top: getChildAtIndexInHTMLElement(
rootElement,
firstOverIndex + indexOffset
).offsetTop,
date: collection[firstOverIndex].cardData.startDate as AbstractDate,
},
};
}
| src/rangeData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\tconst score = compareAbstractDates(a, b);\n\t\t\t\tif (score) return score;\n\t\t\t\treturn compareAbstractDates(aE, bE);\n\t\t\t}\n\t\t);\n\t\tcardDataTime();\n\t\tconst cardRenderTime = measureTime(\"Card Render\");\n\t\tevents.forEach(({ context, cardData }) =>\n\t\t\tcreateCardFromBuiltContext(context, cardData)\n\t\t);",
"score": 0.7516664266586304
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\tawait getDataFromNoteBody(body, context, tagsToFind)\n\t\t\t).filter(isDefined);\n\t\t\tif (!inlineEvents.length) continue;\n\t\t\tevents.push(...inlineEvents);\n\t\t}\n\t\tevents.sort(\n\t\t\t(\n\t\t\t\t{ cardData: { startDate: a, endDate: aE } },\n\t\t\t\t{ cardData: { startDate: b, endDate: bE } }\n\t\t\t) => {",
"score": 0.7364248037338257
},
{
"filename": "src/types.ts",
"retrieved_chunk": "\t\ttimelineRootElement: HTMLElement;\n\t\tcardListRootElement: HTMLElement;\n\t};\n}\n/**\n * The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.\n */\nexport type CompleteCardContext = Exclude<\n\tAwaited<ReturnType<typeof getDataFromNoteMetadata>>,\n\tundefined",
"score": 0.714913010597229
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 0.7103546857833862
},
{
"filename": "src/types.ts",
"retrieved_chunk": "type NumberSpecific = Merge<\n\tCommonValues<DateTokenType.number>,\n\t{\n\t\t/**\n\t\t * The minimum ammount of digits when displaying the date\n\t\t */\n\t\tminLeght: number;\n\t\tdisplayWhenZero: boolean;\n\t\thideSign: boolean;\n\t}",
"score": 0.7098290920257568
}
] | typescript | startDate: AbstractDate; |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
| const prioArray = dateParserGroupPriority.split(","); |
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn {\n\t\tname: \"\",\n\t\ttype: DateTokenType.string,\n\t\tdictionary: [\"\"],\n\t\tformatting: [],\n\t\t...defaultValue,\n\t};\n}\n/**\n * Narrow type down to specific subtype for DateTokenConfigurations.",
"score": 0.7066135406494141
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tmarkdownBlockTagsToFindSeparator: \",\",\n\tdateParserRegex: \"(?<year>-?[0-9]*)-(?<month>-?[0-9]*)-(?<day>-?[0-9]*)\",\n\tdateParserGroupPriority: \"year,month,day\",\n\tdateDisplayFormat: \"{day}/{month}/{year}\",\n\tlookForTagsForTimeline: false,\n\tlookForInlineEventsInNotes: true,\n\tapplyAdditonalConditionFormatting: true,\n\tdateTokenConfiguration: [\n\t\tcreateNumberDateTokenConfiguration({ name: \"year\", minLeght: 4 }),\n\t\tcreateNumberDateTokenConfiguration({ name: \"month\" }),",
"score": 0.7029867172241211
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\tif (!stringValue) return undefined;\n\treturn parseAbstractDate(\n\t\tgroupsToCheck,\n\t\tstringValue,\n\t\tsettings.dateParserRegex\n\t);\n}",
"score": 0.7025077939033508
},
{
"filename": "src/types.ts",
"retrieved_chunk": "type NumberSpecific = Merge<\n\tCommonValues<DateTokenType.number>,\n\t{\n\t\t/**\n\t\t * The minimum ammount of digits when displaying the date\n\t\t */\n\t\tminLeght: number;\n\t\tdisplayWhenZero: boolean;\n\t\thideSign: boolean;\n\t}",
"score": 0.6835220456123352
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 0.6751018762588501
}
] | typescript | const prioArray = dateParserGroupPriority.split(","); |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
({ name }) => name === token
);
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
| applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string { |
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn isDefined(value) && value instanceof Object;\n}\n/**\n * Shorthand to quickly get a well typed number date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.number> - A well typed date token configuration object.\n */\nexport function createNumberDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.number>> = {}",
"score": 0.8371590375900269
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];\nconst acceptedSettingsOverride = [\n\t\"dateDisplayFormat\",\n\t\"applyAdditonalConditionFormatting\",\n] as const;\n/**\n * Checks if a given string is part of the settings keys that can be overriden.\n *\n * @param value - A given settings key.\n * @returns the typeguard boolean `true` if the key is indeed overridable.",
"score": 0.8363745212554932
},
{
"filename": "src/types.ts",
"retrieved_chunk": "\tvalue: T;\n};\nexport type AdditionalDateFormatting<T extends number = number> = {\n\tevaluations: Evaluation<T>[];\n\t/**\n\t * Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.\n\t */\n\tconditionsAreExclusive: boolean;\n\t/**\n\t * Use `{value}` to include the pre-formated output of the numerical value held.",
"score": 0.8341310620307922
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": " * @param timelineFile - The file path of the timeline.\n * @param settings - The plugin's settings.\n * @returns the nessessary context to build a timeline.\n */\nexport function setupTimelineCreation(\n\tapp: App,\n\telement: HTMLElement,\n\ttimelineFile: string,\n\tsettings: AutoTimelineSettings\n) {",
"score": 0.8301181793212891
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.8290744423866272
}
] | typescript | applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string { |
import {
dateTokenConfigurationIsTypeNumber,
dateTokenConfigurationIsTypeString,
evalNumericalCondition,
} from "~/utils";
import type {
AutoTimelineSettings,
AbstractDate,
DateTokenConfiguration,
DateTokenType,
AdditionalDateFormatting,
} from "~/types";
/**
* Handy function to format an abstract date based on the current settings.
*
* @param date - Target date to format.
* @param param1 - The settings of the plugin.
* @param param1.dateDisplayFormat - The target format to displat the date in.
* @param param1.dateParserGroupPriority - The token priority list for the date format.
* @param param1.dateTokenConfiguration - The configuration for the given date format.
* @param param1.applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the formated representation of a given date based off the plugins settings.
*/
export function formatAbstractDate(
date: AbstractDate | boolean,
{
dateDisplayFormat,
dateParserGroupPriority,
dateTokenConfiguration,
applyAdditonalConditionFormatting,
}: Pick<
AutoTimelineSettings,
| "dateDisplayFormat"
| "dateParserGroupPriority"
| "dateTokenConfiguration"
| "applyAdditonalConditionFormatting"
>
): string {
if (typeof date === "boolean") return "now";
const prioArray = dateParserGroupPriority.split(",");
let output = dateDisplayFormat.toString();
prioArray.forEach((token, index) => {
const configuration = dateTokenConfiguration.find(
| ({ name }) => name === token
); |
if (!configuration)
throw new Error(
`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`
);
output = output.replace(
`{${token}}`,
applyConditionBasedFormatting(
formatDateToken(date[index], configuration),
date[index],
configuration,
applyAdditonalConditionFormatting
)
);
});
return output;
}
/**
* Shorthand to format a part of an abstract date.
*
* @param datePart - fragment of an abstract date.
* @param configuration - the configuration bound to that date token.
* @returns the formated token.
*/
export function formatDateToken(
datePart: number,
configuration: DateTokenConfiguration
): string {
if (dateTokenConfigurationIsTypeNumber(configuration))
return formatNumberDateToken(datePart, configuration);
if (dateTokenConfigurationIsTypeString(configuration))
return formatStringDateToken(datePart, configuration);
throw new Error(
`[April's not so automatic timelines] - Corrupted date token configuration, please reset settings`
);
}
/**
* This functions processes each tokens additional conditional formatting.
*
* @param formatedDate - The previously processed date token.
* @param date - The numerical value of the token.
* @param configuration - The configuration of the token.
* @param configuration.formatting - The formatting array bound to a token configuration.
* @param applyAdditonalConditionFormatting - The boolean toggle to check or not for additional condition based formattings.
* @returns the fully formated token ready to be inserted in the output string.
*/
export function applyConditionBasedFormatting(
formatedDate: string,
date: number,
{ formatting }: DateTokenConfiguration,
applyAdditonalConditionFormatting: AutoTimelineSettings["applyAdditonalConditionFormatting"]
): string {
if (!applyAdditonalConditionFormatting) return formatedDate;
return formatting.reduce(
(output, { format, conditionsAreExclusive, evaluations }) => {
const evaluationRestult = (
conditionsAreExclusive ? evaluations.some : evaluations.every
).bind(evaluations)(
({
condition,
value,
}: AdditionalDateFormatting["evaluations"][number]) =>
evalNumericalCondition(condition, date, value)
);
if (evaluationRestult) return format.replace("{value}", output);
return output;
},
formatedDate
);
}
/**
* Used to quickly format a fragment of an abstract date based off a number typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A numerical date token configuration to apply.
* @param param1.minLeght - the minimal length of a numerical date input.
* @param param1.hideSign - if `true` the date part will be passed to `Math.abs` before anu further formatting.
* @returns the formated token.
*/
function formatNumberDateToken(
datePart: number,
{ minLeght, hideSign }: DateTokenConfiguration<DateTokenType.number>
): string {
let stringifiedToken = Math.abs(datePart).toString();
if (minLeght < 0) return stringifiedToken;
while (stringifiedToken.length < minLeght)
stringifiedToken = "0" + stringifiedToken;
if (!hideSign && datePart < 0) stringifiedToken = `-${stringifiedToken}`;
return stringifiedToken;
}
/**
* Used to quickly format a fragment of an abstract date based off a string typed date token configuration.
*
* @param datePart - fragment of an abstract date.
* @param param1 - A string typed date token configuration to apply.
* @param param1.dictionary - the relation dictionary for a date string typed token.
* @returns the formated token.
*/
function formatStringDateToken(
datePart: number,
{ dictionary }: DateTokenConfiguration<DateTokenType.string>
): string {
return dictionary[datePart];
}
| src/abstractDateFormatting.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": "\tmetadataString: string,\n\treg: RegExp | string\n): AbstractDate | undefined {\n\tconst matches = metadataString.match(reg);\n\tif (!matches || !matches.groups) return undefined;\n\tconst { groups } = matches;\n\tconst output = groupsToCheck.reduce((accumulator, groupName) => {\n\t\tconst value = Number(groups[groupName]);\n\t\t// In the case of a faulty regex given by the user in the settings\n\t\tif (!isNaN(value)) accumulator.push(value);",
"score": 0.786554753780365
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.7705590128898621
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)",
"score": 0.7575781941413879
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 0.7534434199333191
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 0.7335941791534424
}
] | typescript | ({ name }) => name === token
); |
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CompleteCardContext,
} from "~/types";
import { parse } from "yaml";
import {
getAbstractDateFromMetadata,
getBodyFromContextOrDocument,
getImageUrlFromContextOrDocument,
getTagsFromMetadataOrTagObject,
} from "./cardDataExtraction";
/**
* A un-changeable key used to check if a note is eligeable for render.
*/
const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"];
/**
* Provides additional context for the creation cards in the DOM.
*
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteMetadata(
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
) {
const { cachedMetadata, settings } = context;
const { frontmatter: metaData, tags } = cachedMetadata;
if (!metaData) return undefined;
if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))
return undefined;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
metaData,
tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;
return {
cardData: await extractCardData(context),
context,
} as const;
}
/**
* Provides additional context for the creation cards in the DOM but reads it from the body
*
* @param body - The extracted body for a single event card.
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteBody(
body: string | undefined | null,
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
): Promise<CompleteCardContext[]> {
const { settings } = context;
if (!body) return [];
const inlineEventBlockRegExp = new RegExp(
`%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`,
"gi"
);
const originalFrontmatter = context.cachedMetadata.frontmatter;
const matches = body.match(inlineEventBlockRegExp);
if (!matches) return [];
matches.unshift();
const output: CompleteCardContext[] = [];
for (const block of matches) {
const sanitizedBlock = block.split("\n");
sanitizedBlock.shift();
sanitizedBlock.pop();
const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao
// Replace frontmatter with newly built fake one. Just to re-use all the existing code.
context.cachedMetadata.frontmatter = fakeFrontmatter;
| if (!isDefinedAsObject(fakeFrontmatter)) continue; |
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
fakeFrontmatter,
context.cachedMetadata.tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;
const matchPositionInBody = body.indexOf(block);
output.push({
cardData: await extractCardData(
context,
matchPositionInBody !== -1
? body.slice(matchPositionInBody + block.length)
: undefined
),
context,
});
}
context.cachedMetadata.frontmatter = originalFrontmatter;
return output;
}
/**
* Checks if the extracted tags match at least one of the tags to find.
*
* @param timelineTags - The extracted tags from the note.
* @param tagsToFind - The tags to find.
* @returns `true` if valid.
*/
function extractedTagsAreValid(
timelineTags: string[],
tagsToFind: string[]
): boolean {
return timelineTags.some((tag) => tagsToFind.includes(tag));
}
/**
* Get the content of a card from a note. This function will parse the raw text content of a note and format it.
*
* @param context - Timeline generic context.
* @param rawFileContent - If you already have it, will avoid reading the file again.
* @returns The extracted data to create a card from a note.
*/
export async function extractCardData(
context: MarkdownCodeBlockTimelineProcessingContext,
rawFileContent?: string
) {
const { file, cachedMetadata: c, settings } = context;
const fileTitle =
c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename;
rawFileContent = rawFileContent || (await file.vault.cachedRead(file));
return {
title: fileTitle as string,
body: getBodyFromContextOrDocument(rawFileContent, context),
imageURL: getImageUrlFromContextOrDocument(rawFileContent, context),
startDate: getAbstractDateFromMetadata(
context,
settings.metadataKeyEventStartDate
),
endDate:
getAbstractDateFromMetadata(
context,
settings.metadataKeyEventEndDate
) ??
(isDefined(
getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean")
)
? true
: undefined),
} as const;
}
export type FnExtractCardData = typeof extractCardData;
| src/cardData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treadonly tagsToFind: string[];\n\treadonly settingsOverride: Partial<AutoTimelineSettings>;\n} {\n\tconst sourceEntries = source.split(\"\\n\");\n\tif (!source.length)\n\t\treturn { tagsToFind: [] as string[], settingsOverride: {} } as const;\n\tconst tagsToFind = sourceEntries[0]\n\t\t.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)\n\t\t.map((e) => e.trim());\n\tsourceEntries.shift();",
"score": 0.7412369847297668
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t\tsettings: { metadataKeyEventBodyOverride },\n\t} = context;\n\tconst overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;\n\tif (!rawFileText.length || overrideBody) return overrideBody;\n\tconst rawTextArray = rawFileText.split(\"\\n\");\n\trawTextArray.shift();\n\tconst processedArray = rawTextArray.slice(rawTextArray.indexOf(\"---\") + 1);\n\tconst finalString = processedArray.join(\"\\n\").trim();\n\treturn finalString;\n}",
"score": 0.7196881771087646
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst cardDataTime = measureTime(\"Data fetch\");\n\t\tconst events: CompleteCardContext[] = [];\n\t\tfor (const context of creationContext) {\n\t\t\tconst baseData = await getDataFromNoteMetadata(context, tagsToFind);\n\t\t\tif (isDefined(baseData)) events.push(baseData);\n\t\t\tif (!finalSettings.lookForInlineEventsInNotes) continue;\n\t\t\tconst body =\n\t\t\t\tbaseData?.cardData.body ||\n\t\t\t\t(await context.file.vault.cachedRead(context.file));\n\t\t\tconst inlineEvents = (",
"score": 0.7149384021759033
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 0.6833386421203613
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\t| (T extends \"string\" ? string : T extends \"number\" ? number : boolean)\n\t| undefined {\n\t// Bail if no formatter object or if the key is missing\n\tif (!cachedMetadata.frontmatter) return undefined;\n\treturn typeof cachedMetadata.frontmatter[key] === type\n\t\t? cachedMetadata.frontmatter[key]\n\t\t: undefined;\n}\n/**\n * Typeguard to check if a value is indeed defined.",
"score": 0.6684032678604126
}
] | typescript | if (!isDefinedAsObject(fakeFrontmatter)) continue; |
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { getClientIp } from "./utils";
import { NextRequest } from "next/server";
import {
upstashToken,
upstashUrl,
enableUpstash,
upstashBanEnabled,
upstashBanDuration,
maxRequests,
requestsWindow,
} from "@/configs/upstash";
const isValidUpstash = () => {
if (!upstashUrl) {
console.error("UPSTASH_URL is missing from your environment variables.");
}
if (!upstashToken) {
console.error("UPSTASH_TOKEN is missing from your environment variables.");
}
return upstashUrl !== "" && upstashToken != "";
};
export const redisClient = new Redis({
url: upstashUrl,
token: upstashToken,
});
export const ratelimit = new Ratelimit({
redis: redisClient,
limiter: Ratelimit.slidingWindow(maxRequests, requestsWindow),
});
export const isRatelimited = async (request: NextRequest) => {
if (!enableUpstash) return false;
// Check if upstash variables are set correctly
const validUpstash = isValidUpstash();
if (!validUpstash) return false;
try {
const | identifier = getClientIp(request); |
if (!identifier) return false;
const result = await ratelimit.limit(identifier);
if (result.success) return false;
// Ban user if ratelimit exceeded
if (upstashBanEnabled) {
await redisClient.setex(
`ban:${identifier}`,
upstashBanDuration,
"banned"
);
}
return true;
} catch (error: any) {
console.error(error.message);
return false;
}
};
| src/lib/rate-limiter.ts | riad-azz-instagram-video-downloader-78513ff | [
{
"filename": "src/middleware.ts",
"retrieved_chunk": " }\n if (requestPath.startsWith(\"/api\") && enableServerAPI) {\n const isLimited = await isRatelimited(request);\n if (isLimited) {\n const banDuration = Math.floor(upstashBanDuration / 60 / 60); // Ban duration in hours\n return NextResponse.json(\n {\n error: `Too many requests, you have been banned for ${banDuration} hours.`,\n },\n { status: 429 }",
"score": 0.8342903256416321
},
{
"filename": "src/lib/instagram/instagramScraper.ts",
"retrieved_chunk": " };\n return videoJson;\n};\nexport const fetchFromPage = async (postUrl: string, timeout: number = 0) => {\n const headers = getHeaders();\n if (!enableScraper) {\n console.log(\"Instagram Scraper is disabled in @config/instagram\");\n return null;\n }\n const response = await makeHttpRequest<string>({",
"score": 0.8146300315856934
},
{
"filename": "src/app/api/instagram/route.ts",
"retrieved_chunk": " const { searchParams } = new URL(request.url);\n const url: string | null = searchParams.get(\"url\");\n let postId;\n try {\n postId = getPostId(url);\n } catch (error: any) {\n return handleError(error);\n }\n try {\n const postJson = await fetchPostJson(postId);",
"score": 0.7962353229522705
},
{
"filename": "src/components/instagram/InstagramForm.tsx",
"retrieved_chunk": "};\nconst fetchVideo = async (postUrl: string) => {\n const response: APIResponse<VideoInfo> = await fetchVideoInfoAction(postUrl);\n if (response.status === \"error\") {\n throw new ClientException(response.message);\n }\n const { filename, videoUrl } = response.data;\n await downloadVideo(filename, videoUrl);\n return true;\n};",
"score": 0.779704213142395
},
{
"filename": "src/lib/instagram/instagramAPI.ts",
"retrieved_chunk": " }\n const formattedJson = formatGuestJson(json);\n return formattedJson;\n};\nexport const fetchFromAPI = async (postUrl: string, timeout: number = 0) => {\n const jsonAsGuest = await fetchAsGuest(postUrl, timeout);\n if (jsonAsGuest) return jsonAsGuest;\n return null;\n};",
"score": 0.779645562171936
}
] | typescript | identifier = getClientIp(request); |
"use client";
import { useState, FormEvent } from "react";
import { DownloadButton } from "./DownloadButton";
import { Exception, ClientException } from "@/exceptions";
import { fetchVideoInfoAction } from "@/lib/instagram/actions";
import { APIResponse, VideoInfo } from "@/types";
const validateInput = (postUrl: string) => {
if (!postUrl) {
throw new ClientException("Instagram URL was not provided");
}
if (!postUrl.includes("instagram.com/")) {
throw new ClientException("Invalid URL does not contain Instagram domain");
}
if (!postUrl.startsWith("https://")) {
throw new ClientException(
'Invalid URL it should start with "https://www.instagram.com..."'
);
}
const postRegex =
/^https:\/\/(?:www\.)?instagram\.com\/p\/([a-zA-Z0-9_-]+)\/?/;
const reelRegex =
/^https:\/\/(?:www\.)?instagram\.com\/reels?\/([a-zA-Z0-9_-]+)\/?/;
if (!postRegex.test(postUrl) && !reelRegex.test(postUrl)) {
throw new ClientException("URL does not match Instagram post or reel");
}
};
const downloadVideo = async (filename: string, downloadUrl: any) => {
try {
await fetch(downloadUrl)
.then((response) => response.blob())
.then((blob) => {
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.target = "_blank";
a.href = blobUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
});
} catch (error) {
const a = document.createElement("a");
a.target = "_blank";
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
console.log(error);
}
};
const fetchVideo = async (postUrl: string) => {
const response: APIResponse<VideoInfo> = await fetchVideoInfoAction(postUrl);
if (response.status === "error") {
throw new ClientException(response.message);
}
const { filename, videoUrl } = response.data;
await downloadVideo(filename, videoUrl);
return true;
};
export default function InstagramForm() {
const [postUrl, setPostUrl] = useState("");
const [errorMsg, setErrorMsg] = useState("");
const [isLoading, setIsLoading] = useState(false);
function handleError(error: any) {
if (error instanceof Exception) {
setErrorMsg(error.message);
} else {
console.error(error);
setErrorMsg(
"Something went wrong, if this problem persists contact the developer."
);
}
setIsLoading(false);
}
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setIsLoading(true);
setErrorMsg("");
try {
validateInput(postUrl);
} catch (error: any) {
return handleError(error);
}
try {
const isSuccess = await fetchVideo(postUrl);
if (isSuccess) setErrorMsg("");
} catch (error: any) {
return handleError(error);
}
setIsLoading(false);
}
return (
<>
{errorMsg !== "" && (
<div className="mb-1 text-sm text-red-500 md:text-base">{errorMsg}</div>
)}
<form
className="flex flex-col items-center gap-4 motion-safe:animate-[animate-up_1.5s_ease-in-out_1] md:flex-row md:gap-2"
onSubmit={handleSubmit}
>
<label htmlFor="url-input" className="sr-only">
instagram URL input
</label>
<input
id="url-input"
type="url"
value={postUrl}
autoFocus={true}
onChange={(e) => setPostUrl(e.target.value)}
placeholder="e.g. https://www.instagram.com/p/CGh4a0iASGS"
aria-label="Instagram video download URL input"
title="Instagram video download URL input"
className="w-full rounded border border-slate-100 px-2 py-3 placeholder-gray-400/80 drop-shadow-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-none dark:bg-gray-700 dark:text-white dark:placeholder-gray-400"
/>
< | DownloadButton isLoading={isLoading} />
</form>
</>
); |
}
| src/components/instagram/InstagramForm.tsx | riad-azz-instagram-video-downloader-78513ff | [
{
"filename": "src/components/instagram/DownloadButton.tsx",
"retrieved_chunk": " type=\"submit\"\n className=\"inline-flex items-center gap-2 rounded border border-slate-100 bg-white px-5 py-3.5 text-sm tracking-wide drop-shadow-lg transition-transform focus:outline-none focus:ring-2 focus:ring-blue-500 active:scale-95 dark:border-none dark:bg-gray-700 max-md:w-full max-md:justify-center\"\n disabled={isLoading}\n >\n {isLoading && (\n <>\n <Icons.loading />\n <span>Fetching</span>\n </>\n )}",
"score": 0.8959013223648071
},
{
"filename": "src/components/navigation/MenuButton.tsx",
"retrieved_chunk": " className=\"order-last ml-3 inline-flex items-center rounded-lg border border-gray-300 p-2 text-sm text-gray-500 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600 md:hidden\"\n aria-controls=\"navbar-dropdown\"\n aria-expanded=\"false\"\n >\n <span className=\"sr-only\">Open navbar menu</span>\n <Icons.menu />\n </button>\n );\n};",
"score": 0.8809098601341248
},
{
"filename": "src/components/navigation/ThemeButton.tsx",
"retrieved_chunk": " <button\n title=\"Toggle Theme\"\n onClick={() => toggleTheme()}\n className=\"flex items-center justify-between rounded-lg border border-gray-300 bg-transparent p-2.5 text-sm font-medium text-gray-900 hover:bg-gray-100 dark:border-gray-600 dark:text-white dark:hover:bg-gray-700 dark:focus:ring-gray-600 md:border-0\"\n >\n <Icons.themeMode />\n </button>\n );\n};",
"score": 0.8804452419281006
},
{
"filename": "src/components/Footer.tsx",
"retrieved_chunk": "import { Icons } from \"@/components/Icons\";\nconst Footer = () => {\n return (\n <footer className=\"bg-zinc-800 text-slate-300 shadow-lg dark:bg-gray-900\">\n <div className=\"mx-auto w-full max-w-screen-xl px-4 py-2 md:flex md:items-center md:justify-between\">\n <span className=\"text-sm sm:text-center\">\n © 2023\n <a\n target=\"_blank\"\n href=\"https://github.com/riad-azz\"",
"score": 0.8717456459999084
},
{
"filename": "src/components/navigation/MobileMenuLink.tsx",
"retrieved_chunk": "}) => {\n return (\n <li>\n <Link\n href={href}\n target={target}\n className=\"flex w-full items-center gap-4 rounded-lg border border-gray-300 bg-white px-5 py-2 font-medium text-gray-900 hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-800 dark:text-white dark:hover:border-gray-600 dark:hover:bg-gray-700\"\n >\n {children}\n </Link>",
"score": 0.8638319969177246
}
] | typescript | DownloadButton isLoading={isLoading} />
</form>
</>
); |
import {
isDefinedAsString,
isDefined,
isDefinedAsArray,
getMetadataKey,
parseAbstractDate,
} from "~/utils";
import { FrontMatterCache, TagCache, TFile } from "obsidian";
import type {
AutoTimelineSettings,
AbstractDate,
MarkdownCodeBlockTimelineProcessingContext,
} from "~/types";
/**
* Returns a list of tags based off plugin settings, note frontmatter and note tags.
*
* @param settings - The plugins settings.
* @param metaData - The frontematter cache.
* @param tags - Potencial tags.
* @returns A list of tags to look for in a note.
*/
export function getTagsFromMetadataOrTagObject(
settings: AutoTimelineSettings,
metaData: Omit<FrontMatterCache, "position">,
tags?: TagCache[]
): string[] {
let output = [] as string[];
const timelineArray = metaData[settings.metadataKeyEventTimelineTag];
if (isDefinedAsArray(timelineArray))
output = timelineArray.filter(isDefinedAsString);
// Breakout earlier if we don't check the tags
if (!settings.lookForTagsForTimeline) return output;
if (isDefinedAsArray(tags))
output = output.concat(tags.map(({ tag }) => tag.substring(1)));
// Tags in the frontmatter
const metadataInlineTags = metaData.tags;
if (!isDefined(metadataInlineTags)) return output;
if (isDefinedAsString(metadataInlineTags))
output = output.concat(
metadataInlineTags.split(",").map((e) => e.trim())
);
if (isDefinedAsArray(metadataInlineTags))
output = output.concat(metadataInlineTags.filter(isDefinedAsString));
// .substring called to remove the initial `#` in the notes tags
return output;
}
/**
* Extract the body from the raw text of a note.
* After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the body of a given card or null if none was found.
*/
export function getBodyFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
settings: { | metadataKeyEventBodyOverride },
} = context; |
const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;
if (!rawFileText.length || overrideBody) return overrideBody;
const rawTextArray = rawFileText.split("\n");
rawTextArray.shift();
const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1);
const finalString = processedArray.join("\n").trim();
return finalString;
}
/**
* Extract the first image from the raw markdown in a note.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the URL of the image to be displayed in a card or null if none where found.
*/
export function getImageUrlFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
file: currentFile,
app,
settings: { metadataKeyEventPictureOverride },
} = context;
const {
vault,
metadataCache: { getFirstLinkpathDest },
} = app;
const override = metadata?.[metadataKeyEventPictureOverride];
if (override) return override;
const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/);
const matchs =
internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/);
if (!matchs || !matchs.groups || !matchs.groups.src) return null;
if (internalLinkMatch) {
// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295
const file = getFirstLinkpathDest.bind(app.metadataCache)(
matchs.groups.src,
currentFile.path
) satisfies TFile | null;
if (file instanceof TFile) return vault.getResourcePath(file);
// Thanks https://github.com/joethei
return null;
} else return encodeURI(matchs.groups.src);
}
/**
* Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it
*
* @param param0 - Timeline generic context.
* @param param0.cachedMetadata - The cached metadata from a note.
* @param param0.settings - the plugin's settings.
* @param key - The target lookup key in the notes metadata object.
* @returns the abstract date representation or undefined.
*/
export function getAbstractDateFromMetadata(
{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,
key: string
): AbstractDate | undefined {
const groupsToCheck = settings.dateParserGroupPriority.split(",");
const numberValue = getMetadataKey(cachedMetadata, key, "number");
if (isDefined(numberValue)) {
const additionalContentForNumberOnlydate = [
...Array(Math.max(0, groupsToCheck.length - 1)),
].map(() => 0);
return [numberValue, ...additionalContentForNumberOnlydate];
}
const stringValue = getMetadataKey(cachedMetadata, key, "string");
if (!stringValue) return undefined;
return parseAbstractDate(
groupsToCheck,
stringValue,
settings.dateParserRegex
);
}
| src/cardDataExtraction.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 0.8721373677253723
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 0.8557800054550171
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t * @param element - The root element of all the timeline.\n\t * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.\n\t * @param param2.sourcePath - A string representing the fs path of a note.\n\t */\n\tasync run(\n\t\tsource: string,\n\t\telement: HTMLElement,\n\t\t{ sourcePath }: MarkdownPostProcessorContext\n\t) {\n\t\tconst runtimeTime = measureTime(\"Run time\");",
"score": 0.8291038870811462
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.8080296516418457
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst { app } = this;\n\t\tconst { tagsToFind, settingsOverride } =\n\t\t\tparseMarkdownBlockSource(source);\n\t\tconst finalSettings = { ...this.settings, ...settingsOverride };\n\t\tconst creationContext = setupTimelineCreation(\n\t\t\tapp,\n\t\t\telement,\n\t\t\tsourcePath,\n\t\t\tfinalSettings\n\t\t);",
"score": 0.7842734456062317
}
] | typescript | metadataKeyEventBodyOverride },
} = context; |
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { getClientIp } from "./utils";
import { NextRequest } from "next/server";
import {
upstashToken,
upstashUrl,
enableUpstash,
upstashBanEnabled,
upstashBanDuration,
maxRequests,
requestsWindow,
} from "@/configs/upstash";
const isValidUpstash = () => {
if (!upstashUrl) {
console.error("UPSTASH_URL is missing from your environment variables.");
}
if (!upstashToken) {
console.error("UPSTASH_TOKEN is missing from your environment variables.");
}
return upstashUrl !== "" && upstashToken != "";
};
export const redisClient = new Redis({
url: upstashUrl,
token: upstashToken,
});
export const ratelimit = new Ratelimit({
redis: redisClient,
limiter: Ratelimit.slidingWindow(maxRequests, requestsWindow),
});
export const isRatelimited = async (request: NextRequest) => {
if (!enableUpstash) return false;
// Check if upstash variables are set correctly
const validUpstash = isValidUpstash();
if (!validUpstash) return false;
try {
| const identifier = getClientIp(request); |
if (!identifier) return false;
const result = await ratelimit.limit(identifier);
if (result.success) return false;
// Ban user if ratelimit exceeded
if (upstashBanEnabled) {
await redisClient.setex(
`ban:${identifier}`,
upstashBanDuration,
"banned"
);
}
return true;
} catch (error: any) {
console.error(error.message);
return false;
}
};
| src/lib/rate-limiter.ts | riad-azz-instagram-video-downloader-78513ff | [
{
"filename": "src/middleware.ts",
"retrieved_chunk": " }\n if (requestPath.startsWith(\"/api\") && enableServerAPI) {\n const isLimited = await isRatelimited(request);\n if (isLimited) {\n const banDuration = Math.floor(upstashBanDuration / 60 / 60); // Ban duration in hours\n return NextResponse.json(\n {\n error: `Too many requests, you have been banned for ${banDuration} hours.`,\n },\n { status: 429 }",
"score": 0.8327926993370056
},
{
"filename": "src/lib/instagram/instagramScraper.ts",
"retrieved_chunk": " };\n return videoJson;\n};\nexport const fetchFromPage = async (postUrl: string, timeout: number = 0) => {\n const headers = getHeaders();\n if (!enableScraper) {\n console.log(\"Instagram Scraper is disabled in @config/instagram\");\n return null;\n }\n const response = await makeHttpRequest<string>({",
"score": 0.8096710443496704
},
{
"filename": "src/app/api/instagram/route.ts",
"retrieved_chunk": " const { searchParams } = new URL(request.url);\n const url: string | null = searchParams.get(\"url\");\n let postId;\n try {\n postId = getPostId(url);\n } catch (error: any) {\n return handleError(error);\n }\n try {\n const postJson = await fetchPostJson(postId);",
"score": 0.7951528429985046
},
{
"filename": "src/components/instagram/InstagramForm.tsx",
"retrieved_chunk": "};\nconst fetchVideo = async (postUrl: string) => {\n const response: APIResponse<VideoInfo> = await fetchVideoInfoAction(postUrl);\n if (response.status === \"error\") {\n throw new ClientException(response.message);\n }\n const { filename, videoUrl } = response.data;\n await downloadVideo(filename, videoUrl);\n return true;\n};",
"score": 0.7790634036064148
},
{
"filename": "src/lib/instagram/instagramAPI.ts",
"retrieved_chunk": " }\n const formattedJson = formatGuestJson(json);\n return formattedJson;\n};\nexport const fetchFromAPI = async (postUrl: string, timeout: number = 0) => {\n const jsonAsGuest = await fetchAsGuest(postUrl, timeout);\n if (jsonAsGuest) return jsonAsGuest;\n return null;\n};",
"score": 0.7766451835632324
}
] | typescript | const identifier = getClientIp(request); |
import {
isDefinedAsString,
isDefined,
isDefinedAsArray,
getMetadataKey,
parseAbstractDate,
} from "~/utils";
import { FrontMatterCache, TagCache, TFile } from "obsidian";
import type {
AutoTimelineSettings,
AbstractDate,
MarkdownCodeBlockTimelineProcessingContext,
} from "~/types";
/**
* Returns a list of tags based off plugin settings, note frontmatter and note tags.
*
* @param settings - The plugins settings.
* @param metaData - The frontematter cache.
* @param tags - Potencial tags.
* @returns A list of tags to look for in a note.
*/
export function getTagsFromMetadataOrTagObject(
settings: AutoTimelineSettings,
metaData: Omit<FrontMatterCache, "position">,
tags?: TagCache[]
): string[] {
let output = [] as string[];
const timelineArray = metaData[settings.metadataKeyEventTimelineTag];
if (isDefinedAsArray(timelineArray))
output = timelineArray.filter(isDefinedAsString);
// Breakout earlier if we don't check the tags
if (!settings.lookForTagsForTimeline) return output;
if (isDefinedAsArray(tags))
output = output.concat(tags.map(({ tag }) => tag.substring(1)));
// Tags in the frontmatter
const metadataInlineTags = metaData.tags;
if (!isDefined(metadataInlineTags)) return output;
if (isDefinedAsString(metadataInlineTags))
output = output.concat(
metadataInlineTags.split(",").map((e) => e.trim())
);
if (isDefinedAsArray(metadataInlineTags))
output = output.concat(metadataInlineTags.filter(isDefinedAsString));
// .substring called to remove the initial `#` in the notes tags
return output;
}
/**
* Extract the body from the raw text of a note.
* After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the body of a given card or null if none was found.
*/
export function getBodyFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
settings: { metadataKeyEventBodyOverride },
} = context;
const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;
if (!rawFileText.length || overrideBody) return overrideBody;
const rawTextArray = rawFileText.split("\n");
rawTextArray.shift();
const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1);
const finalString = processedArray.join("\n").trim();
return finalString;
}
/**
* Extract the first image from the raw markdown in a note.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the URL of the image to be displayed in a card or null if none where found.
*/
export function getImageUrlFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
file: currentFile,
app,
settings: { | metadataKeyEventPictureOverride },
} = context; |
const {
vault,
metadataCache: { getFirstLinkpathDest },
} = app;
const override = metadata?.[metadataKeyEventPictureOverride];
if (override) return override;
const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/);
const matchs =
internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/);
if (!matchs || !matchs.groups || !matchs.groups.src) return null;
if (internalLinkMatch) {
// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295
const file = getFirstLinkpathDest.bind(app.metadataCache)(
matchs.groups.src,
currentFile.path
) satisfies TFile | null;
if (file instanceof TFile) return vault.getResourcePath(file);
// Thanks https://github.com/joethei
return null;
} else return encodeURI(matchs.groups.src);
}
/**
* Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it
*
* @param param0 - Timeline generic context.
* @param param0.cachedMetadata - The cached metadata from a note.
* @param param0.settings - the plugin's settings.
* @param key - The target lookup key in the notes metadata object.
* @returns the abstract date representation or undefined.
*/
export function getAbstractDateFromMetadata(
{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,
key: string
): AbstractDate | undefined {
const groupsToCheck = settings.dateParserGroupPriority.split(",");
const numberValue = getMetadataKey(cachedMetadata, key, "number");
if (isDefined(numberValue)) {
const additionalContentForNumberOnlydate = [
...Array(Math.max(0, groupsToCheck.length - 1)),
].map(() => 0);
return [numberValue, ...additionalContentForNumberOnlydate];
}
const stringValue = getMetadataKey(cachedMetadata, key, "string");
if (!stringValue) return undefined;
return parseAbstractDate(
groupsToCheck,
stringValue,
settings.dateParserRegex
);
}
| src/cardDataExtraction.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 0.8523778915405273
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t * @param element - The root element of all the timeline.\n\t * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.\n\t * @param param2.sourcePath - A string representing the fs path of a note.\n\t */\n\tasync run(\n\t\tsource: string,\n\t\telement: HTMLElement,\n\t\t{ sourcePath }: MarkdownPostProcessorContext\n\t) {\n\t\tconst runtimeTime = measureTime(\"Run time\");",
"score": 0.8298909068107605
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " */\nexport async function getDataFromNoteBody(\n\tbody: string | undefined | null,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n): Promise<CompleteCardContext[]> {\n\tconst { settings } = context;\n\tif (!body) return [];\n\tconst inlineEventBlockRegExp = new RegExp(\n\t\t`%%${settings.noteInlineEventKey}\\n(((\\\\s|\\\\d|[a-z]|-)*):(.*)\\n)*%%`,",
"score": 0.811991274356842
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst { app } = this;\n\t\tconst { tagsToFind, settingsOverride } =\n\t\t\tparseMarkdownBlockSource(source);\n\t\tconst finalSettings = { ...this.settings, ...settingsOverride };\n\t\tconst creationContext = setupTimelineCreation(\n\t\t\tapp,\n\t\t\telement,\n\t\t\tsourcePath,\n\t\t\tfinalSettings\n\t\t);",
"score": 0.8102388381958008
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.7930589914321899
}
] | typescript | metadataKeyEventPictureOverride },
} = context; |
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client";
import { prisma } from "../../../prisma/client";
export class GetPedidoPorCpfUseCase {
async getPedidoPorCpf(numero: string): Promise<any | null> {
if (numero.length === 11) {
const clienteCpf = await prisma.cliente.findFirst({
where: {
cpf: numero
}
});
if (clienteCpf) {
const pedido = await prisma.pedido.findMany({
where: {
id_cliente: clienteCpf.id_cliente
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true
}
}
}
});
if (!pedido) {
return null;
}
const pedidosFormatados = pedido.map(( | pedido) => ({ |
numero: pedido.numero,
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
cpf_cliente: pedido.cliente.cpf,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
}));
return pedidosFormatados;
}
}
}
}
| src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 0.8750394582748413
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " status_erro: true\n }\n },\n produto: {\n select: {\n valor: true,\n quantidade: true\n }\n },\n }",
"score": 0.8369426727294922
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " id_transacao: true\n }\n },\n pedido_status: {\n select: {\n status_pedido: true,\n status_erro: true\n }\n }\n }",
"score": 0.8352423906326294
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " }\n },\n produto: {\n select: {\n nome_produto: true,\n quantidade: true,\n valor: true\n }\n }\n }",
"score": 0.7837804555892944
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " referencia: true,\n descricao: true,\n quantidade: true,\n valor: true,\n }\n },\n pagamento: {\n select: {\n tipo_pagamento: true,\n parcela: true,",
"score": 0.7808499932289124
}
] | typescript | pedido) => ({ |
import {
pedido,
pedido_status,
nota_fiscal,
pagamento,
produto,
cliente
} from '@prisma/client'
import { prisma } from '../../../prisma/client'
export class GetPedidosDataUseCase {
async allPedidosData(data: String): Promise<any[] | null> {
const pedidos = await prisma.pedido.findMany({
where: {
data_pedido_realizado: {
gte: new Date(`${data}`),
lt: new Date(`${data}T23:59:59Z`)
}
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true,
valor: true
}
}
}
})
if (!pedidos) {
return null
}
| const pedidosFormatados = pedidos.map(pedido => ({ |
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
pedido: pedido.cliente.cpf,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
// valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,
// nome_produto: pedido.produto.nome_produto,
// quantidade_produto: pedido.produto.quantidade
}))
return pedidosFormatados
}
}
| src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 0.8812016844749451
},
{
"filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts",
"retrieved_chunk": " select: {\n nome_produto: true,\n quantidade: true\n }\n }\n }\n });\n if (!pedido) {\n return null;\n }",
"score": 0.8635867834091187
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " status_erro: true\n }\n },\n produto: {\n select: {\n valor: true,\n quantidade: true\n }\n },\n }",
"score": 0.845253586769104
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " id_transacao: true\n }\n },\n pedido_status: {\n select: {\n status_pedido: true,\n status_erro: true\n }\n }\n }",
"score": 0.8344858288764954
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " referencia: true,\n descricao: true,\n quantidade: true,\n valor: true,\n }\n },\n pagamento: {\n select: {\n tipo_pagamento: true,\n parcela: true,",
"score": 0.7989959120750427
}
] | typescript | const pedidosFormatados = pedidos.map(pedido => ({ |
import { getMetadataKey, isDefined, isDefinedAsObject } from "~/utils";
import type {
MarkdownCodeBlockTimelineProcessingContext,
CompleteCardContext,
} from "~/types";
import { parse } from "yaml";
import {
getAbstractDateFromMetadata,
getBodyFromContextOrDocument,
getImageUrlFromContextOrDocument,
getTagsFromMetadataOrTagObject,
} from "./cardDataExtraction";
/**
* A un-changeable key used to check if a note is eligeable for render.
*/
const RENDER_GREENLIGHT_METADATA_KEY = ["aat-render-enabled"];
/**
* Provides additional context for the creation cards in the DOM.
*
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteMetadata(
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
) {
const { cachedMetadata, settings } = context;
const { frontmatter: metaData, tags } = cachedMetadata;
if (!metaData) return undefined;
if (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))
return undefined;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
metaData,
tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;
return {
cardData: await extractCardData(context),
context,
} as const;
}
/**
* Provides additional context for the creation cards in the DOM but reads it from the body
*
* @param body - The extracted body for a single event card.
* @param context - Timeline generic context.
* @param tagsToFind - The tags to find in a note to match the current timeline.
* @returns the context or underfined if it could not build it.
*/
export async function getDataFromNoteBody(
body: string | undefined | null,
context: MarkdownCodeBlockTimelineProcessingContext,
tagsToFind: string[]
): Promise<CompleteCardContext[]> {
const { settings } = context;
if (!body) return [];
const inlineEventBlockRegExp = new RegExp(
`%%${settings.noteInlineEventKey}\n(((\\s|\\d|[a-z]|-)*):(.*)\n)*%%`,
"gi"
);
const originalFrontmatter = context.cachedMetadata.frontmatter;
const matches = body.match(inlineEventBlockRegExp);
if (!matches) return [];
matches.unshift();
const output: CompleteCardContext[] = [];
for (const block of matches) {
const sanitizedBlock = block.split("\n");
sanitizedBlock.shift();
sanitizedBlock.pop();
const fakeFrontmatter = parse(sanitizedBlock.join("\n")); // this actually works lmao
// Replace frontmatter with newly built fake one. Just to re-use all the existing code.
context.cachedMetadata.frontmatter = fakeFrontmatter;
if (!isDefinedAsObject(fakeFrontmatter)) continue;
const timelineTags = getTagsFromMetadataOrTagObject(
settings,
fakeFrontmatter,
context.cachedMetadata.tags
);
if (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;
const matchPositionInBody = body.indexOf(block);
output.push({
cardData: await extractCardData(
context,
matchPositionInBody !== -1
? body.slice(matchPositionInBody + block.length)
: undefined
),
context,
});
}
context.cachedMetadata.frontmatter = originalFrontmatter;
return output;
}
/**
* Checks if the extracted tags match at least one of the tags to find.
*
* @param timelineTags - The extracted tags from the note.
* @param tagsToFind - The tags to find.
* @returns `true` if valid.
*/
function extractedTagsAreValid(
timelineTags: string[],
tagsToFind: string[]
): boolean {
return timelineTags.some((tag) => tagsToFind.includes(tag));
}
/**
* Get the content of a card from a note. This function will parse the raw text content of a note and format it.
*
* @param context - Timeline generic context.
* @param rawFileContent - If you already have it, will avoid reading the file again.
* @returns The extracted data to create a card from a note.
*/
export async function extractCardData(
context: MarkdownCodeBlockTimelineProcessingContext,
rawFileContent?: string
) {
const { file, cachedMetadata: c, settings } = context;
const fileTitle =
| c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename; |
rawFileContent = rawFileContent || (await file.vault.cachedRead(file));
return {
title: fileTitle as string,
body: getBodyFromContextOrDocument(rawFileContent, context),
imageURL: getImageUrlFromContextOrDocument(rawFileContent, context),
startDate: getAbstractDateFromMetadata(
context,
settings.metadataKeyEventStartDate
),
endDate:
getAbstractDateFromMetadata(
context,
settings.metadataKeyEventEndDate
) ??
(isDefined(
getMetadataKey(c, settings.metadataKeyEventEndDate, "boolean")
)
? true
: undefined),
} as const;
}
export type FnExtractCardData = typeof extractCardData;
| src/cardData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the body of a given card or null if none was found.\n */\nexport function getBodyFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext\n): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },",
"score": 0.8389642834663391
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t * @param element - The root element of all the timeline.\n\t * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.\n\t * @param param2.sourcePath - A string representing the fs path of a note.\n\t */\n\tasync run(\n\t\tsource: string,\n\t\telement: HTMLElement,\n\t\t{ sourcePath }: MarkdownPostProcessorContext\n\t) {\n\t\tconst runtimeTime = measureTime(\"Run time\");",
"score": 0.8135577440261841
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "\t\telements: { cardListRootElement },\n\t\tfile,\n\t\tsettings,\n\t}: MarkdownCodeBlockTimelineProcessingContext,\n\tcardContent: CardContent\n): void {\n\tconst { body, title, imageURL } = cardContent;\n\tconst cardBaseDiv = createElementShort(cardListRootElement, \"a\", [\n\t\t\"internal-link\",\n\t\t\"aat-card\",",
"score": 0.8056612014770508
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tconst { app } = this;\n\t\tconst { tagsToFind, settingsOverride } =\n\t\t\tparseMarkdownBlockSource(source);\n\t\tconst finalSettings = { ...this.settings, ...settingsOverride };\n\t\tconst creationContext = setupTimelineCreation(\n\t\t\tapp,\n\t\t\telement,\n\t\t\tsourcePath,\n\t\t\tfinalSettings\n\t\t);",
"score": 0.7980694770812988
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },\n\t\tfile: currentFile,\n\t\tapp,\n\t\tsettings: { metadataKeyEventPictureOverride },\n\t} = context;\n\tconst {\n\t\tvault,\n\t\tmetadataCache: { getFirstLinkpathDest },",
"score": 0.7966644763946533
}
] | typescript | c.frontmatter?.[settings.metadataKeyEventTitleOverride] ||
file.basename; |
import {
pedido,
pedido_status,
nota_fiscal,
pagamento,
produto,
cliente
} from '@prisma/client'
import { prisma } from '../../../prisma/client'
export class GetPedidosDataUseCase {
async allPedidosData(data: String): Promise<any[] | null> {
const pedidos = await prisma.pedido.findMany({
where: {
data_pedido_realizado: {
gte: new Date(`${data}`),
lt: new Date(`${data}T23:59:59Z`)
}
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true,
valor: true
}
}
}
})
if (!pedidos) {
return null
}
const pedidosFormatados = pedidos.map | (pedido => ({ |
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
pedido: pedido.cliente.cpf,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
// valor_e_parcela: `${pedido.pagamento.parcela}x - R$${pedido.produto.valor}`,
// nome_produto: pedido.produto.nome_produto,
// quantidade_produto: pedido.produto.quantidade
}))
return pedidosFormatados
}
}
| src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 0.8609008193016052
},
{
"filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts",
"retrieved_chunk": " select: {\n nome_produto: true,\n quantidade: true\n }\n }\n }\n });\n if (!pedido) {\n return null;\n }",
"score": 0.8374243974685669
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " id_transacao: true\n }\n },\n pedido_status: {\n select: {\n status_pedido: true,\n status_erro: true\n }\n }\n }",
"score": 0.8010299205780029
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " status_erro: true\n }\n },\n produto: {\n select: {\n valor: true,\n quantidade: true\n }\n },\n }",
"score": 0.7983868718147278
},
{
"filename": "src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts",
"retrieved_chunk": " numero_nota: true\n }\n },\n pagamento: {\n select: {\n tipo_pagamento: true,\n parcela: true\n }\n },\n produto: {",
"score": 0.7609409689903259
}
] | typescript | (pedido => ({ |
import {
isDefinedAsString,
isDefined,
isDefinedAsArray,
getMetadataKey,
parseAbstractDate,
} from "~/utils";
import { FrontMatterCache, TagCache, TFile } from "obsidian";
import type {
AutoTimelineSettings,
AbstractDate,
MarkdownCodeBlockTimelineProcessingContext,
} from "~/types";
/**
* Returns a list of tags based off plugin settings, note frontmatter and note tags.
*
* @param settings - The plugins settings.
* @param metaData - The frontematter cache.
* @param tags - Potencial tags.
* @returns A list of tags to look for in a note.
*/
export function getTagsFromMetadataOrTagObject(
settings: AutoTimelineSettings,
metaData: Omit<FrontMatterCache, "position">,
tags?: TagCache[]
): string[] {
let output = [] as string[];
const timelineArray = metaData[settings.metadataKeyEventTimelineTag];
if (isDefinedAsArray(timelineArray))
output = timelineArray.filter(isDefinedAsString);
// Breakout earlier if we don't check the tags
if (!settings.lookForTagsForTimeline) return output;
if (isDefinedAsArray(tags))
output = output.concat(tags.map(({ tag }) => tag.substring(1)));
// Tags in the frontmatter
const metadataInlineTags = metaData.tags;
if (!isDefined(metadataInlineTags)) return output;
if (isDefinedAsString(metadataInlineTags))
output = output.concat(
metadataInlineTags.split(",").map((e) => e.trim())
);
if (isDefinedAsArray(metadataInlineTags))
output = output.concat(metadataInlineTags.filter(isDefinedAsString));
// .substring called to remove the initial `#` in the notes tags
return output;
}
/**
* Extract the body from the raw text of a note.
* After extraction most markdown tokens will be removed and links will be sanitized aswell and wrapped into bold tags for clearner display.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the body of a given card or null if none was found.
*/
export function getBodyFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
settings: { metadataKeyEventBodyOverride },
} = context;
const overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;
if (!rawFileText.length || overrideBody) return overrideBody;
const rawTextArray = rawFileText.split("\n");
rawTextArray.shift();
const processedArray = rawTextArray.slice(rawTextArray.indexOf("---") + 1);
const finalString = processedArray.join("\n").trim();
return finalString;
}
/**
* Extract the first image from the raw markdown in a note.
*
* @param rawFileText - The text content of a obsidian note.
* @param context - Timeline generic context.
* @returns the URL of the image to be displayed in a card or null if none where found.
*/
export function getImageUrlFromContextOrDocument(
rawFileText: string,
context: MarkdownCodeBlockTimelineProcessingContext
): string | null {
const {
cachedMetadata: { frontmatter: metadata },
file: currentFile,
app,
settings: { metadataKeyEventPictureOverride },
} = context;
const {
vault,
metadataCache: { getFirstLinkpathDest },
} = app;
const override = metadata?.[metadataKeyEventPictureOverride];
if (override) return override;
const internalLinkMatch = rawFileText.match(/!\[\[(?<src>.*)\]\]/);
const matchs =
internalLinkMatch || rawFileText.match(/!\[.*\]\((?<src>.*)\)/);
if (!matchs || !matchs.groups || !matchs.groups.src) return null;
if (internalLinkMatch) {
// https://github.com/obsidianmd/obsidian-releases/pull/1882#issuecomment-1512952295
const file = getFirstLinkpathDest.bind(app.metadataCache)(
matchs.groups.src,
currentFile.path
) satisfies TFile | null;
if (file instanceof TFile) return vault.getResourcePath(file);
// Thanks https://github.com/joethei
return null;
} else return encodeURI(matchs.groups.src);
}
/**
* Given a metadata key it'll try to parse the associated data as an `AbstractDate` and return it
*
* @param param0 - Timeline generic context.
* @param param0.cachedMetadata - The cached metadata from a note.
* @param param0.settings - the plugin's settings.
* @param key - The target lookup key in the notes metadata object.
* @returns the abstract date representation or undefined.
*/
export function getAbstractDateFromMetadata(
{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,
key: string
): AbstractDate | undefined {
const groupsToCheck = | settings.dateParserGroupPriority.split(","); |
const numberValue = getMetadataKey(cachedMetadata, key, "number");
if (isDefined(numberValue)) {
const additionalContentForNumberOnlydate = [
...Array(Math.max(0, groupsToCheck.length - 1)),
].map(() => 0);
return [numberValue, ...additionalContentForNumberOnlydate];
}
const stringValue = getMetadataKey(cachedMetadata, key, "string");
if (!stringValue) return undefined;
return parseAbstractDate(
groupsToCheck,
stringValue,
settings.dateParserRegex
);
}
| src/cardDataExtraction.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.9115695953369141
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 0.8997738361358643
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 0.8895249366760254
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t * @param element - The root element of all the timeline.\n\t * @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.\n\t * @param param2.sourcePath - A string representing the fs path of a note.\n\t */\n\tasync run(\n\t\tsource: string,\n\t\telement: HTMLElement,\n\t\t{ sourcePath }: MarkdownPostProcessorContext\n\t) {\n\t\tconst runtimeTime = measureTime(\"Run time\");",
"score": 0.8615924119949341
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "/**\n * Parse a string based off user date extract settings.\n *\n * @param groupsToCheck - The token names to check.\n * @param metadataString - The actual extracted data from the frontmatter.\n * @param reg - The user defined regex to apply.\n * @returns The parsed abstract date or nothing.\n */\nexport function parseAbstractDate(\n\tgroupsToCheck: string[],",
"score": 0.8607027530670166
}
] | typescript | settings.dateParserGroupPriority.split(","); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await | getDataFromNoteMetadata(context, tagsToFind); |
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 0.7811832427978516
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 0.7438013553619385
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "\t\telements: { cardListRootElement },\n\t\tfile,\n\t\tsettings,\n\t}: MarkdownCodeBlockTimelineProcessingContext,\n\tcardContent: CardContent\n): void {\n\tconst { body, title, imageURL } = cardContent;\n\tconst cardBaseDiv = createElementShort(cardListRootElement, \"a\", [\n\t\t\"internal-link\",\n\t\t\"aat-card\",",
"score": 0.731716513633728
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t)\n\t\t\t\treturn accumulator;\n\t\t\tconst timelineLength = timelineRootElement.offsetHeight;\n\t\t\tconst targetCard = cardListRootElement.children.item(\n\t\t\t\tindex\n\t\t\t) as HTMLElement | null;\n\t\t\t// Error handling but should not happen\n\t\t\tif (!targetCard) return accumulator;\n\t\t\tconst cardRelativeTopPosition = targetCard.offsetTop;\n\t\t\tlet targetPosition: number;",
"score": 0.7250996828079224
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 0.720862865447998
}
] | typescript | getDataFromNoteMetadata(context, tagsToFind); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
| const score = compareAbstractDates(a, b); |
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 0.8323160409927368
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)",
"score": 0.8073999881744385
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 0.7919842004776001
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 0.774899959564209
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": " */\nexport function getDateText(\n\t{ startDate, endDate }: Pick<CardContent, \"startDate\" | \"endDate\">,\n\tsettings: AutoTimelineSettings\n): string {\n\tif (!isDefined(startDate)) return \"Start date missing\";\n\tconst formatedStart = formatAbstractDate(startDate, settings);\n\tif (!isDefined(endDate)) return formatedStart;\n\treturn `From ${formatedStart} to ${formatAbstractDate(endDate, settings)}`;\n}",
"score": 0.7620267868041992
}
] | typescript | const score = compareAbstractDates(a, b); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
| if (isDefined(baseData)) events.push(baseData); |
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 0.7822977304458618
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 0.72076416015625
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\t\"gi\"\n\t);\n\tconst originalFrontmatter = context.cachedMetadata.frontmatter;\n\tconst matches = body.match(inlineEventBlockRegExp);\n\tif (!matches) return [];\n\tmatches.unshift();\n\tconst output: CompleteCardContext[] = [];\n\tfor (const block of matches) {\n\t\tconst sanitizedBlock = block.split(\"\\n\");\n\t\tsanitizedBlock.shift();",
"score": 0.7076640129089355
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 0.7051784992218018
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " */\nexport function getTagsFromMetadataOrTagObject(\n\tsettings: AutoTimelineSettings,\n\tmetaData: Omit<FrontMatterCache, \"position\">,\n\ttags?: TagCache[]\n): string[] {\n\tlet output = [] as string[];\n\tconst timelineArray = metaData[settings.metadataKeyEventTimelineTag];\n\tif (isDefinedAsArray(timelineArray))\n\t\toutput = timelineArray.filter(isDefinedAsString);",
"score": 0.7010495662689209
}
] | typescript | if (isDefined(baseData)) events.push(baseData); |
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client";
import { prisma } from "../../../prisma/client";
export class GetPedidoPorNumeroUseCase {
async getPedidoPorNumero(numero: string): Promise<any | null> {
const pedido = await prisma.pedido.findFirst({
where: {
numero
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true,
telefone: true,
email: true,
endereco: true
}
}, produto: {
select: {
nome_produto: true,
referencia: true,
descricao: true,
quantidade: true,
valor: true,
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true,
id_transacao: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
}
}
});
if (!pedido) {
return null;
}
const produtosFormatados: { nome: string; referencia: string; descricao: string; quantidade: number; valor_produto: number; valor_total_produto: number; }[] = [];
pedido.produto | .forEach((produto) => { |
const produtoFormatado = {
nome: produto.nome_produto,
referencia: produto.referencia,
descricao: produto.descricao,
quantidade: produto.quantidade,
valor_produto: produto.valor,
valor_total_produto: produto.valor * produto.quantidade
};
produtosFormatados.push(produtoFormatado);
});
const moment = require('moment');
const pedidoFormatado = {
cpf: pedido.cliente.cpf,
nome: pedido.cliente.nome_completo,
contato: pedido.cliente.telefone,
email: pedido.cliente.email,
endereco: pedido.cliente.endereco,
numeroDoPedido: pedido.numero,
produtos: produtosFormatados,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
parcelas: pedido.pagamento.parcela,
id_transacao: pedido.pagamento.id_transacao,
dataDaCompra: moment(pedido.data_pedido_realizado).format('DD/MM/YYYY'),
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro
};
return pedidoFormatado;
}
} | src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 0.9029129147529602
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {\n return total + (produto.valor * produto.quantidade);\n }, 0);\n return {\n cpf: pedido.cliente.cpf,\n nome: pedido.cliente.nome_completo,\n numeroDoPedido: pedido.numero,",
"score": 0.8493918180465698
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " }\n },\n produto: {\n select: {\n nome_produto: true,\n quantidade: true,\n valor: true\n }\n }\n }",
"score": 0.8429647088050842
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " select: {\n nome_completo: true,\n cpf: true\n }\n },\n pedido_status: {\n select: {\n status_pedido: true,\n status_erro: true\n }",
"score": 0.825464129447937
},
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " }\n },\n pedido_status: {\n select: {\n status_pedido: true,\n status_erro: true,\n problema_resolvido: true\n }\n },\n produto: {",
"score": 0.8141912817955017
}
] | typescript | .forEach((produto) => { |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
| events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
); |
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 0.782157838344574
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)",
"score": 0.7564749121665955
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 0.7395714521408081
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 0.7335007786750793
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\tif (endDate === true) targetPosition = timelineLength;\n\t\t\telse\n\t\t\t\ttargetPosition = findEndPositionForDate(\n\t\t\t\t\tendDate,\n\t\t\t\t\tcollection.slice(index),\n\t\t\t\t\ttimelineLength,\n\t\t\t\t\tcardListRootElement,\n\t\t\t\t\tindex\n\t\t\t\t);\n\t\t\taccumulator.push({",
"score": 0.7313957214355469
}
] | typescript | events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
); |
import { pedido, pedido_status, nota_fiscal, pagamento, produto, cliente } from "@prisma/client";
import { prisma } from "../../../prisma/client";
export class GetPedidoPorCpfUseCase {
async getPedidoPorCpf(numero: string): Promise<any | null> {
if (numero.length === 11) {
const clienteCpf = await prisma.cliente.findFirst({
where: {
cpf: numero
}
});
if (clienteCpf) {
const pedido = await prisma.pedido.findMany({
where: {
id_cliente: clienteCpf.id_cliente
},
include: {
cliente: {
select: {
nome_completo: true,
cpf: true
}
},
pedido_status: {
select: {
status_pedido: true,
status_erro: true
}
},
nota_fiscal: {
select: {
numero_nota: true
}
},
pagamento: {
select: {
tipo_pagamento: true,
parcela: true
}
},
produto: {
select: {
nome_produto: true,
quantidade: true
}
}
}
});
if (!pedido) {
return null;
}
| const pedidosFormatados = pedido.map((pedido) => ({ |
numero: pedido.numero,
status_pedido: pedido.pedido_status.status_pedido,
status_erro: pedido.pedido_status.status_erro,
numero_nota_fiscal: pedido.nota_fiscal.numero_nota,
data_pedido_realizado: pedido.data_pedido_realizado,
nome_cliente: pedido.cliente.nome_completo,
cpf_cliente: pedido.cliente.cpf,
tipo_pagamento: pedido.pagamento.tipo_pagamento,
}));
return pedidosFormatados;
}
}
}
}
| src/modules/pedidos/buscarPedidosPorCPF/GetPedidoPorCpfUseCase.ts | Iguu42-node-project-FC-0cd6618 | [
{
"filename": "src/modules/pedidos/BuscarTodosPedidos/GetAllPedidosUseCase.ts",
"retrieved_chunk": " select: {\n valor: true,\n quantidade: true\n }\n },\n }\n });\n const moment = require('moment');\n const pedidosFormatados = pedidos.map((pedido) => {\n const valorTotal = pedido.produto.reduce((total, produto) => {",
"score": 0.9122415781021118
},
{
"filename": "src/modules/pedidos/filtrosPedidos/GetPedidosPorFiltroUseCase.ts",
"retrieved_chunk": " status_erro: true\n }\n },\n produto: {\n select: {\n valor: true,\n quantidade: true\n }\n },\n }",
"score": 0.8640429973602295
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " id_transacao: true\n }\n },\n pedido_status: {\n select: {\n status_pedido: true,\n status_erro: true\n }\n }\n }",
"score": 0.854690432548523
},
{
"filename": "src/modules/pedidos/buscarPedidosPorData/GetPedidosPorDataUseCase.ts",
"retrieved_chunk": " }\n },\n produto: {\n select: {\n nome_produto: true,\n quantidade: true,\n valor: true\n }\n }\n }",
"score": 0.8345174193382263
},
{
"filename": "src/modules/pedidos/buscarPedidoPorNumero/GetPedidoPorNumeroUseCase.ts",
"retrieved_chunk": " referencia: true,\n descricao: true,\n quantidade: true,\n valor: true,\n }\n },\n pagamento: {\n select: {\n tipo_pagamento: true,\n parcela: true,",
"score": 0.8284445405006409
}
] | typescript | const pedidosFormatados = pedido.map((pedido) => ({ |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
| { cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } } |
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tcontext: {\n\t\t\t\t\telements: { timelineRootElement, cardListRootElement },\n\t\t\t\t},\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t} = relatedCardData;\n\t\t\tif (!isDefined(startDate) || !isDefined(endDate))\n\t\t\t\treturn accumulator;\n\t\t\tif (\n\t\t\t\tendDate !== true &&\n\t\t\t\tcompareAbstractDates(endDate, startDate) < 0",
"score": 0.8143646717071533
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 0.7509211301803589
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\tindex,\n\t\t\t} as const);\n\t\t\treturn accumulator;\n\t\t},\n\t\t[] as {\n\t\t\treadonly relatedCardData: CompleteCardContext & {\n\t\t\t\tcardData: CompleteCardContext[\"cardData\"] & {\n\t\t\t\t\tstartDate: AbstractDate;\n\t\t\t\t\tendDate: AbstractDate | true;\n\t\t\t\t};",
"score": 0.7477328181266785
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\tisDefined(startDate) ? compareAbstractDates(startDate, date) > 0 : false\n\t);\n\tif (firstOverIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"No first over found - Can't draw range since there are no other two start date to referrence it's position\"\n\t\t);\n\tconst firstLastUnderIndex = findLastIndex(\n\t\tcollection,\n\t\t({ cardData: { startDate } }) =>\n\t\t\tisDefined(startDate)",
"score": 0.7475837469100952
},
{
"filename": "src/rangeData.ts",
"retrieved_chunk": "\t\t\t\t? compareAbstractDates(startDate, date) <= 0\n\t\t\t\t: false\n\t);\n\tif (firstLastUnderIndex === -1)\n\t\tthrow new Error(\n\t\t\t\"Could not find a firstLastUnderIndex, this means this function was called with un rangeable members\"\n\t\t);\n\tconst lastUnderIndex = collection.findIndex(\n\t\t({ cardData: { startDate } }, index) => {\n\t\t\treturn (",
"score": 0.7455458045005798
}
] | typescript | { cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } } |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await | getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tconst fileTitle =\n\t\tc.frontmatter?.[settings.metadataKeyEventTitleOverride] ||\n\t\tfile.basename;\n\trawFileContent = rawFileContent || (await file.vault.cachedRead(file));\n\treturn {\n\t\ttitle: fileTitle as string,\n\t\tbody: getBodyFromContextOrDocument(rawFileContent, context),\n\t\timageURL: getImageUrlFromContextOrDocument(rawFileContent, context),\n\t\tstartDate: getAbstractDateFromMetadata(\n\t\t\tcontext,",
"score": 0.7781211137771606
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 0.7753417491912842
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 0.7654010653495789
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t// Breakout earlier if we don't check the tags\n\tif (!settings.lookForTagsForTimeline) return output;\n\tif (isDefinedAsArray(tags))\n\t\toutput = output.concat(tags.map(({ tag }) => tag.substring(1)));\n\t// Tags in the frontmatter\n\tconst metadataInlineTags = metaData.tags;\n\tif (!isDefined(metadataInlineTags)) return output;\n\tif (isDefinedAsString(metadataInlineTags))\n\t\toutput = output.concat(\n\t\t\tmetadataInlineTags.split(\",\").map((e) => e.trim())",
"score": 0.7424843311309814
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "\t\tsettings: { metadataKeyEventBodyOverride },\n\t} = context;\n\tconst overrideBody = metadata?.[metadataKeyEventBodyOverride] ?? null;\n\tif (!rawFileText.length || overrideBody) return overrideBody;\n\tconst rawTextArray = rawFileText.split(\"\\n\");\n\trawTextArray.shift();\n\tconst processedArray = rawTextArray.slice(rawTextArray.indexOf(\"---\") + 1);\n\tconst finalString = processedArray.join(\"\\n\").trim();\n\treturn finalString;\n}",
"score": 0.7226947546005249
}
] | typescript | getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const | runtimeTime = measureTime("Run time"); |
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the body of a given card or null if none was found.\n */\nexport function getBodyFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext\n): string | null {\n\tconst {\n\t\tcachedMetadata: { frontmatter: metadata },",
"score": 0.8485161662101746
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 0.8407353162765503
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.8249961733818054
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 0.8096785545349121
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": " * @param timelineFile - The file path of the timeline.\n * @param settings - The plugin's settings.\n * @returns the nessessary context to build a timeline.\n */\nexport function setupTimelineCreation(\n\tapp: App,\n\telement: HTMLElement,\n\ttimelineFile: string,\n\tsettings: AutoTimelineSettings\n) {",
"score": 0.8085559606552124
}
] | typescript | runtimeTime = measureTime("Run time"); |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
index < this.settings.dateTokenConfiguration.length;
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
| this.addSettingTab(new TimelineSettingTab(this.app, this)); |
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "\tlet output = dateDisplayFormat.toString();\n\tprioArray.forEach((token, index) => {\n\t\tconst configuration = dateTokenConfiguration.find(\n\t\t\t({ name }) => name === token\n\t\t);\n\t\tif (!configuration)\n\t\t\tthrow new Error(\n\t\t\t\t`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`\n\t\t\t);\n\t\toutput = output.replace(",
"score": 0.7172236442565918
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "\t\t\t`{${token}}`,\n\t\t\tapplyConditionBasedFormatting(\n\t\t\t\tformatDateToken(date[index], configuration),\n\t\t\t\tdate[index],\n\t\t\t\tconfiguration,\n\t\t\t\tapplyAdditonalConditionFormatting\n\t\t\t)\n\t\t);\n\t});\n\treturn output;",
"score": 0.7090793251991272
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "): AbstractDate | undefined {\n\tconst groupsToCheck = settings.dateParserGroupPriority.split(\",\");\n\tconst numberValue = getMetadataKey(cachedMetadata, key, \"number\");\n\tif (isDefined(numberValue)) {\n\t\tconst additionalContentForNumberOnlydate = [\n\t\t\t...Array(Math.max(0, groupsToCheck.length - 1)),\n\t\t].map(() => 0);\n\t\treturn [numberValue, ...additionalContentForNumberOnlydate];\n\t}\n\tconst stringValue = getMetadataKey(cachedMetadata, key, \"string\");",
"score": 0.6800442934036255
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tsanitizedBlock.pop();\n\t\tconst fakeFrontmatter = parse(sanitizedBlock.join(\"\\n\")); // this actually works lmao\n\t\t// Replace frontmatter with newly built fake one. Just to re-use all the existing code.\n\t\tcontext.cachedMetadata.frontmatter = fakeFrontmatter;\n\t\tif (!isDefinedAsObject(fakeFrontmatter)) continue;\n\t\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\t\tsettings,\n\t\t\tfakeFrontmatter,\n\t\t\tcontext.cachedMetadata.tags\n\t\t);",
"score": 0.6715061664581299
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\tconstructor(app: ObsidianApp, plugin: AprilsAutomaticTimelinesPlugin) {\n\t\tsuper(app, plugin);\n\t\tthis.plugin = plugin;\n\t\tthis.vueApp = null;\n\t}\n\tdisplay(): void {\n\t\tthis.containerEl.empty();\n\t\t// TODO Read locale off obsidian.\n\t\tconst i18n = createVueI18nConfig();\n\t\tthis.vueApp = createApp({",
"score": 0.6706016063690186
}
] | typescript | this.addSettingTab(new TimelineSettingTab(this.app, this)); |
import { SETTINGS_DEFAULT } from "~/settings";
import { FnGetRangeData } from "./rangeData";
import { FnExtractCardData, getDataFromNoteMetadata } from "~/cardData";
import type { App, CachedMetadata, TFile } from "obsidian";
import type { Merge } from "ts-essentials";
/**
* @author https://stackoverflow.com/a/69756175
*/
export type PickByType<T, Value> = {
[P in keyof T as T[P] extends Value | undefined ? P : never]: T[P];
};
export type AutoTimelineSettings = typeof SETTINGS_DEFAULT;
/**
* The main bundle of data needed to build a timeline.
*/
export interface MarkdownCodeBlockTimelineProcessingContext {
/**
* Obsidian application context.
*/
app: App;
/**
* The plugins settings
*/
settings: AutoTimelineSettings;
/**
* The formatted metadata of a single note.
*/
cachedMetadata: CachedMetadata;
/**
* The file data of a single note.
*/
file: TFile;
/**
* The filepath of a single timeline.
*/
timelineFile: string;
/**
* Shorthand access to HTMLElements for the range timelines and the card list.
*/
elements: {
timelineRootElement: HTMLElement;
cardListRootElement: HTMLElement;
};
}
/**
* The context extracted from a single note to create a single card in the timeline combined with the more general purpise timeline context.
*/
export type CompleteCardContext = Exclude<
Awaited<ReturnType<typeof getDataFromNoteMetadata>>,
undefined
>;
/**
* The context extracted from a single note to create a single card in the timeline.
*/
export type CardContent = Awaited<ReturnType<FnExtractCardData>>;
/**
* The needed data to compute a range in a single timeline.
*/
| export type Range = ReturnType<FnGetRangeData>[number]; |
/**
* An abstract representation of a fantasy date.
* Given the fickle nature of story telling and how people will literally almost never stick to standard date formats
* We'll organise the dates in segments, let's take for example our human callendar
* The date will commonly be segmented in 3 parts year, month and day the abstract representation will equate to
* `[year, month, day]`
* Now if someone wants to make a more complex date system like `[cycle, moon, phase, day]` we can treat them the same when sorting and performing computing tasks on those dates.
* The only major limitation to this system is that all the dates must respect the same system.
*/
export type AbstractDate = number[];
/**
* Before formatting an abstract date, the end user can configure it's output display
* This DateToken type helps to determine what's the nature of a given token
* E.g. should it be displayed as a number or as a string ?
*/
export enum DateTokenType {
number = "NUMBER",
string = "STRING",
}
export const availableDateTokenTypeArray = Object.values(DateTokenType);
export enum Condition {
Greater = "GREATER",
Less = "LESS",
Equal = "EQUAL",
NotEqual = "NOTEQUAL",
GreaterOrEqual = "GREATEROREQUAL",
LessOrEqual = "LESSOREQUAL",
}
export const availableConditionArray = Object.values(Condition);
export type Evaluation<T extends number = number> = {
condition: Condition;
value: T;
};
export type AdditionalDateFormatting<T extends number = number> = {
evaluations: Evaluation<T>[];
/**
* Basically: if `true` the conditions all need to be `true` to return `true`. Else it only need one of the conditions to be checked.
*/
conditionsAreExclusive: boolean;
/**
* Use `{value}` to include the pre-formated output of the numerical value held.
*/
format: string;
};
/**
* The data used to compute the output of an abstract date based on it's type
*/
type CommonValues<T extends DateTokenType> = {
name: string;
type: T;
formatting: AdditionalDateFormatting[];
};
export type DateTokenConfiguration<T extends DateTokenType = DateTokenType> =
T extends DateTokenType.number
? NumberSpecific
: T extends DateTokenType.string
? StringSpecific
: StringSpecific | NumberSpecific;
/**
* Number typed date token.
*/
type NumberSpecific = Merge<
CommonValues<DateTokenType.number>,
{
/**
* The minimum ammount of digits when displaying the date
*/
minLeght: number;
displayWhenZero: boolean;
hideSign: boolean;
}
>;
/**
* String typed date token.
*/
type StringSpecific = Merge<
CommonValues<DateTokenType.string>,
{
/**
* The dictionary reference for the token
*/
dictionary: string[];
}
>;
| src/types.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/rangeData.ts",
"retrieved_chunk": " * Will compute all the data needed to build ranges in the timeline.\n *\n * @param collection - The complete collection of relevant data gathered from notes.\n * @returns the needed data to build ranges in the timeline.\n */\nexport function getAllRangeData(collection: CompleteCardContext[]) {\n\tif (!collection.length) return [];\n\treturn collection.reduce(\n\t\t(accumulator, relatedCardData, index) => {\n\t\t\tconst {",
"score": 0.820309579372406
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " *\n * @param context - Timeline generic context.\n * @param rawFileContent - If you already have it, will avoid reading the file again.\n * @returns The extracted data to create a card from a note.\n */\nexport async function extractCardData(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\trawFileContent?: string\n) {\n\tconst { file, cachedMetadata: c, settings } = context;",
"score": 0.8106145262718201
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tcontext,\n\t} as const;\n}\n/**\n * Provides additional context for the creation cards in the DOM but reads it from the body\n *\n * @param body - The extracted body for a single event card.\n * @param context - Timeline generic context.\n * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.",
"score": 0.8073210716247559
},
{
"filename": "src/cardMarkup.ts",
"retrieved_chunk": "/**\n * Format the body string of the note data for a single card.\n *\n * @param body - The body string parsed earlier.\n * @returns The formated string ready to be displayed.\n */\nexport function formatBodyForCard(body?: string | null): string {\n\tif (!body) return \"No body for this note :(\";\n\t// Remove external image links\n\treturn (",
"score": 0.8060846924781799
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": "/**\n * Extract the first image from the raw markdown in a note.\n *\n * @param rawFileText - The text content of a obsidian note.\n * @param context - Timeline generic context.\n * @returns the URL of the image to be displayed in a card or null if none where found.\n */\nexport function getImageUrlFromContextOrDocument(\n\trawFileText: string,\n\tcontext: MarkdownCodeBlockTimelineProcessingContext",
"score": 0.8053172826766968
}
] | typescript | export type Range = ReturnType<FnGetRangeData>[number]; |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
): AutoTimelineSettings[OverridableSettingKey] | undefined {
if (!isOverridableSettingsKey(key)) return undefined;
if | (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 0.7842468619346619
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "\treturn isDefined(value) && value instanceof Object;\n}\n/**\n * Shorthand to quickly get a well typed number date token configuration object.\n *\n * @param defaultValue - Override the values of the return object.\n * @returns DateTokenConfiguration<DateTokenType.number> - A well typed date token configuration object.\n */\nexport function createNumberDateTokenConfiguration(\n\tdefaultValue: Partial<DateTokenConfiguration<DateTokenType.number>> = {}",
"score": 0.7825179696083069
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": " * @param tagsToFind - The tags to find in a note to match the current timeline.\n * @returns the context or underfined if it could not build it.\n */\nexport async function getDataFromNoteMetadata(\n\tcontext: MarkdownCodeBlockTimelineProcessingContext,\n\ttagsToFind: string[]\n) {\n\tconst { cachedMetadata, settings } = context;\n\tconst { frontmatter: metaData, tags } = cachedMetadata;\n\tif (!metaData) return undefined;",
"score": 0.78005450963974
},
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 0.7773894667625427
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": " * @param timelineFile - The file path of the timeline.\n * @param settings - The plugin's settings.\n * @returns the nessessary context to build a timeline.\n */\nexport function setupTimelineCreation(\n\tapp: App,\n\telement: HTMLElement,\n\ttimelineFile: string,\n\tsettings: AutoTimelineSettings\n) {",
"score": 0.7765506505966187
}
] | typescript | (isDefinedAsString(SETTINGS_DEFAULT[key])) return value; |
import { SETTINGS_DEFAULT } from "~/settings";
import { AutoTimelineSettings } from "./types";
import { isDefined, isDefinedAsBoolean, isDefinedAsString } from "./utils";
/**
* Fetches the tags to find and timeline specific settings override.
*
* @param source - The markdown code block source, a.k.a. the content inside the code block.
* @returns Partial settings to override the global ones.
*/
export function parseMarkdownBlockSource(source: string): {
readonly tagsToFind: string[];
readonly settingsOverride: Partial<AutoTimelineSettings>;
} {
const sourceEntries = source.split("\n");
if (!source.length)
return { tagsToFind: [] as string[], settingsOverride: {} } as const;
const tagsToFind = sourceEntries[0]
.split(SETTINGS_DEFAULT.markdownBlockTagsToFindSeparator)
.map((e) => e.trim());
sourceEntries.shift();
return {
tagsToFind,
settingsOverride: sourceEntries.reduce((accumulator, element) => {
return {
...accumulator,
...parseSingleLine(element),
};
}, {} as Partial<AutoTimelineSettings>),
} as const;
}
type OverridableSettingKey = (typeof acceptedSettingsOverride)[number];
const acceptedSettingsOverride = [
"dateDisplayFormat",
"applyAdditonalConditionFormatting",
] as const;
/**
* Checks if a given string is part of the settings keys that can be overriden.
*
* @param value - A given settings key.
* @returns the typeguard boolean `true` if the key is indeed overridable.
*/
function isOverridableSettingsKey(
value: string
): value is OverridableSettingKey {
// @ts-expect-error
return acceptedSettingsOverride.includes(value);
}
/**
* Will apply the needed formatting to a setting value based of it's key.
*
* @param key - The settings key.
* @param value - The value associated to this value.
* @returns Undefined if unvalid or the actual expected value.
*/
function formatValueFromKey(
key: string,
value: string
| ): AutoTimelineSettings[OverridableSettingKey] | undefined { |
if (!isOverridableSettingsKey(key)) return undefined;
if (isDefinedAsString(SETTINGS_DEFAULT[key])) return value;
if (isDefinedAsBoolean(SETTINGS_DEFAULT[key])) {
const validBooleanStrings = ["true", "false"];
if (!validBooleanStrings.includes(value.toLocaleLowerCase()))
throw new Error(`${value} is supposed to be a boolean`);
return value.toLocaleLowerCase() === "true" ? true : false;
}
return undefined;
}
/**
* Parse a single line of the timeline markdown block content.
*
* @param line - The line to parse.
* @returns A potencialy partial settings object.
*/
function parseSingleLine(line: string): Partial<AutoTimelineSettings> {
const reg = /((?<key>(\s|\d|[a-z])*):(?<value>.*))/i;
const matches = line.match(reg);
if (
!matches ||
!matches.groups ||
!isDefinedAsString(matches.groups.key) ||
!isDefined(matches.groups.value)
)
return {};
const key = matches.groups.key.trim();
const value = formatValueFromKey(key, matches.groups.value.trim());
if (!isDefined(value)) return {};
return { [key]: value };
}
| src/markdownBlockData.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/cardDataExtraction.ts",
"retrieved_chunk": " *\n * @param param0 - Timeline generic context.\n * @param param0.cachedMetadata - The cached metadata from a note.\n * @param param0.settings - the plugin's settings.\n * @param key - The target lookup key in the notes metadata object.\n * @returns the abstract date representation or undefined.\n */\nexport function getAbstractDateFromMetadata(\n\t{ cachedMetadata, settings }: MarkdownCodeBlockTimelineProcessingContext,\n\tkey: string",
"score": 0.8956428170204163
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " * @param cachedMetadata - cachedMetadata - Obsidians cachedMetadata object.\n * @param key - the sought after key in the obsidian metadata object.\n * @param type - The expected type of the key value.\n * @returns The metadata value assigned to the given key or null if unvalidated or missing.\n */\nexport function getMetadataKey<T extends \"string\" | \"number\" | \"boolean\">(\n\tcachedMetadata: MarkdownCodeBlockTimelineProcessingContext[\"cachedMetadata\"],\n\tkey: string,\n\ttype: T\n):",
"score": 0.889133095741272
},
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "}\n/**\n * Shorthand to format a part of an abstract date.\n *\n * @param datePart - fragment of an abstract date.\n * @param configuration - the configuration bound to that date token.\n * @returns the formated token.\n */\nexport function formatDateToken(\n\tdatePart: number,",
"score": 0.877521276473999
},
{
"filename": "src/timelineMarkup.ts",
"retrieved_chunk": " * @param timelineFile - The file path of the timeline.\n * @param settings - The plugin's settings.\n * @returns the nessessary context to build a timeline.\n */\nexport function setupTimelineCreation(\n\tapp: App,\n\telement: HTMLElement,\n\ttimelineFile: string,\n\tsettings: AutoTimelineSettings\n) {",
"score": 0.8718363046646118
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "/**\n * Parse a string based off user date extract settings.\n *\n * @param groupsToCheck - The token names to check.\n * @param metadataString - The actual extracted data from the frontmatter.\n * @param reg - The user defined regex to apply.\n * @returns The parsed abstract date or nothing.\n */\nexport function parseAbstractDate(\n\tgroupsToCheck: string[],",
"score": 0.8700181245803833
}
] | typescript | ): AutoTimelineSettings[OverridableSettingKey] | undefined { |
import { MarkdownPostProcessorContext, Plugin } from "obsidian";
import type { AutoTimelineSettings, CompleteCardContext } from "~/types";
import { compareAbstractDates, isDefined, measureTime } from "~/utils";
import { getDataFromNoteMetadata, getDataFromNoteBody } from "~/cardData";
import { setupTimelineCreation } from "~/timelineMarkup";
import { createCardFromBuiltContext } from "~/cardMarkup";
import { getAllRangeData } from "~/rangeData";
import { renderRanges } from "~/rangeMarkup";
import { SETTINGS_DEFAULT, TimelineSettingTab } from "~/settings";
import { parseMarkdownBlockSource } from "./markdownBlockData";
export default class AprilsAutomaticTimelinesPlugin extends Plugin {
settings: AutoTimelineSettings;
/**
* The default onload method of a obsidian plugin
* See the official documentation for more details
*/
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor(
"aat-vertical",
(source, element, context) => {
this.run(source, element, context);
}
);
}
onunload() {}
/**
* Main runtime function to process a single timeline.
*
* @param source - The content found in the markdown block.
* @param element - The root element of all the timeline.
* @param param2 - The context provided by obsidians `registerMarkdownCodeBlockProcessor()` method.
* @param param2.sourcePath - A string representing the fs path of a note.
*/
async run(
source: string,
element: HTMLElement,
{ sourcePath }: MarkdownPostProcessorContext
) {
const runtimeTime = measureTime("Run time");
const { app } = this;
const { tagsToFind, settingsOverride } =
parseMarkdownBlockSource(source);
const finalSettings = { ...this.settings, ...settingsOverride };
const creationContext = setupTimelineCreation(
app,
element,
sourcePath,
finalSettings
);
const cardDataTime = measureTime("Data fetch");
const events: CompleteCardContext[] = [];
for (const context of creationContext) {
const baseData = await getDataFromNoteMetadata(context, tagsToFind);
if (isDefined(baseData)) events.push(baseData);
if (!finalSettings.lookForInlineEventsInNotes) continue;
const body =
baseData?.cardData.body ||
(await context.file.vault.cachedRead(context.file));
const inlineEvents = (
await getDataFromNoteBody(body, context, tagsToFind)
).filter(isDefined);
if (!inlineEvents.length) continue;
events.push(...inlineEvents);
}
events.sort(
(
{ cardData: { startDate: a, endDate: aE } },
{ cardData: { startDate: b, endDate: bE } }
) => {
const score = compareAbstractDates(a, b);
if (score) return score;
return compareAbstractDates(aE, bE);
}
);
cardDataTime();
const cardRenderTime = measureTime("Card Render");
events.forEach(({ context, cardData }) =>
createCardFromBuiltContext(context, cardData)
);
cardRenderTime();
const rangeDataFecthTime = measureTime("Range Data");
const ranges = getAllRangeData(events);
rangeDataFecthTime();
const rangeRenderTime = measureTime("Range Render");
renderRanges(ranges, element);
rangeRenderTime();
runtimeTime();
}
/**
* Loads the saved settings from the local device and sets up the setting tabs in the plugin options.
*/
async loadSettings() {
this.settings = Object.assign(
{},
SETTINGS_DEFAULT,
await this.loadData()
);
for (
let index = 0;
| index < this.settings.dateTokenConfiguration.length; |
index++
) {
this.settings.dateTokenConfiguration[index].formatting =
this.settings.dateTokenConfiguration[index].formatting || [];
}
this.addSettingTab(new TimelineSettingTab(this.app, this));
}
/**
* Saves the settings in obsidian.
*/
async saveSettings() {
await this.saveData(this.settings);
}
}
| src/main.ts | April-Gras-obsidian-auto-timelines-047d836 | [
{
"filename": "src/abstractDateFormatting.ts",
"retrieved_chunk": "\tlet output = dateDisplayFormat.toString();\n\tprioArray.forEach((token, index) => {\n\t\tconst configuration = dateTokenConfiguration.find(\n\t\t\t({ name }) => name === token\n\t\t);\n\t\tif (!configuration)\n\t\t\tthrow new Error(\n\t\t\t\t`[April's not so automatic timelines] - No date token configuration found for ${token}, please setup your date tokens correctly`\n\t\t\t);\n\t\toutput = output.replace(",
"score": 0.7559888362884521
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\tif (!RENDER_GREENLIGHT_METADATA_KEY.some((key) => metaData[key] === true))\n\t\treturn undefined;\n\tconst timelineTags = getTagsFromMetadataOrTagObject(\n\t\tsettings,\n\t\tmetaData,\n\t\ttags\n\t);\n\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) return undefined;\n\treturn {\n\t\tcardData: await extractCardData(context),",
"score": 0.7469114065170288
},
{
"filename": "src/rangeMarkup.ts",
"retrieved_chunk": "\t);\n\tranges.forEach((range) => {\n\t\tconst {\n\t\t\trelatedCardData: {\n\t\t\t\tcardData: { startDate, endDate },\n\t\t\t},\n\t\t} = range;\n\t\tconst offsetIndex = endDates.findIndex(\n\t\t\t(date) =>\n\t\t\t\t!isDefined(date) ||",
"score": 0.746522843837738
},
{
"filename": "src/markdownBlockData.ts",
"retrieved_chunk": "\treturn {\n\t\ttagsToFind,\n\t\tsettingsOverride: sourceEntries.reduce((accumulator, element) => {\n\t\t\treturn {\n\t\t\t\t...accumulator,\n\t\t\t\t...parseSingleLine(element),\n\t\t\t};\n\t\t}, {} as Partial<AutoTimelineSettings>),\n\t} as const;\n}",
"score": 0.739649772644043
},
{
"filename": "src/cardData.ts",
"retrieved_chunk": "\t\tif (!extractedTagsAreValid(timelineTags, tagsToFind)) continue;\n\t\tconst matchPositionInBody = body.indexOf(block);\n\t\toutput.push({\n\t\t\tcardData: await extractCardData(\n\t\t\t\tcontext,\n\t\t\t\tmatchPositionInBody !== -1\n\t\t\t\t\t? body.slice(matchPositionInBody + block.length)\n\t\t\t\t\t: undefined\n\t\t\t),\n\t\t\tcontext,",
"score": 0.7049785256385803
}
] | typescript | index < this.settings.dateTokenConfiguration.length; |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public | findServiceByType(type: string): Service { |
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {",
"score": 0.8209595084190369
},
{
"filename": "src/schemas/didSchema.ts",
"retrieved_chunk": " return new Did(did)\n } else if (did instanceof Did) {\n return did\n } else {\n throw new DidError(`id must be of type 'string' or an instance of 'Did'`)\n }\n })\nexport const stringOrDidUrl = z\n .union([\n didUrlSchemaWithouttransformation,",
"score": 0.813341498374939
},
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " for (const obj of verificationMethods) {\n if (idSet.has(obj.id)) {\n return false\n }\n idSet.add(obj.id)\n }\n return true\n }, `Duplicate verificationMethod.id found. They must be unique`)\nexport const stringOrVerificationMethod = z\n .union([stringOrDidUrl, verificationMethodSchema])",
"score": 0.8088908195495605
},
{
"filename": "src/schemas/didSchema.ts",
"retrieved_chunk": " z.custom<Did>((did) => did instanceof Did),\n ])\n .transform((did: string | Did): Did => {\n if (typeof did === 'string') {\n return new Did(did)\n } else if (did instanceof Did) {\n return did\n } else {\n throw new DidError(`id must be of type 'string' or an instance of 'Did'`)\n }",
"score": 0.7740562558174133
},
{
"filename": "src/schemas/didSchema.ts",
"retrieved_chunk": "export const didSchemaWithouttransformation = z\n .string()\n .regex(DID_REGEXP, { message: 'Invalid did syntax' })\nexport const stringOrDid = z\n .union([\n didSchemaWithouttransformation,\n z.custom<Did>((did) => did instanceof Did),\n ])\n .transform((did: string | Did): Did => {\n if (typeof did === 'string') {",
"score": 0.7671491503715515
}
] | typescript | findServiceByType(type: string): Service { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
| id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean { |
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {",
"score": 0.8288947343826294
},
{
"filename": "src/service.ts",
"retrieved_chunk": " */\n public isTypeInDidSpecRegistry(\n additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (Object.values(ServiceTypes) as Array<string>).concat(\n additionalAcceptedTypesArray",
"score": 0.8093489408493042
},
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id",
"score": 0.8068894743919373
},
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (\n Object.values(VerificationMethodTypes) as Array<string>\n ).concat(additionalAcceptedTypesArray)\n return allTypes.includes(this.type)",
"score": 0.8021478056907654
},
{
"filename": "src/did.ts",
"retrieved_chunk": " private path?: string\n private query?: Record<string, string>\n private fragment?: string\n private parameters?: Record<string, string>\n private parameterKeys: Array<string>\n public constructor(did: string, parameterKeys?: Array<string>) {\n const parsedDid = didUrlSchemaWithouttransformation.parse(did)\n const url = new URL(parsedDid)\n const prefixPathIndex = url.pathname.indexOf(PREFIX_PATH)\n const stripUntil = Math.min(",
"score": 0.7929139137268066
}
] | typescript | id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: | string | Did,
asArray = true
): ReturnBuilderWithController<this> { |
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/did.ts",
"retrieved_chunk": " public removePath(): this {\n this.path = undefined\n return this\n }\n public withQuery(query: Record<string, string>): this {\n this.query = query\n return this\n }\n public addQuery(query: Record<string, string>): this {\n if (this.query) {",
"score": 0.7735708355903625
},
{
"filename": "src/did.ts",
"retrieved_chunk": " return this\n }\n public addPath(path: string): this {\n if (this.path) {\n this.path = this.path + this.addPrefixIfNotSupplied(path, PREFIX_PATH)\n } else {\n return this.withPath(path)\n }\n return this\n }",
"score": 0.7663345336914062
},
{
"filename": "src/didResolution.ts",
"retrieved_chunk": "export interface DidResolution<\n AdditionalOptions extends Record<string, unknown> = {},\n AdditionalDidResolutionMetadata extends Record<string, unknown> = {},\n AdditionalDidDocument extends Record<string, unknown> = {},\n AdditionalDidDocumentMetadata extends Record<string, unknown> = {}\n> {\n resolve(\n did: string,\n resolutionOptions?: Impossible<\n ResolutionOptions<AdditionalOptions>,",
"score": 0.7593584060668945
},
{
"filename": "src/service.ts",
"retrieved_chunk": " */\n public isTypeInDidSpecRegistry(\n additionalAcceptedTypes: string | Array<string> = []\n ): boolean {\n const additionalAcceptedTypesArray =\n typeof additionalAcceptedTypes === 'string'\n ? [additionalAcceptedTypes]\n : additionalAcceptedTypes\n const allTypes = (Object.values(ServiceTypes) as Array<string>).concat(\n additionalAcceptedTypesArray",
"score": 0.7466009855270386
},
{
"filename": "src/did.ts",
"retrieved_chunk": " this.query = { ...this.query, ...query }\n } else {\n this.withQuery(query)\n }\n return this\n }\n public removeQuery(): this {\n this.query = undefined\n return this\n }",
"score": 0.7432379722595215
}
] | typescript | string | Did,
asArray = true
): ReturnBuilderWithController<this> { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
| public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/didResolution.ts",
"retrieved_chunk": "export interface DidResolution<\n AdditionalOptions extends Record<string, unknown> = {},\n AdditionalDidResolutionMetadata extends Record<string, unknown> = {},\n AdditionalDidDocument extends Record<string, unknown> = {},\n AdditionalDidDocumentMetadata extends Record<string, unknown> = {}\n> {\n resolve(\n did: string,\n resolutionOptions?: Impossible<\n ResolutionOptions<AdditionalOptions>,",
"score": 0.8000195026397705
},
{
"filename": "src/didResolution.ts",
"retrieved_chunk": "// « didResolutionMetadata, didDocumentStream, didDocumentMetadata »\nexport type DidDocumentMetadata<T extends Record<string, unknown>> = {\n created?: string\n updated?: string\n deactivated?: string\n nextUpdate?: string\n versionId?: string\n equivalentId?: Array<string>\n canonicalId?: string\n} & T",
"score": 0.7904701232910156
},
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id",
"score": 0.7797700762748718
},
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {",
"score": 0.7737983465194702
},
{
"filename": "src/didResolution.ts",
"retrieved_chunk": " resolvePresentation(\n did: string,\n resolutionOptions?: ResolutionOptions<AdditionalOptions>\n ): OrPromise<{\n didResolutionMetadata: DidResolutionMetadata<AdditionalDidResolutionMetadata>\n didDocumentStream: Uint8Array\n didDocumentMetadata: DidDocumentMetadata<AdditionalDidDocumentMetadata>\n }>\n}",
"score": 0.7628464698791504
}
] | typescript | public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
| public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addService(service: ServiceOptions): ReturnBuilderWithService<this> {
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/didResolution.ts",
"retrieved_chunk": "export interface DidResolution<\n AdditionalOptions extends Record<string, unknown> = {},\n AdditionalDidResolutionMetadata extends Record<string, unknown> = {},\n AdditionalDidDocument extends Record<string, unknown> = {},\n AdditionalDidDocumentMetadata extends Record<string, unknown> = {}\n> {\n resolve(\n did: string,\n resolutionOptions?: Impossible<\n ResolutionOptions<AdditionalOptions>,",
"score": 0.8000195026397705
},
{
"filename": "src/didResolution.ts",
"retrieved_chunk": "// « didResolutionMetadata, didDocumentStream, didDocumentMetadata »\nexport type DidDocumentMetadata<T extends Record<string, unknown>> = {\n created?: string\n updated?: string\n deactivated?: string\n nextUpdate?: string\n versionId?: string\n equivalentId?: Array<string>\n canonicalId?: string\n} & T",
"score": 0.7904701232910156
},
{
"filename": "src/verificationMethod.ts",
"retrieved_chunk": " id: Did\n controller: Did\n type: VerificationMethodTypes | string\n publicKeyJwk?: PublicKeyJwk\n publicKeyMultibase?: PublicKeyMultibase\n public constructor(options: VerificationMethodOptions) {\n this.fullVerificationMethod = options\n const { id, controller, type, publicKeyJwk, publicKeyMultibase } =\n verificationMethodSchema.parse(options)\n this.id = id",
"score": 0.7797700762748718
},
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {",
"score": 0.7737983465194702
},
{
"filename": "src/didResolution.ts",
"retrieved_chunk": " resolvePresentation(\n did: string,\n resolutionOptions?: ResolutionOptions<AdditionalOptions>\n ): OrPromise<{\n didResolutionMetadata: DidResolutionMetadata<AdditionalDidResolutionMetadata>\n didDocumentStream: Uint8Array\n didDocumentMetadata: DidDocumentMetadata<AdditionalDidDocumentMetadata>\n }>\n}",
"score": 0.7628464698791504
}
] | typescript | public service?: Array<Service>
public constructor(options: DidDocumentOptions) { |
import { z } from 'zod'
import { Did } from './did'
import { Service, ServiceOptions } from './service'
import {
VerificationMethod,
VerificationMethodOptions,
} from './verificationMethod'
import {
didDocumentSchema,
stringOrDid,
uniqueServicesSchema,
uniqueStringOrVerificationMethodsSchema,
uniqueVerificationMethodsSchema,
} from './schemas'
import { DidDocumentError } from './error'
import { MakePropertyRequired, Modify } from './types'
type DidOrVerificationMethodArray = Array<VerificationMethodOrDidOrString>
type VerificationMethodOrDidOrString =
| VerificationMethod
| VerificationMethodOptions
| Did
| string
export type DidDocumentOptions<T extends Record<string, unknown> = {}> = Modify<
z.input<typeof didDocumentSchema>,
{
verificationMethod?: Array<VerificationMethodOptions>
authentication?: DidOrVerificationMethodArray
assertionMethod?: DidOrVerificationMethodArray
keyAgreement?: DidOrVerificationMethodArray
capabilityInvocation?: DidOrVerificationMethodArray
capabilityDelegation?: DidOrVerificationMethodArray
service?: Array<ServiceOptions | Service>
}
> &
Record<string, unknown> &
T
type ReturnBuilderWithAlsoKnownAs<T extends DidDocument> = MakePropertyRequired<
T,
'alsoKnownAs'
>
type ReturnBuilderWithController<T extends DidDocument> = MakePropertyRequired<
T,
'controller'
>
type ReturnBuilderWithVerificationMethod<T extends DidDocument> =
MakePropertyRequired<T, 'verificationMethod'>
type ReturnBuilderWithAuthentication<T extends DidDocument> =
MakePropertyRequired<T, 'authentication'>
type ReturnBuilderWithAssertionMethod<T extends DidDocument> =
MakePropertyRequired<T, 'assertionMethod'>
type ReturnBuilderWithKeyAgreementMethod<T extends DidDocument> =
MakePropertyRequired<T, 'keyAgreement'>
type ReturnBuilderWithCapabilityInvocation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityInvocation'>
type ReturnBuilderWithCapabilityDelegation<T extends DidDocument> =
MakePropertyRequired<T, 'capabilityDelegation'>
type ReturnBuilderWithService<T extends DidDocument> = MakePropertyRequired<
T,
'service'
>
export class DidDocument {
public fullDocument: DidDocumentOptions
public id: Did
public alsoKnownAs?: Array<string>
public controller?: Did | Array<Did>
public verificationMethod?: Array<VerificationMethod>
public authentication?: Array<VerificationMethod | Did>
public assertionMethod?: Array<VerificationMethod | Did>
public keyAgreement?: Array<VerificationMethod | Did>
public capabilityInvocation?: Array<VerificationMethod | Did>
public capabilityDelegation?: Array<VerificationMethod | Did>
public service?: Array<Service>
public constructor(options: DidDocumentOptions) {
this.fullDocument = options
const parsed = didDocumentSchema.parse(options)
this.id = parsed.id
this.alsoKnownAs = parsed.alsoKnownAs
this.controller = parsed.controller
this.verificationMethod = parsed.verificationMethod
this.authentication = parsed.authentication
this.assertionMethod = parsed.assertionMethod
this.keyAgreement = parsed.keyAgreement
this.capabilityDelegation = parsed.capabilityDelegation
this.capabilityInvocation = parsed.capabilityInvocation
this.service = parsed.service
}
public findVerificationMethodByDidUrl(didUrl: z.input<typeof stringOrDid>) {
const did = stringOrDid.parse(didUrl)
const verificationMethod = this.verificationMethod?.find(
(verificationMethod) => verificationMethod.id.toUrl() === did.toUrl()
)
if (!verificationMethod) {
throw new DidDocumentError(
`Verification method for did '${did.toString()}' not found`
)
}
return verificationMethod
}
public safeFindToVerificationMethodByDidUrl(
didUrl: z.input<typeof stringOrDid>
) {
try {
return this.findVerificationMethodByDidUrl(didUrl)
} catch {
return undefined
}
}
public addAlsoKnownAs(
alsoKnownAs: string
): ReturnBuilderWithAlsoKnownAs<this> {
if (this.alsoKnownAs) {
this.alsoKnownAs.push(alsoKnownAs)
} else {
this.alsoKnownAs = [alsoKnownAs]
}
return this as ReturnBuilderWithAlsoKnownAs<this>
}
public addController(
controller: string | Did,
asArray = true
): ReturnBuilderWithController<this> {
const instancedController =
typeof controller === 'string' ? new Did(controller) : controller
if (this.controller) {
if (Array.isArray(this.controller)) {
this.controller.push(instancedController)
} else {
this.controller = [this.controller, instancedController]
}
} else {
this.controller = asArray ? [instancedController] : instancedController
}
return this as ReturnBuilderWithController<this>
}
public addVerificationMethod(
verificationMethod: VerificationMethodOptions
): ReturnBuilderWithVerificationMethod<this> {
if (this.verificationMethod) {
this.verificationMethod.push(new VerificationMethod(verificationMethod))
} else {
this.verificationMethod = [new VerificationMethod(verificationMethod)]
}
uniqueVerificationMethodsSchema.parse(this.verificationMethod)
return this as ReturnBuilderWithVerificationMethod<this>
}
public addAuthentication(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString
)
return this as ReturnBuilderWithAuthentication<this>
}
public addAuthenticationUnsafe(
verificationMethodOrDidOrString: VerificationMethodOrDidOrString
): ReturnBuilderWithAuthentication<this> {
this.authentication = this.addVerificationMethodOrDidOrString(
'authentication',
this.authentication,
verificationMethodOrDidOrString,
true
)
return this as ReturnBuilderWithAuthentication<this>
}
public addKeyAgreement(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addKeyAgreementUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithKeyAgreementMethod<this> {
this.keyAgreement = this.addVerificationMethodOrDidOrString(
'keyAgreement',
this.keyAgreement,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithKeyAgreementMethod<this>
}
public addAssertionMethod(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addAssertionMethodUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithAssertionMethod<this> {
this.assertionMethod = this.addVerificationMethodOrDidOrString(
'assertionMethod',
this.assertionMethod,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithAssertionMethod<this>
}
public addCapabilityDelegation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityDelegationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityDelegation<this> {
this.capabilityDelegation = this.addVerificationMethodOrDidOrString(
'capabilityDelegation',
this.capabilityDelegation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityDelegation<this>
}
public addCapabilityInvocation(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public addCapabilityInvocationUnsafe(
verificationMethodOrStringOrDid: VerificationMethodOrDidOrString
): ReturnBuilderWithCapabilityInvocation<this> {
this.capabilityInvocation = this.addVerificationMethodOrDidOrString(
'capabilityInvocation',
this.capabilityInvocation,
verificationMethodOrStringOrDid,
true
)
return this as ReturnBuilderWithCapabilityInvocation<this>
}
public | addService(service: ServiceOptions): ReturnBuilderWithService<this> { |
const instanceService = new Service(service)
if (this.service) {
this.service.push(instanceService)
} else {
this.service = [instanceService]
}
uniqueServicesSchema.parse(this.service)
return this as ReturnBuilderWithService<this>
}
private addVerificationMethodOrDidOrString(
fieldName: string,
previousItem: Array<VerificationMethod | Did> | undefined,
verificationMethodOrDidOrString: VerificationMethodOrDidOrString,
unsafe = false
) {
let newItem = previousItem
const id =
verificationMethodOrDidOrString instanceof Did
? verificationMethodOrDidOrString
: typeof verificationMethodOrDidOrString === 'string'
? new Did(verificationMethodOrDidOrString)
: undefined
if (id && !unsafe) {
const verificationMethodIds = this.verificationMethod?.map((vm) =>
vm.id.toUrl()
)
if (
verificationMethodIds === undefined ||
!verificationMethodIds.includes(id.toUrl())
) {
throw new DidDocumentError(
`Tried to add '${id.toUrl()}' to '${fieldName}', but it was not found in the verificationMethod. If you want to add it anyways, try 'this.add${
fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
}Unsafe(...)'`
)
}
}
const vm =
id === undefined
? verificationMethodOrDidOrString instanceof VerificationMethod
? verificationMethodOrDidOrString
: new VerificationMethod(
verificationMethodOrDidOrString as VerificationMethodOptions
)
: undefined
const item = id ?? vm
if (item) {
if (newItem) {
newItem.push(item)
} else {
newItem = [item]
}
} else {
throw new DidDocumentError(
`Something went wrong while trying to parse verification method for ${fieldName} with item ${verificationMethodOrDidOrString}`
)
}
uniqueStringOrVerificationMethodsSchema(fieldName).parse(newItem)
return newItem
}
public findServiceByType(type: string): Service {
const service = this.service?.find((s) =>
(typeof s.type === 'string' ? [s.type] : s.type).includes(type)
)
if (!service) {
throw new DidDocumentError(`Service not found for type '${type}'`)
}
return service
}
public safeFindServiceByType(type: string): Service | undefined {
try {
return this.findServiceByType(type)
} catch {
return undefined
}
}
public findServiceById(id: string): Service {
const service = this.service?.find((s) => s.id === id)
if (!service) {
throw new DidDocumentError(`Service not found with id '${id}'`)
}
return service
}
public safeFindServiceById(id: string): Service | undefined {
try {
return this.findServiceById(id)
} catch {
return undefined
}
}
public findVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod {
const field =
purpose === 'authentication'
? this.authentication
: purpose === 'keyAgreement'
? this.keyAgreement
: purpose === 'assertionMethod'
? this.assertionMethod
: purpose === 'capabilityInvocation'
? this.capabilityInvocation
: purpose === 'capabilityDelegation'
? this.capabilityInvocation
: this.verificationMethod
if (!field) {
throw new DidDocumentError(
`Purpose '${purpose}' does not exist inside the did document`
)
}
const vm = field
.map((f) =>
f instanceof Did ? this.safeFindToVerificationMethodByDidUrl(f) : f
)
.find((vm) => vm?.type === type)
if (!vm) {
throw new DidDocumentError(
`Purpose '${purpose}' does not have a field with type '${type}'`
)
}
return vm
}
public safeFindVerificationMethodByTypeAndPurpose(
type: string,
purpose:
| 'authentication'
| 'keyAgreement'
| 'assertionMethod'
| 'capabilityInvocation'
| 'capabilityDelegation'
| 'verificationMethod' = 'verificationMethod'
): VerificationMethod | undefined {
try {
return this.findVerificationMethodByTypeAndPurpose(type, purpose)
} catch {
return undefined
}
}
public isVerificationMethodTypeRegistered(
id: Did | string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const vm = this.findVerificationMethodByDidUrl(id)
return vm.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public isServiceTypeRegistered(
id: string,
additionalAcceptedTypes: string | Array<string> = []
): boolean {
const service = this.findServiceById(id)
return service.isTypeInDidSpecRegistry(additionalAcceptedTypes)
}
public toJSON(omitKeys?: Array<string>): Record<string, unknown> {
const mapStringOrVerificationMethod = (i: Did | VerificationMethod) =>
i.toJSON()
const omitBase = ['fullDocument']
const omitKeysWithBase = omitKeys ? [...omitBase, ...omitKeys] : omitBase
const mappedRest = {
...this.fullDocument,
id: this.id.did,
alsoKnownAs: this.alsoKnownAs,
controller:
this.controller && this.controller instanceof Did
? this.controller?.did
: this.controller?.map((c) => c.did),
verificationMethod: this.verificationMethod?.map((v) => v.toJSON()),
service: this.service?.map((s) => s.toJSON()),
assertionMethod: this.assertionMethod?.map(mapStringOrVerificationMethod),
keyAgreement: this.keyAgreement?.map(mapStringOrVerificationMethod),
capabilityInvocation: this.capabilityInvocation?.map(
mapStringOrVerificationMethod
),
capabilityDelegation: this.capabilityDelegation?.map(
mapStringOrVerificationMethod
),
authentication: this.authentication?.map(mapStringOrVerificationMethod),
}
const cleanedRest = Object.fromEntries(
Object.entries(mappedRest)
.filter(([_, value]) => value !== undefined)
.filter(([key]) => !omitKeysWithBase.includes(key))
)
return cleanedRest
}
}
| src/didDocument.ts | berendsliedrecht-did-core-1d5b3ba | [
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " .transform((verificationMethod) => {\n if (verificationMethod instanceof Did) {\n return verificationMethod\n }\n return new VerificationMethod(verificationMethod)\n })\nexport const uniqueStringOrVerificationMethodsSchema = (name: string) =>\n z.array(stringOrVerificationMethod).refine((verificationMethods) => {\n const idSet = new Set()\n for (const obj of verificationMethods) {",
"score": 0.7605599164962769
},
{
"filename": "src/schemas/didDocumentSchema.ts",
"retrieved_chunk": " ),\n keyAgreement: z.optional(\n uniqueStringOrVerificationMethodsSchema('keyAgreement')\n ),\n capabilityInvocation: z.optional(\n uniqueStringOrVerificationMethodsSchema('capabilityInvocation')\n ),\n capabilityDelegation: z.optional(\n uniqueStringOrVerificationMethodsSchema('capabilityInvocation')\n ),",
"score": 0.7419333457946777
},
{
"filename": "src/schemas/didDocumentSchema.ts",
"retrieved_chunk": " service: z.optional(uniqueServicesSchema),\n })\n .transform((didDocument) => ({\n ...didDocument,\n service: didDocument.service?.map((s) => new Service(s)),\n verificationMethod: didDocument.verificationMethod?.map(\n (v) => new VerificationMethod(v)\n ),\n }))",
"score": 0.740851879119873
},
{
"filename": "src/schemas/verificationMethodSchema.ts",
"retrieved_chunk": " z.object({\n id: stringOrDidUrl,\n controller: stringOrDid,\n type: z.string(),\n publicKeyJwk: z.optional(publicKeyJwkSchema),\n publicKeyMultibase: z.optional(publicKeyMultibaseSchema),\n }),\n z.custom<VerificationMethod>(\n (verificationMethod) => verificationMethod instanceof VerificationMethod\n ),",
"score": 0.7337180376052856
},
{
"filename": "src/didResolution.ts",
"retrieved_chunk": "export interface DidResolution<\n AdditionalOptions extends Record<string, unknown> = {},\n AdditionalDidResolutionMetadata extends Record<string, unknown> = {},\n AdditionalDidDocument extends Record<string, unknown> = {},\n AdditionalDidDocumentMetadata extends Record<string, unknown> = {}\n> {\n resolve(\n did: string,\n resolutionOptions?: Impossible<\n ResolutionOptions<AdditionalOptions>,",
"score": 0.7260909080505371
}
] | typescript | addService(service: ServiceOptions): ReturnBuilderWithService<this> { |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)}
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
| const { update, save } = useFilesMutations(); |
const { name, content } = useFile.Selected();
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`mr-2 h-5 w-5 ${props.iconClassName ?? ''}`}\n />\n )}\n {props.children}\n </button>\n )}\n </Menu.Item>\n);\nconst MenuHeader = (props: { children: ReactNode }): JSX.Element => (\n <Menu.Item as=\"p\" className=\"px-2 py-1 text-xs text-slate-400\">",
"score": 0.8757994174957275
},
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": " props.className ?? ''\n }`}\n >\n {Icon && <Icon className=\"-ml-1 mr-2 h-5 w-5\" />}\n {props.children}\n </button>\n );\n};\nexport default Button;",
"score": 0.8506507277488708
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>",
"score": 0.7969552278518677
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}",
"score": 0.7917064428329468
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuItem icon={TrashIcon} onClick={props.onClickClearConsole}>\n Clear output\n </MenuItem>\n </div>\n </Menu.Items>\n </Transition>\n </Menu>\n );\n};\nexport default TerminalMenu;",
"score": 0.7885324954986572
}
] | typescript | const { update, save } = useFilesMutations(); |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
< | FileItem
key={name} |
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 0.862566351890564
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.8261934518814087
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.8080416917800903
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 0.796634316444397
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 0.7929373979568481
}
] | typescript | FileItem
key={name} |
import { useState } from 'react';
import { Transition } from '@headlessui/react';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import UnsavedBadge from './UnsavedBadge';
interface RenamableInputProps {
initialValue: string;
onConfirm: (value: string) => void;
}
const RenamableInput = (props: RenamableInputProps): JSX.Element => {
const [newFileName, setNewFileName] = useState<string>();
const [editing, setEditing] = useState(false);
return !editing ? (
<div
className="min-w-0 rounded-lg p-2 hover:bg-slate-800"
onClick={() => setEditing(true)}
>
<p className="text-md overflow-hidden overflow-ellipsis whitespace-nowrap">
{props.initialValue}
</p>
</div>
) : (
<input
autoFocus
className="w-fit rounded-lg bg-slate-800 bg-transparent p-2 outline-none ring-2 ring-slate-600"
onBlur={() => {
let newName = newFileName?.trim();
setEditing(false);
setNewFileName(undefined);
if (
!newName ||
newName === props.initialValue ||
newName.startsWith('.') ||
newName.endsWith('.')
)
return;
/**
* @see https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
*/
newName = newName.replace(/[/\\?%*:|"<>]/g, '_');
props.onConfirm(newName);
}}
onChange={(e) => setNewFileName(e.target.value)}
onFocus={(e) => {
const name = e.target.value;
const extensionLength = name.split('.').pop()?.length ?? 0;
e.target.setSelectionRange(0, name.length - extensionLength - 1);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.currentTarget.blur();
}
if (e.key === 'Escape') {
e.preventDefault();
setEditing(false);
setNewFileName(undefined);
}
}}
placeholder={props.initialValue}
type="text"
value={newFileName ?? props.initialValue}
/>
);
};
const FileName = (): JSX.Element => {
const name = useFile.SelectedName();
const unsaved = useFile.IsUnsavedOf(name);
const existingNames = useFile.NamesSet();
| const { rename } = useFilesMutations(); |
return (
<div className="flex min-w-0 items-center space-x-3">
{name && (
<RenamableInput
initialValue={name}
onConfirm={(newName) => {
if (!name) return;
if (existingNames.has(newName)) return;
rename(name, newName);
}}
/>
)}
<Transition
enter="transition-transform origin-left duration-75"
enterFrom="scale-0"
enterTo="scale-100"
leave="transition-transform origin-left duration-150"
leaveFrom="scale-100"
leaveTo="scale-0"
show={Boolean(name && unsaved)}
>
<UnsavedBadge />
</Transition>
</div>
);
};
export default FileName;
| src/components/FileName.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 0.8178409337997437
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": "});\nconst selectFiles = (state: RootState) => state.files;\nexport const getSelectedFileName = createSelector(\n selectFiles,\n (files) => files.selected,\n);\nexport const getSelectedFile = createSelector(selectFiles, (files) =>\n files.selected\n ? { name: files.selected, content: files.files[files.selected] }\n : { name: undefined, content: undefined },",
"score": 0.7931623458862305
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": " return fileInFiles !== fileInVault;\n });\nconst Exports = () => {\n const { files, list } = getState().vault;\n return list.map((name) => ({ name, content: files[name] }));\n};\nconst useFile = {\n SelectedName,\n Selected,\n NamesSet,",
"score": 0.7929295897483826
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": "import { getState } from '../store';\nimport { getSelectedFile, getSelectedFileName } from '../store/filesSlice';\nimport { useAppSelector } from '../store/hooks';\nconst Selected = () => useAppSelector(getSelectedFile);\nconst SelectedName = () => useAppSelector(getSelectedFileName);\nconst NamesSet = () =>\n useAppSelector(({ files, vault }) => new Set(files.list.concat(vault.list)));\nconst NamesWithUnsaved = () =>\n useAppSelector(({ files, vault }) =>\n files.list.map((name) => {",
"score": 0.7918639779090881
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}",
"score": 0.7754314541816711
}
] | typescript | const { rename } = useFilesMutations(); |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)}
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
const { name, | content } = useFile.Selected(); |
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.8586292266845703
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": " return fileInFiles !== fileInVault;\n });\nconst Exports = () => {\n const { files, list } = getState().vault;\n return list.map((name) => ({ name, content: files[name] }));\n};\nconst useFile = {\n SelectedName,\n Selected,\n NamesSet,",
"score": 0.8383677005767822
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}",
"score": 0.8378989696502686
},
{
"filename": "src/components/Item.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ItemProps extends ComponentProps<'div'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n iconClassName?: string;\n labelClassName?: string;\n selected?: boolean;\n}\nconst Item = (props: ItemProps): JSX.Element => {\n const {\n icon: Icon,",
"score": 0.835731565952301
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": "const Prompt = forwardRef<PromptRef, PromptProps>((props, ref): JSX.Element => {\n const [{ dirty, command }, setCommand] = useState({\n dirty: false,\n command: '',\n });\n const inputRef = useRef<HTMLInputElement>(null);\n const history = useCommandHistory();\n useImperativeHandle(ref, () => ({\n focusWith: (key) => {\n if (key)",
"score": 0.8325977325439453
}
] | typescript | content } = useFile.Selected(); |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
| onReturn={(input) => { |
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 0.8755908012390137
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " <p className=\"overflow-ellipsis whitespace-nowrap text-sm opacity-50\">\n Python commands go here! More options? →\n </p>\n </div>\n )}\n <input\n ref={inputRef}\n className=\"w-full bg-transparent py-2 pr-2 font-mono text-sm outline-none\"\n onChange={(e) => {\n setCommand({ dirty: true, command: e.target.value });",
"score": 0.8530794382095337
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 0.841577410697937
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.8301971554756165
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>",
"score": 0.8286927342414856
}
] | typescript | onReturn={(input) => { |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
< | K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
const { name, content } = useFile.Selected();
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 0.8822253346443176
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.8596405982971191
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.8418518304824829
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.8361669778823853
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 0.828802764415741
}
] | typescript | K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
| <TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()} |
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " <p className=\"overflow-ellipsis whitespace-nowrap text-sm opacity-50\">\n Python commands go here! More options? →\n </p>\n </div>\n )}\n <input\n ref={inputRef}\n className=\"w-full bg-transparent py-2 pr-2 font-mono text-sm outline-none\"\n onChange={(e) => {\n setCommand({ dirty: true, command: e.target.value });",
"score": 0.7995069026947021
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.7745524644851685
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.7739807367324829
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " </div>\n ) : (\n <input\n autoFocus\n className=\"w-fit rounded-lg bg-slate-800 bg-transparent p-2 outline-none ring-2 ring-slate-600\"\n onBlur={() => {\n let newName = newFileName?.trim();\n setEditing(false);\n setNewFileName(undefined);\n if (",
"score": 0.7723973989486694
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " return (\n <section className=\"windowed h-full w-full\">\n <MonacoEditor\n defaultLanguage=\"python\"\n onChange={(value) =>\n value !== undefined ? props.onChange(value) : null\n }\n onMount={(editor) => (ref.current = editor)}\n options={{\n fontSize: 14,",
"score": 0.7722548842430115
}
] | typescript | <TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()} |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
| {files.map(({ name, unsaved }) => (
<FileItem
key={name} |
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 0.8651307821273804
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.8259509801864624
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.8051022291183472
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 0.7951511144638062
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>",
"score": 0.7852158546447754
}
] | typescript | {files.map(({ name, unsaved }) => (
<FileItem
key={name} |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
< | FileUploader
icon={ArrowUpTrayIcon} |
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>",
"score": 0.8055540323257446
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.7934885025024414
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " const { update, save } = useFilesMutations();\n const { name, content } = useFile.Selected();\n useLayoutEffect(() => {\n document.title = `${name ? `${name} | ` : ''}Glide`;\n }, [name]);\n if (name === undefined || content === undefined) return null;\n return (\n <CoreEditor\n {...props}\n onChange={update}",
"score": 0.7901608943939209
},
{
"filename": "src/components/Item.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ItemProps extends ComponentProps<'div'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n iconClassName?: string;\n labelClassName?: string;\n selected?: boolean;\n}\nconst Item = (props: ItemProps): JSX.Element => {\n const {\n icon: Icon,",
"score": 0.7875485420227051
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " children: ReactNode;\n onClick?: MouseEventHandler<HTMLButtonElement>;\n className?: string;\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n iconClassName?: string;\n}\nconst MenuItem = (props: MenuItemProps): JSX.Element => (\n <Menu.Item>\n {({ active }) => (\n <button",
"score": 0.7699986100196838
}
] | typescript | FileUploader
icon={ArrowUpTrayIcon} |
import {
loadPyodide,
PyodideInterface,
PyProxy,
PyProxyAwaitable,
PyProxyCallable,
PyProxyDict,
} from 'pyodide';
import consoleScript from '../assets/console.py';
/**
* @see https://pyodide.org/en/stable/usage/api/python-api/console.html#pyodide.console.ConsoleFuture.syntax_check
*/
type SyntaxCheck = 'syntax-error' | 'incomplete' | 'complete';
interface Message<T extends Record<string, unknown>> {
type: keyof T;
payload: any;
}
interface RunExportableData {
code: string;
exports?: { name: string; content: string }[];
}
let pyodide: PyodideInterface;
let interruptBuffer: Uint8Array | null;
let await_fut: PyProxyCallable;
let repr_shorten: PyProxyCallable;
let pyconsole: PyProxy;
let clear_console: PyProxyCallable;
let create_console: PyProxyCallable;
const PS1 = '\u001b[32;1m>>> \u001b[0m' as const;
const PS2 = '\u001b[32m... \u001b[0m' as const;
const RUN_CODE = '\u001b[3m\u001b[32m<run code>\u001b[0m' as const;
const post = {
write: (text: string) => postMessage({ type: 'write', payload: text }),
writeln: (line: string) => postMessage({ type: 'writeln', payload: line }),
error: (message: string) => postMessage({ type: 'error', payload: message }),
system: (message: string) =>
postMessage({ type: 'system', payload: message }),
lock: () => postMessage({ type: 'lock' }),
unlock: () => postMessage({ type: 'unlock' }),
prompt: (newLine = true) => post.write(`${newLine ? '\n' : ''}${PS1}`),
promptPending: () => post.write(PS2),
};
const setUpConsole = (globals?: PyProxyDict) => {
pyconsole?.destroy();
pyconsole = create_console(globals);
};
const setUpREPLEnvironment = () => {
const globals = pyodide.globals.get('dict')();
pyodide | .runPython(consoleScript, { globals }); |
repr_shorten = globals.get('repr_shorten');
await_fut = globals.get('await_fut');
create_console = globals.get('create_console');
clear_console = globals.get('clear_console');
setUpConsole();
return globals.get('BANNER') as string;
};
const preparePyodide = async () => {
const newPyodide = await loadPyodide();
newPyodide.setStdout({ batched: post.writeln });
newPyodide.setStderr({ batched: post.error });
pyodide = newPyodide;
if (interruptBuffer) pyodide.setInterruptBuffer(interruptBuffer);
/**
* Replaces Pyodide's `js` import with a stub `object`. This must also be
* paired with some `del sys.modules['js']` in Pyodide's initialisation.
*/
pyodide.registerJsModule('js', {});
const banner = setUpREPLEnvironment();
post.writeln(banner);
post.prompt(false);
post.unlock();
return newPyodide;
};
const prepareExports = (exports?: { name: string; content: string }[]) => {
let newExports = new Set<string>();
exports?.forEach(({ name, content }) => {
pyodide.FS.writeFile(name, content, { encoding: 'utf-8' });
newExports.add(name);
});
const oldExports = pyodide.FS.readdir('.') as string[];
oldExports.forEach((name) => {
if (name === '.' || name === '..' || newExports.has(name)) return;
pyodide.FS.unlink(name);
});
};
/**
* Pyodide may sometimes not catch `RecursionError`s and excessively
* recursive code spills as JavaScript `RangeError`, causing Pyodide to
* fatally crash. We need to restart Pyodide in this case.
* @see https://github.com/pyodide/pyodide/issues/951
*/
const handleRangeErrorAndRestartPyodide = async (error: unknown) => {
if (!(error instanceof RangeError)) return;
post.system(
'\nOops, something happened and we have to restart the interpreter. ' +
"Don't worry, it's not your fault. " +
'You may continue once you see the prompt again.\n',
);
await preparePyodide();
};
const listeners = {
initialize: async (newInterruptBuffer?: Uint8Array) => {
pyodide ??= await preparePyodide();
if (!newInterruptBuffer) return;
pyodide.setInterruptBuffer(newInterruptBuffer);
interruptBuffer = newInterruptBuffer;
},
run: async ({ code, exports }: RunExportableData) => {
pyodide ??= await preparePyodide();
post.writeln(RUN_CODE);
try {
post.lock();
prepareExports(exports);
await pyodide.loadPackagesFromImports(code);
const globals = pyodide.globals.get('dict')();
/**
* `await pyodide.runPythonAsync(code)` is not used because it raises
* an uncatchable `PythonError` when Pyodide emits a `KeyboardInterrupt`.
* @see https://github.com/pyodide/pyodide/issues/2141
*/
const result = pyodide.runPython(code, { globals });
setUpConsole(globals);
post.writeln(result?.toString());
} catch (error) {
if (!(error instanceof Error)) throw error;
post.error(error.message);
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
post.unlock();
}
},
replClear: async () => {
try {
clear_console(pyconsole);
await await_fut(pyconsole.push(''));
} finally {
post.error('\nKeyboardInterrupt');
post.prompt();
}
},
replInput: async ({ code, exports }: RunExportableData) => {
post.writeln(code);
const future = pyconsole.push(code) as PyProxy;
const status = future.syntax_check as SyntaxCheck;
switch (status) {
case 'syntax-error':
post.error(future.formatted_error.trimEnd());
post.prompt();
return;
case 'incomplete':
post.promptPending();
return;
case 'complete':
break;
default:
throw new Error(`Unexpected type: ${status}`);
}
prepareExports(exports);
const wrapped = await_fut(future) as PyProxyAwaitable;
try {
const [value] = await wrapped;
if (value !== undefined) {
const repr = repr_shorten.callKwargs(value, {
separator: '\n<long output truncated>\n',
}) as string;
post.writeln(repr);
}
if (pyodide.isPyProxy(value)) value.destroy();
} catch (error) {
if (!(error instanceof Error)) throw error;
const message = future.formatted_error || error.message;
post.error(message.trimEnd());
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
future.destroy();
wrapped.destroy();
}
},
};
onmessage = async (event: MessageEvent<Message<typeof listeners>>) => {
listeners[event.data.type]?.(event.data.payload);
};
| src/workers/interpreter.worker.ts | NUSSOC-glide-3ab6925 | [
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " const interpreter = useInterpreter({\n write: (text: string) => consoleRef.current?.write(text),\n writeln: (text: string) => consoleRef.current?.append(text),\n error: (text: string) => consoleRef.current?.error(text),\n system: (text: string) => consoleRef.current?.system(text),\n exports: useFile.Exports,\n lock: () => setRunning(true),\n unlock: () => setRunning(false),\n });\n return (",
"score": 0.7041215896606445
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": " resetInterruptBuffer();\n workerRef.current?.postMessage({\n type: 'replInput',\n payload: { code, exports: callbacks.exports?.() },\n });\n },\n restart: () => {\n callbacks.system('\\nOkies! Restarting interpreter...\\n');\n restartInterpreter();\n },",
"score": 0.6931031942367554
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": "const useInterpreter = (callbacks: Callbacks): Interpreter => {\n const workerRef = useRef<Worker>();\n const interruptBufferRef = useRef<Uint8Array>();\n const setUpInterpreterWorker = () => {\n const worker = new Worker(\n new URL('../workers/interpreter.worker.ts', import.meta.url),\n );\n worker.onmessage = (event: MessageEvent<Message<Callbacks>>) => {\n callbacks[event.data.type]?.(event.data.payload);\n };",
"score": 0.6737686991691589
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }\n xterm.onKey(({ key }) => {\n if (!(isASCIIPrintable(key) || key >= '\\u00a0')) return;\n promptRef.current?.focusWith(key);\n });\n xterm.open(terminal);\n fitAddon.fit();\n xtermRef.current = xterm;\n fitAddonRef.current = fitAddon;\n return () => xterm.dispose();",
"score": 0.6637636423110962
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": " setUpInterpreterWorker();\n }, []);\n const resetInterruptBuffer = () => {\n if (!interruptBufferRef.current) return;\n interruptBufferRef.current[0] = 0;\n };\n const restartInterpreter = () => {\n workerRef.current?.terminate();\n setUpInterpreterWorker();\n };",
"score": 0.663042426109314
}
] | typescript | .runPython(consoleScript, { globals }); |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
| onUpload={(name, content) => { |
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.8205753564834595
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>",
"score": 0.8152488470077515
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " const { update, save } = useFilesMutations();\n const { name, content } = useFile.Selected();\n useLayoutEffect(() => {\n document.title = `${name ? `${name} | ` : ''}Glide`;\n }, [name]);\n if (name === undefined || content === undefined) return null;\n return (\n <CoreEditor\n {...props}\n onChange={update}",
"score": 0.8108710646629333
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " return (\n <section className=\"windowed h-full w-full\">\n <MonacoEditor\n defaultLanguage=\"python\"\n onChange={(value) =>\n value !== undefined ? props.onChange(value) : null\n }\n onMount={(editor) => (ref.current = editor)}\n options={{\n fontSize: 14,",
"score": 0.7889771461486816
},
{
"filename": "src/components/Item.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ItemProps extends ComponentProps<'div'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n iconClassName?: string;\n labelClassName?: string;\n selected?: boolean;\n}\nconst Item = (props: ItemProps): JSX.Element => {\n const {\n icon: Icon,",
"score": 0.7810534238815308
}
] | typescript | onUpload={(name, content) => { |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, | unsaved }) => (
<FileItem
key={name} |
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 0.8627007007598877
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.821935772895813
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.8041837215423584
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 0.798534095287323
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 0.7940789461135864
}
] | typescript | unsaved }) => (
<FileItem
key={name} |
import { useEffect, useState } from 'react';
import { BuildingLibraryIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import FileName from './FileName';
import K from './Hotkey';
import Item from './Item';
import Library from './Library';
const isMac = navigator.platform.startsWith('Mac');
const Navigator = (): JSX.Element => {
const [openLibrary, setOpenLibrary] = useState(true);
const name = useFile.SelectedName();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = isMac ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 'o') {
e.preventDefault();
setOpenLibrary(true);
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
return (
<>
<nav className="flex items-center justify-between space-x-2">
<FileName />
<div className="flex flex-row items-center space-x-2">
{name && (
<Item
className="text-slate-400"
onClick={() => {
window.dispatchEvent(
new KeyboardEvent('keydown', {
key: 's',
metaKey: isMac,
ctrlKey: !isMac,
}),
);
}}
>
Save < | K of="Mod+S" />
</Item>
)} |
<Item
className="text-slate-400"
icon={BuildingLibraryIcon}
onClick={() => setOpenLibrary(true)}
>
Library <K of="Mod+O" />
</Item>
</div>
</nav>
<Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
);
};
export default Navigator;
| src/components/Navigator.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " if (e.key === 'ArrowDown' && (!command || !dirty)) {\n e.preventDefault();\n setCommand({ dirty: false, command: history.next() ?? '' });\n }\n }}\n value={command}\n />\n </div>\n </div>\n );",
"score": 0.7972042560577393
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuItem icon={TrashIcon} onClick={props.onClickClearConsole}>\n Clear output\n </MenuItem>\n </div>\n </Menu.Items>\n </Transition>\n </Menu>\n );\n};\nexport default TerminalMenu;",
"score": 0.7643356323242188
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 0.7412532567977905
},
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": " props.className ?? ''\n }`}\n >\n {Icon && <Icon className=\"-ml-1 mr-2 h-5 w-5\" />}\n {props.children}\n </button>\n );\n};\nexport default Button;",
"score": 0.7370111346244812
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " >\n <UnsavedBadge />\n </Transition>\n </div>\n );\n};\nexport default FileName;",
"score": 0.7327824831008911
}
] | typescript | K of="Mod+S" />
</Item>
)} |
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
| <K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
const { name, content } = useFile.Selected();
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 0.8945493698120117
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.8536758422851562
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.8485657572746277
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.8391995429992676
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 0.8350261449813843
}
] | typescript | <K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)} |
import { useEffect, useState } from 'react';
import { BuildingLibraryIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import FileName from './FileName';
import K from './Hotkey';
import Item from './Item';
import Library from './Library';
const isMac = navigator.platform.startsWith('Mac');
const Navigator = (): JSX.Element => {
const [openLibrary, setOpenLibrary] = useState(true);
const name = useFile.SelectedName();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = isMac ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 'o') {
e.preventDefault();
setOpenLibrary(true);
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
return (
<>
<nav className="flex items-center justify-between space-x-2">
<FileName />
<div className="flex flex-row items-center space-x-2">
{name && (
<Item
className="text-slate-400"
onClick={() => {
window.dispatchEvent(
new KeyboardEvent('keydown', {
key: 's',
metaKey: isMac,
ctrlKey: !isMac,
}),
);
}}
>
| Save <K of="Mod+S" />
</Item>
)} |
<Item
className="text-slate-400"
icon={BuildingLibraryIcon}
onClick={() => setOpenLibrary(true)}
>
Library <K of="Mod+O" />
</Item>
</div>
</nav>
<Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
);
};
export default Navigator;
| src/components/Navigator.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " if (e.key === 'ArrowDown' && (!command || !dirty)) {\n e.preventDefault();\n setCommand({ dirty: false, command: history.next() ?? '' });\n }\n }}\n value={command}\n />\n </div>\n </div>\n );",
"score": 0.8194984197616577
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": " Ctrl: '⌃',\n }\n : {\n Mod: 'Ctrl',\n Alt: 'Alt',\n Shift: 'Shift',\n Ctrl: 'Ctrl',\n };\ntype ConvertibleKeys = keyof typeof CONVERTED_KEYS;\nconst SEPARATOR = '+' as const;",
"score": 0.7623580694198608
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "interface HotkeyProps {\n of: string;\n className?: string;\n}\nconst isMac = navigator.platform.startsWith('Mac');\nconst CONVERTED_KEYS = isMac\n ? {\n Mod: '⌘',\n Alt: '⌥',\n Shift: '⇧',",
"score": 0.7511075735092163
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuItem icon={TrashIcon} onClick={props.onClickClearConsole}>\n Clear output\n </MenuItem>\n </div>\n </Menu.Items>\n </Transition>\n </Menu>\n );\n};\nexport default TerminalMenu;",
"score": 0.7389297485351562
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand(\n produce((draft) => {\n draft.command = `${command}\\t`;\n }),\n );\n }\n if (e.key === 'ArrowUp' && (!command || !dirty)) {\n e.preventDefault();\n setCommand({ dirty: false, command: history.previous() ?? '' });\n }",
"score": 0.7351808547973633
}
] | typescript | Save <K of="Mod+S" />
</Item>
)} |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
| <Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)} |
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>",
"score": 0.8507059216499329
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.8427780866622925
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 0.8412883877754211
},
{
"filename": "src/components/Item.tsx",
"retrieved_chunk": " } ${props.className ?? ''}`}\n role=\"button\"\n >\n {Icon && (\n <Icon\n className={`w-5 flex-shrink-0 opacity-80 ${\n !selected ? 'group-hover:opacity-90' : ''\n } ${iconClassName ?? ''}`}\n />\n )}",
"score": 0.8339700102806091
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.816889762878418
}
] | typescript | <Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)} |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload= | {(name, content) => { |
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>",
"score": 0.8291113376617432
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.7951958179473877
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " </div>\n </nav>\n <Library onClose={() => setOpenLibrary(false)} open={openLibrary} />\n </>\n );\n};\nexport default Navigator;",
"score": 0.7855599522590637
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 0.7854648232460022
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuItem icon={TrashIcon} onClick={props.onClickClearConsole}>\n Clear output\n </MenuItem>\n </div>\n </Menu.Items>\n </Transition>\n </Menu>\n );\n};\nexport default TerminalMenu;",
"score": 0.7842801213264465
}
] | typescript | {(name, content) => { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.